@dxos/shell 0.4.10-main.61a4cf6 → 0.4.10-main.6f15454
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.
- package/dist/bundle/{index-DY0hiAob.mjs → index-D-0DqO_p.mjs} +38 -22
- package/dist/bundle/index-D-0DqO_p.mjs.map +1 -0
- package/dist/bundle/{index-_bedgWKd.mjs → index-DrUA2jlt.mjs} +146 -139
- package/dist/bundle/index-DrUA2jlt.mjs.map +1 -0
- package/dist/bundle/shell.mjs +1 -1
- package/dist/bundle/shell.umd.js +12 -12
- package/dist/bundle/shell.umd.js.map +1 -1
- package/package.json +21 -21
- package/dist/bundle/index-DY0hiAob.mjs.map +0 -1
- package/dist/bundle/index-_bedgWKd.mjs.map +0 -1
package/dist/bundle/shell.umd.js
CHANGED
|
@@ -111,7 +111,7 @@ Check the top-level render call using <`+lt+">.")}return at}}function Nn(Pe,at){
|
|
|
111
111
|
*/var import_buffer$1=__toESM(require_buffer());globalThis.global=globalThis,globalThis.Buffer=import_buffer$1.Buffer,globalThis.process=process$1;var import_util=__toESM(require_util()),import_util2=__toESM(require_util());import_util.default,import_util2.callbackify;var export_inspect=import_util2.inspect;import_util2.promisify;var lodash_defaultsdeep={exports:{}};lodash_defaultsdeep.exports,function($,I){var U=200,q="__lodash_hash_undefined__",G=800,K=16,Y=9007199254740991,J="[object Arguments]",X="[object Array]",Z="[object AsyncFunction]",Q="[object Boolean]",ee="[object Date]",te="[object Error]",ne="[object Function]",ie="[object GeneratorFunction]",oe="[object Map]",ce="[object Number]",fe="[object Null]",se="[object Object]",de="[object Proxy]",ue="[object RegExp]",pe="[object Set]",ve="[object String]",me="[object Undefined]",be="[object WeakMap]",_e="[object ArrayBuffer]",Se="[object DataView]",xe="[object Float32Array]",ke="[object Float64Array]",De="[object Int8Array]",Be="[object Int16Array]",Ve="[object Int32Array]",nt="[object Uint8Array]",ot="[object Uint8ClampedArray]",ft="[object Uint16Array]",it="[object Uint32Array]",ut=/[\\^$.*+?()[\]{}|]/g,et=/^\[object .+?Constructor\]$/,Ue=/^(?:0|[1-9]\d*)$/,We={};We[xe]=We[ke]=We[De]=We[Be]=We[Ve]=We[nt]=We[ot]=We[ft]=We[it]=!0,We[J]=We[X]=We[_e]=We[Q]=We[Se]=We[ee]=We[te]=We[ne]=We[oe]=We[ce]=We[se]=We[ue]=We[pe]=We[ve]=We[be]=!1;var tt=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,vt=typeof self=="object"&&self&&self.Object===Object&&self,je=tt||vt||Function("return this")(),ze=I&&!I.nodeType&&I,Ae=ze&&!0&&$&&!$.nodeType&&$,Re=Ae&&Ae.exports===ze,Ce=Re&&tt.process,ge=function(){try{var $e=Ae&&Ae.require&&Ae.require("util").types;return $e||Ce&&Ce.binding&&Ce.binding("util")}catch{}}(),ye=ge&&ge.isTypedArray;function Me($e,Fe,Xe){switch(Xe.length){case 0:return $e.call(Fe);case 1:return $e.call(Fe,Xe[0]);case 2:return $e.call(Fe,Xe[0],Xe[1]);case 3:return $e.call(Fe,Xe[0],Xe[1],Xe[2])}return $e.apply(Fe,Xe)}function Ke($e,Fe){for(var Xe=-1,_t=Array($e);++Xe<$e;)_t[Xe]=Fe(Xe);return _t}function st($e){return function(Fe){return $e(Fe)}}function dt($e,Fe){return $e==null?void 0:$e[Fe]}function $t($e,Fe){return function(Xe){return $e(Fe(Xe))}}var Et=Array.prototype,rt=Function.prototype,jt=Object.prototype,Gt=je["__core-js_shared__"],At=rt.toString,zt=jt.hasOwnProperty,nn=function(){var $e=/[^.]+$/.exec(Gt&&Gt.keys&&Gt.keys.IE_PROTO||"");return $e?"Symbol(src)_1."+$e:""}(),St=jt.toString,Ut=At.call(Object),le=RegExp("^"+At.call(zt).replace(ut,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),re=Re?je.Buffer:void 0,ae=je.Symbol,he=je.Uint8Array,we=re?re.allocUnsafe:void 0,Ee=$t(Object.getPrototypeOf,Object),Le=Object.create,bt=jt.propertyIsEnumerable,Lt=Et.splice,Ct=ae?ae.toStringTag:void 0,It=function(){try{var $e=wt(Object,"defineProperty");return $e({},"",{}),$e}catch{}}(),Tt=re?re.isBuffer:void 0,Sn=Math.max,gn=Date.now,pn=wt(je,"Map"),vn=wt(Object,"create"),Tn=function(){function $e(){}return function(Fe){if(!Qt(Fe))return{};if(Le)return Le(Fe);$e.prototype=Fe;var Xe=new $e;return $e.prototype=void 0,Xe}}();function dn($e){var Fe=-1,Xe=$e==null?0:$e.length;for(this.clear();++Fe<Xe;){var _t=$e[Fe];this.set(_t[0],_t[1])}}function Pn(){this.__data__=vn?vn(null):{},this.size=0}function $n($e){var Fe=this.has($e)&&delete this.__data__[$e];return this.size-=Fe?1:0,Fe}function Vn($e){var Fe=this.__data__;if(vn){var Xe=Fe[$e];return Xe===q?void 0:Xe}return zt.call(Fe,$e)?Fe[$e]:void 0}function Nn($e){var Fe=this.__data__;return vn?Fe[$e]!==void 0:zt.call(Fe,$e)}function Fn($e,Fe){var Xe=this.__data__;return this.size+=this.has($e)?0:1,Xe[$e]=vn&&Fe===void 0?q:Fe,this}dn.prototype.clear=Pn,dn.prototype.delete=$n,dn.prototype.get=Vn,dn.prototype.has=Nn,dn.prototype.set=Fn;function fn($e){var Fe=-1,Xe=$e==null?0:$e.length;for(this.clear();++Fe<Xe;){var _t=$e[Fe];this.set(_t[0],_t[1])}}function Gn(){this.__data__=[],this.size=0}function bn($e){var Fe=this.__data__,Xe=ln(Fe,$e);if(Xe<0)return!1;var _t=Fe.length-1;return Xe==_t?Fe.pop():Lt.call(Fe,Xe,1),--this.size,!0}function Kn($e){var Fe=this.__data__,Xe=ln(Fe,$e);return Xe<0?void 0:Fe[Xe][1]}function He($e){return ln(this.__data__,$e)>-1}function pt($e,Fe){var Xe=this.__data__,_t=ln(Xe,$e);return _t<0?(++this.size,Xe.push([$e,Fe])):Xe[_t][1]=Fe,this}fn.prototype.clear=Gn,fn.prototype.delete=bn,fn.prototype.get=Kn,fn.prototype.has=He,fn.prototype.set=pt;function kt($e){var Fe=-1,Xe=$e==null?0:$e.length;for(this.clear();++Fe<Xe;){var _t=$e[Fe];this.set(_t[0],_t[1])}}function Pe(){this.size=0,this.__data__={hash:new dn,map:new(pn||fn),string:new dn}}function at($e){var Fe=gt(this,$e).delete($e);return this.size-=Fe?1:0,Fe}function lt($e){return gt(this,$e).get($e)}function xt($e){return gt(this,$e).has($e)}function Rt($e,Fe){var Xe=gt(this,$e),_t=Xe.size;return Xe.set($e,Fe),this.size+=Xe.size==_t?0:1,this}kt.prototype.clear=Pe,kt.prototype.delete=at,kt.prototype.get=lt,kt.prototype.has=xt,kt.prototype.set=Rt;function Dt($e){var Fe=this.__data__=new fn($e);this.size=Fe.size}function Mt(){this.__data__=new fn,this.size=0}function Ot($e){var Fe=this.__data__,Xe=Fe.delete($e);return this.size=Fe.size,Xe}function Xt($e){return this.__data__.get($e)}function Zt($e){return this.__data__.has($e)}function Kt($e,Fe){var Xe=this.__data__;if(Xe instanceof fn){var _t=Xe.__data__;if(!pn||_t.length<U-1)return _t.push([$e,Fe]),this.size=++Xe.size,this;Xe=this.__data__=new kt(_t)}return Xe.set($e,Fe),this.size=Xe.size,this}Dt.prototype.clear=Mt,Dt.prototype.delete=Ot,Dt.prototype.get=Xt,Dt.prototype.has=Zt,Dt.prototype.set=Kt;function an($e,Fe){var Xe=yt($e),_t=!Xe&&Qe($e),Bt=!Xe&&!_t&&Wt($e),Nt=!Xe&&!_t&&!Bt&&kn($e),qt=Xe||_t||Bt||Nt,Vt=qt?Ke($e.length,String):[],Jt=Vt.length;for(var En in $e)(Fe||zt.call($e,En))&&!(qt&&(En=="length"||Bt&&(En=="offset"||En=="parent")||Nt&&(En=="buffer"||En=="byteLength"||En=="byteOffset")||Yt(En,Jt)))&&Vt.push(En);return Vt}function xn($e,Fe,Xe){(Xe!==void 0&&!Ne($e[Fe],Xe)||Xe===void 0&&!(Fe in $e))&&Bn($e,Fe,Xe)}function Yn($e,Fe,Xe){var _t=$e[Fe];(!(zt.call($e,Fe)&&Ne(_t,Xe))||Xe===void 0&&!(Fe in $e))&&Bn($e,Fe,Xe)}function ln($e,Fe){for(var Xe=$e.length;Xe--;)if(Ne($e[Xe][0],Fe))return Xe;return-1}function Bn($e,Fe,Xe){Fe=="__proto__"&&It?It($e,Fe,{configurable:!0,enumerable:!0,value:Xe,writable:!0}):$e[Fe]=Xe}var jn=ht();function An($e){return $e==null?$e===void 0?me:fe:Ct&&Ct in Object($e)?Ft($e):er($e)}function Un($e){return un($e)&&An($e)==J}function Qn($e){if(!Qt($e)||sn($e))return!1;var Fe=hn($e)?le:et;return Fe.test(qn($e))}function ir($e){return un($e)&&rn($e.length)&&!!We[An($e)]}function ar($e){if(!Qt($e))return Hn($e);var Fe=wn($e),Xe=[];for(var _t in $e)_t=="constructor"&&(Fe||!zt.call($e,_t))||Xe.push(_t);return Xe}function zn($e,Fe,Xe,_t,Bt){$e!==Fe&&jn(Fe,function(Nt,qt){if(Bt||(Bt=new Dt),Qt(Nt))or($e,Fe,qt,Xe,zn,_t,Bt);else{var Vt=_t?_t(Mn($e,qt),Nt,qt+"",$e,Fe,Bt):void 0;Vt===void 0&&(Vt=Nt),xn($e,qt,Vt)}},Rn)}function or($e,Fe,Xe,_t,Bt,Nt,qt){var Vt=Mn($e,Xe),Jt=Mn(Fe,Xe),En=qt.get(Jt);if(En){xn($e,Xe,En);return}var Cn=Nt?Nt(Vt,Jt,Xe+"",$e,Fe,qt):void 0,tr=Cn===void 0;if(tr){var fr=yt(Jt),ur=!fr&&Wt(Jt),vr=!fr&&!ur&&kn(Jt);Cn=Jt,fr||ur||vr?yt(Vt)?Cn=Vt:tn(Vt)?Cn=Ze(Vt):ur?(tr=!1,Cn=qe(Jt,!0)):vr?(tr=!1,Cn=Ye(Jt,!0)):Cn=[]:yn(Jt)||Qe(Jt)?(Cn=Vt,Qe(Vt)?Cn=mn(Vt):(!Qt(Vt)||hn(Vt))&&(Cn=Ht(Jt))):tr=!1}tr&&(qt.set(Jt,Cn),Bt(Cn,Jt,_t,Nt,qt),qt.delete(Jt)),xn($e,Xe,Cn)}function nr($e,Fe){return cr(Wn($e,Fe,Ie),$e+"")}var Te=It?function($e,Fe){return It($e,"toString",{configurable:!0,enumerable:!1,value:Dn(Fe),writable:!0})}:Ie;function qe($e,Fe){if(Fe)return $e.slice();var Xe=$e.length,_t=we?we(Xe):new $e.constructor(Xe);return $e.copy(_t),_t}function Oe($e){var Fe=new $e.constructor($e.byteLength);return new he(Fe).set(new he($e)),Fe}function Ye($e,Fe){var Xe=Fe?Oe($e.buffer):$e.buffer;return new $e.constructor(Xe,$e.byteOffset,$e.length)}function Ze($e,Fe){var Xe=-1,_t=$e.length;for(Fe||(Fe=Array(_t));++Xe<_t;)Fe[Xe]=$e[Xe];return Fe}function Ge($e,Fe,Xe,_t){var Bt=!Xe;Xe||(Xe={});for(var Nt=-1,qt=Fe.length;++Nt<qt;){var Vt=Fe[Nt],Jt=_t?_t(Xe[Vt],$e[Vt],Vt,Xe,$e):void 0;Jt===void 0&&(Jt=$e[Vt]),Bt?Bn(Xe,Vt,Jt):Yn(Xe,Vt,Jt)}return Xe}function ct($e){return nr(function(Fe,Xe){var _t=-1,Bt=Xe.length,Nt=Bt>1?Xe[Bt-1]:void 0,qt=Bt>2?Xe[2]:void 0;for(Nt=$e.length>3&&typeof Nt=="function"?(Bt--,Nt):void 0,qt&&en(Xe[0],Xe[1],qt)&&(Nt=Bt<3?void 0:Nt,Bt=1),Fe=Object(Fe);++_t<Bt;){var Vt=Xe[_t];Vt&&$e(Fe,Vt,_t,Nt)}return Fe})}function ht($e){return function(Fe,Xe,_t){for(var Bt=-1,Nt=Object(Fe),qt=_t(Fe),Vt=qt.length;Vt--;){var Jt=qt[$e?Vt:++Bt];if(Xe(Nt[Jt],Jt,Nt)===!1)break}return Fe}}function mt($e,Fe,Xe,_t,Bt,Nt){return Qt($e)&&Qt(Fe)&&(Nt.set(Fe,$e),zn($e,Fe,void 0,mt,Nt),Nt.delete(Fe)),$e}function gt($e,Fe){var Xe=$e.__data__;return cn(Fe)?Xe[typeof Fe=="string"?"string":"hash"]:Xe.map}function wt($e,Fe){var Xe=dt($e,Fe);return Qn(Xe)?Xe:void 0}function Ft($e){var Fe=zt.call($e,Ct),Xe=$e[Ct];try{$e[Ct]=void 0;var _t=!0}catch{}var Bt=St.call($e);return _t&&(Fe?$e[Ct]=Xe:delete $e[Ct]),Bt}function Ht($e){return typeof $e.constructor=="function"&&!wn($e)?Tn(Ee($e)):{}}function Yt($e,Fe){var Xe=typeof $e;return Fe=Fe??Y,!!Fe&&(Xe=="number"||Xe!="symbol"&&Ue.test($e))&&$e>-1&&$e%1==0&&$e<Fe}function en($e,Fe,Xe){if(!Qt(Xe))return!1;var _t=typeof Fe;return(_t=="number"?Pt(Xe)&&Yt(Fe,Xe.length):_t=="string"&&Fe in Xe)?Ne(Xe[Fe],$e):!1}function cn($e){var Fe=typeof $e;return Fe=="string"||Fe=="number"||Fe=="symbol"||Fe=="boolean"?$e!=="__proto__":$e===null}function sn($e){return!!nn&&nn in $e}function wn($e){var Fe=$e&&$e.constructor,Xe=typeof Fe=="function"&&Fe.prototype||jt;return $e===Xe}function Hn($e){var Fe=[];if($e!=null)for(var Xe in Object($e))Fe.push(Xe);return Fe}function er($e){return St.call($e)}function Wn($e,Fe,Xe){return Fe=Sn(Fe===void 0?$e.length-1:Fe,0),function(){for(var _t=arguments,Bt=-1,Nt=Sn(_t.length-Fe,0),qt=Array(Nt);++Bt<Nt;)qt[Bt]=_t[Fe+Bt];Bt=-1;for(var Vt=Array(Fe+1);++Bt<Fe;)Vt[Bt]=_t[Bt];return Vt[Fe]=Xe(qt),Me($e,this,Vt)}}function Mn($e,Fe){if(!(Fe==="constructor"&&typeof $e[Fe]=="function")&&Fe!="__proto__")return $e[Fe]}var cr=sr(Te);function sr($e){var Fe=0,Xe=0;return function(){var _t=gn(),Bt=K-(_t-Xe);if(Xe=_t,Bt>0){if(++Fe>=G)return arguments[0]}else Fe=0;return $e.apply(void 0,arguments)}}function qn($e){if($e!=null){try{return At.call($e)}catch{}try{return $e+""}catch{}}return""}function Ne($e,Fe){return $e===Fe||$e!==$e&&Fe!==Fe}var Qe=Un(function(){return arguments}())?Un:function($e){return un($e)&&zt.call($e,"callee")&&!bt.call($e,"callee")},yt=Array.isArray;function Pt($e){return $e!=null&&rn($e.length)&&!hn($e)}function tn($e){return un($e)&&Pt($e)}var Wt=Tt||Je;function hn($e){if(!Qt($e))return!1;var Fe=An($e);return Fe==ne||Fe==ie||Fe==Z||Fe==de}function rn($e){return typeof $e=="number"&&$e>-1&&$e%1==0&&$e<=Y}function Qt($e){var Fe=typeof $e;return $e!=null&&(Fe=="object"||Fe=="function")}function un($e){return $e!=null&&typeof $e=="object"}function yn($e){if(!un($e)||An($e)!=se)return!1;var Fe=Ee($e);if(Fe===null)return!0;var Xe=zt.call(Fe,"constructor")&&Fe.constructor;return typeof Xe=="function"&&Xe instanceof Xe&&At.call(Xe)==Ut}var kn=ye?st(ye):ir;function mn($e){return Ge($e,Rn($e))}var On=nr(function($e){return $e.push(void 0,mt),Me(Ln,void 0,$e)});function Rn($e){return Pt($e)?an($e,!0):ar($e)}var Ln=ct(function($e,Fe,Xe,_t){zn($e,Fe,Xe,_t)});function Dn($e){return function(){return $e}}function Ie($e){return $e}function Je(){return!1}$.exports=On}(lodash_defaultsdeep,lodash_defaultsdeep.exports);var lodash_defaultsdeepExports=lodash_defaultsdeep.exports;const defaultsDeep=getDefaultExportFromCjs(lodash_defaultsdeepExports);var import_buffer=__toESM(require_buffer()),export_Buffer=import_buffer.Buffer,invariant=($,I,U)=>{if($)return;if(I!=null&&I.startsWith("BUG"))debugger;let q="invariant violation";throw I&&(q+=`: ${I}`),U!=null&&U.A&&(q+=` [${U.A[0]}]`),U!=null&&U.F&&(q+=` at ${getRelativeFilename$1(U.F)}:${U.L}`),new InvariantViolation(q)},InvariantViolation=class extends Error{constructor($){super($),Object.setPrototypeOf(this,new.target.prototype)}},getRelativeFilename$1=$=>{const I=$.match(/.+\/(packages\/.+\/.+)/);if(I){const[,U]=I;return U}return $},require_events=__commonJS({"node_modules/.pnpm/events@3.3.0/node_modules/events/events.js"($,I){var U=typeof Reflect=="object"?Reflect:null,q=U&&typeof U.apply=="function"?U.apply:function(me,be,_e){return Function.prototype.apply.call(me,be,_e)},G;U&&typeof U.ownKeys=="function"?G=U.ownKeys:Object.getOwnPropertySymbols?G=function(me){return Object.getOwnPropertyNames(me).concat(Object.getOwnPropertySymbols(me))}:G=function(me){return Object.getOwnPropertyNames(me)};function K(ve){console&&console.warn&&console.warn(ve)}var Y=Number.isNaN||function(me){return me!==me};function J(){J.init.call(this)}I.exports=J,I.exports.once=de,J.EventEmitter=J,J.prototype._events=void 0,J.prototype._eventsCount=0,J.prototype._maxListeners=void 0;var X=10;function Z(ve){if(typeof ve!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof ve)}Object.defineProperty(J,"defaultMaxListeners",{enumerable:!0,get:function(){return X},set:function(ve){if(typeof ve!="number"||ve<0||Y(ve))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+ve+".");X=ve}}),J.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},J.prototype.setMaxListeners=function(me){if(typeof me!="number"||me<0||Y(me))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+me+".");return this._maxListeners=me,this};function Q(ve){return ve._maxListeners===void 0?J.defaultMaxListeners:ve._maxListeners}J.prototype.getMaxListeners=function(){return Q(this)},J.prototype.emit=function(me){for(var be=[],_e=1;_e<arguments.length;_e++)be.push(arguments[_e]);var Se=me==="error",xe=this._events;if(xe!==void 0)Se=Se&&xe.error===void 0;else if(!Se)return!1;if(Se){var ke;if(be.length>0&&(ke=be[0]),ke instanceof Error)throw ke;var De=new Error("Unhandled error."+(ke?" ("+ke.message+")":""));throw De.context=ke,De}var Be=xe[me];if(Be===void 0)return!1;if(typeof Be=="function")q(Be,this,be);else for(var Ve=Be.length,nt=ce(Be,Ve),_e=0;_e<Ve;++_e)q(nt[_e],this,be);return!0};function ee(ve,me,be,_e){var Se,xe,ke;if(Z(be),xe=ve._events,xe===void 0?(xe=ve._events=Object.create(null),ve._eventsCount=0):(xe.newListener!==void 0&&(ve.emit("newListener",me,be.listener?be.listener:be),xe=ve._events),ke=xe[me]),ke===void 0)ke=xe[me]=be,++ve._eventsCount;else if(typeof ke=="function"?ke=xe[me]=_e?[be,ke]:[ke,be]:_e?ke.unshift(be):ke.push(be),Se=Q(ve),Se>0&&ke.length>Se&&!ke.warned){ke.warned=!0;var De=new Error("Possible EventEmitter memory leak detected. "+ke.length+" "+String(me)+" listeners added. Use emitter.setMaxListeners() to increase limit");De.name="MaxListenersExceededWarning",De.emitter=ve,De.type=me,De.count=ke.length,K(De)}return ve}J.prototype.addListener=function(me,be){return ee(this,me,be,!1)},J.prototype.on=J.prototype.addListener,J.prototype.prependListener=function(me,be){return ee(this,me,be,!0)};function te(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ne(ve,me,be){var _e={fired:!1,wrapFn:void 0,target:ve,type:me,listener:be},Se=te.bind(_e);return Se.listener=be,_e.wrapFn=Se,Se}J.prototype.once=function(me,be){return Z(be),this.on(me,ne(this,me,be)),this},J.prototype.prependOnceListener=function(me,be){return Z(be),this.prependListener(me,ne(this,me,be)),this},J.prototype.removeListener=function(me,be){var _e,Se,xe,ke,De;if(Z(be),Se=this._events,Se===void 0)return this;if(_e=Se[me],_e===void 0)return this;if(_e===be||_e.listener===be)--this._eventsCount===0?this._events=Object.create(null):(delete Se[me],Se.removeListener&&this.emit("removeListener",me,_e.listener||be));else if(typeof _e!="function"){for(xe=-1,ke=_e.length-1;ke>=0;ke--)if(_e[ke]===be||_e[ke].listener===be){De=_e[ke].listener,xe=ke;break}if(xe<0)return this;xe===0?_e.shift():fe(_e,xe),_e.length===1&&(Se[me]=_e[0]),Se.removeListener!==void 0&&this.emit("removeListener",me,De||be)}return this},J.prototype.off=J.prototype.removeListener,J.prototype.removeAllListeners=function(me){var be,_e,Se;if(_e=this._events,_e===void 0)return this;if(_e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):_e[me]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete _e[me]),this;if(arguments.length===0){var xe=Object.keys(_e),ke;for(Se=0;Se<xe.length;++Se)ke=xe[Se],ke!=="removeListener"&&this.removeAllListeners(ke);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(be=_e[me],typeof be=="function")this.removeListener(me,be);else if(be!==void 0)for(Se=be.length-1;Se>=0;Se--)this.removeListener(me,be[Se]);return this};function ie(ve,me,be){var _e=ve._events;if(_e===void 0)return[];var Se=_e[me];return Se===void 0?[]:typeof Se=="function"?be?[Se.listener||Se]:[Se]:be?se(Se):ce(Se,Se.length)}J.prototype.listeners=function(me){return ie(this,me,!0)},J.prototype.rawListeners=function(me){return ie(this,me,!1)},J.listenerCount=function(ve,me){return typeof ve.listenerCount=="function"?ve.listenerCount(me):oe.call(ve,me)},J.prototype.listenerCount=oe;function oe(ve){var me=this._events;if(me!==void 0){var be=me[ve];if(typeof be=="function")return 1;if(be!==void 0)return be.length}return 0}J.prototype.eventNames=function(){return this._eventsCount>0?G(this._events):[]};function ce(ve,me){for(var be=new Array(me),_e=0;_e<me;++_e)be[_e]=ve[_e];return be}function fe(ve,me){for(;me+1<ve.length;me++)ve[me]=ve[me+1];ve.pop()}function se(ve){for(var me=new Array(ve.length),be=0;be<me.length;++be)me[be]=ve[be].listener||ve[be];return me}function de(ve,me){return new Promise(function(be,_e){function Se(ke){ve.removeListener(me,xe),_e(ke)}function xe(){typeof ve.removeListener=="function"&&ve.removeListener("error",Se),be([].slice.call(arguments))}pe(ve,me,xe,{once:!0}),me!=="error"&&ue(ve,Se,{once:!0})})}function ue(ve,me,be){typeof ve.on=="function"&&pe(ve,"error",me,be)}function pe(ve,me,be,_e){if(typeof ve.on=="function")_e.once?ve.once(me,be):ve.on(me,be);else if(typeof ve.addEventListener=="function")ve.addEventListener(me,function Se(xe){_e.once&&ve.removeEventListener(me,Se),be(xe)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof ve)}}}),import_events=__toESM(require_events());import_events.EventEmitter,import_events.EventEmitter;var ErrorStream=class{constructor(){this._unhandledErrors=0}assertNoUnhandledErrors(){if(this._unhandledErrors>0)throw new Error(`Assertion failed: expected no unhandled errors to be thrown, but ${this._unhandledErrors} were thrown.`)}raise($){this._handler?this._handler($):this._unhandledError($)}handle($){this._handler=$}pipeTo($){this.handle(I=>$.raise(I))}_unhandledError($){this._unhandledErrors++,setTimeout(()=>{throw $})}},failUndefined=()=>{throw new Error("Required value was null or undefined.")},inspectObject=$=>{const I=Object.getPrototypeOf($).constructor.name;return $.toJSON?`${I}(${export_inspect($.toJSON())})`:String($)},raise$2=$=>{throw $},SnoopLevel;(function($){$[$.DEFAULT=0]="DEFAULT",$[$.VERBOSE=1]="VERBOSE",$[$.BOLD=2]="BOLD"})(SnoopLevel||(SnoopLevel={}));var StackTrace=class{constructor(){this._stack=new Error}getStack($=0){return this._stack.stack.split(`
|
|
112
112
|
`).slice($+2).join(`
|
|
113
113
|
`)}},truncateKey=($,I=8)=>{const U=String($);return U.length<=I?U:U.slice(0,I)},warnAfterTimeout=async($,I,U)=>{const q=new StackTrace,G=setTimeout(()=>{console.warn(`Action \`${I}\` is taking more then ${$} ms to complete. This might be a bug.
|
|
114
|
-
${q.getStack()}`)},$);try{return await U()}finally{clearTimeout(G)}},devtoolsFormatter=Symbol.for("devtoolsFormatter"),register=()=>{typeof window<"u"&&(window.devtoolsFormatters??(window.devtoolsFormatters=[])).push({header:($,I)=>{const U=$[devtoolsFormatter];if(U===void 0)return null;if(typeof U!="object"||U===null||typeof U.header!="function")throw new Error(`Invalid devtools formatter for ${$.constructor.name}`);return U.header(I)},hasBody:($,I)=>{const U=$[devtoolsFormatter];return!U||!U.hasBody?!1:U.hasBody(I)},body:($,I)=>{const U=$[devtoolsFormatter];return!U||!U.body?null:U.body(I)}})};register();var equalsSymbol=Symbol.for("dxos.common.equals"),__require$1=($=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy($,{get:(I,U)=>(typeof require<"u"?require:I)[U]}):$)(function($){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')}),__dxlog_file$a="/home/runner/work/dxos/dxos/packages/common/keys/src/public-key.ts",PUBLIC_KEY_LENGTH=32,PublicKey=class In{static from(I){if(invariant(I,void 0,{F:__dxlog_file$a,L:30,S:this,A:["source",""]}),I instanceof In)return I;if(I instanceof Buffer)return new In(new Uint8Array(I.buffer,I.byteOffset,I.byteLength));if(I instanceof Uint8Array)return new In(I);if(I instanceof ArrayBuffer)return new In(new Uint8Array(I));if(typeof I=="string")return In.fromHex(I);if(I.asUint8Array)return new In(I.asUint8Array());throw new TypeError(`Unable to create PublicKey from ${I}`)}static safeFrom(I){if(I)try{return In.from(I)}catch{return}}static fromHex(I){I.startsWith("0x")&&(I=I.slice(2));const U=Buffer.from(I,"hex");return new In(new Uint8Array(U.buffer,U.byteOffset,U.byteLength))}static random(){return In.from(randomBytes$1(PUBLIC_KEY_LENGTH))}static*randomSequence(){for(let I=0;I<1e4;I++)yield In.random();throw new Error("Too many keys requested")}static isPublicKey(I){return I instanceof In}static assertValidPublicKey(I){if(!this.isPublicKey(I))throw new TypeError("Invalid PublicKey")}static equals(I,U){return In.from(I).equals(U)}static bufferize(I){return invariant(typeof I=="string","Invalid type",{F:__dxlog_file$a,L:129,S:this,A:["typeof str === 'string'","'Invalid type'"]}),Buffer.from(I,"hex")}static stringify(I){return I instanceof In?I=I.asBuffer():I instanceof Uint8Array&&(I=Buffer.from(I.buffer,I.byteOffset,I.byteLength)),invariant(I instanceof Buffer,"Invalid type",{F:__dxlog_file$a,L:148,S:this,A:["key instanceof Buffer","'Invalid type'"]}),I.toString("hex")}static hash(I){return I.toHex()}constructor(I){if(this._value=I,!(I instanceof Uint8Array))throw new TypeError(`Expected Uint8Array, got: ${I}`)}toString(){return this.toHex()}toJSON(){return this.toHex()}toJSONL(){return this.truncate()}get length(){return this._value.length}toHex(){return this.asBuffer().toString("hex")}truncate(I=void 0){return truncateKey(this,I)}asBuffer(){return Buffer.from(this._value.buffer,this._value.byteOffset,this._value.byteLength)}asUint8Array(){return this._value}getInsecureHash(I){return Math.abs(this._value.reduce((U,q)=>U^q|0,0))%I}[export_inspect.custom](I,U){if(!U.colors||typeof process.stdout.hasColors!="function"||!process.stdout.hasColors())return`<PublicKey ${this.truncate()}>`;const q=Y=>`\x1B[${Y}m`,G=["red","green","yellow","blue","magenta","cyan","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"],K=G[this.getInsecureHash(G.length)];return`PublicKey(${q(export_inspect.colors[K][0])}${this.truncate()}${q(export_inspect.colors.reset[0])})`}get[devtoolsFormatter](){return{header:()=>{const I=["darkred","green","orange","blue","darkmagenta","darkcyan","red","green","orange","blue","magenta","darkcyan","black"],U=I[this.getInsecureHash(I.length)];return["span",{},["span",{},"PublicKey("],["span",{style:`color: ${U};`},this.truncate()],["span",{},")"]]}}}equals(I){const U=In.from(I);if(this._value.length!==U._value.length)return!1;let q=!0;for(let G=0;G<this._value.length;G++)q&&(q=this._value[G]===U._value[G]);return q}[equalsSymbol](I){return In.isPublicKey(I)?this.equals(I):!1}},randomBytes$1=$=>{const I=globalThis.crypto??__require$1("@dxos/node-std/crypto").webcrypto,U=new Uint8Array($);return I.getRandomValues(U),U},__dxlog_file3$5="/home/runner/work/dxos/dxos/packages/common/util/src/callback.ts",Callback=class{call(...$){return invariant(this._callback,"Callback not set",{F:__dxlog_file3$5,L:20,S:this,A:["this._callback","'Callback not set'"]}),this._callback(...$)}callIfSet(...$){var I;return(I=this._callback)==null?void 0:I.call(this,...$)}set($){invariant(!this._callback,"Callback already set",{F:__dxlog_file3$5,L:29,S:this,A:["!this._callback","'Callback already set'"]}),this._callback=$}isSet(){return!!this._callback}},MAX_SERIALIZATION_LENGTH=10,ComplexSet=class{constructor($,I){if(this._projection=$,this._values=new Map,I)for(const U of I)this.add(U)}toString(){return inspectObject(this)}toJSON(){return this._values.size>MAX_SERIALIZATION_LENGTH?{size:this._values.size}:Array.from(this._values.values())}[export_inspect.custom](){return inspectObject(this)}add($){return this._values.set(this._projection($),$),this}clear(){this._values.clear()}delete($){return this._values.delete(this._projection($))}forEach($,I){I&&($=$.bind(I)),this._values.forEach(U=>$(U,U,this))}has($){return this._values.has(this._projection($))}get size(){return this._values.size}[Symbol.iterator](){return this._values.values()}*entries(){for(const $ of this._values.values())yield[$,$]}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}get[Symbol.toStringTag](){return"ComplexSet"}},ComplexMap=class{constructor($,I){if(this._keyProjection=$,this._keys=new Map,this._values=new Map,I)for(const[U,q]of I)this.set(U,q)}toString(){return inspectObject(this)}toJSON(){return this._values.size>MAX_SERIALIZATION_LENGTH?{size:this._values.size}:Array.from(this._values.values())}[export_inspect.custom](){return inspectObject(this)}clear(){this._keys.clear(),this._values.clear()}delete($){const I=this._keys.delete(this._keyProjection($)),U=this._values.delete(this._keyProjection($));return I||U}forEach($,I){I&&($=$.bind(I)),this._keys.forEach((U,q)=>$(this._values.get(q)??raise$2(new Error("Map corrupted.")),U,this))}get($){return this._values.get(this._keyProjection($))}has($){return this._keys.has(this._keyProjection($))}set($,I){const U=this._keyProjection($);return this._keys.set(U,$),this._values.set(U,I),this}get size(){return this._keys.size}*[Symbol.iterator](){for(const[$,I]of this._keys){const U=this._values.get($)??raise$2(new Error("Map corrupted."));yield[I,U]}}entries(){return this[Symbol.iterator]()}keys(){return this._keys.values()}values(){return this._values.values()}get[Symbol.toStringTag](){return"ComplexMap"}},idEmoji=["👹","👻","👽","🤖","🎃","🦾","🦿","🦷","👣","👁️","🧶","👑","🐒","🦆","🦉","🐴","🦄","🐝","🦋","🐞","🪲","🐢","🦎","🦕","🦑","🦀","🐠","🐬","🐋","🦭","🐅","🐆","🦓","🦍","🦧","🐘","🐫","🦒","🦘","🦬","🐖","🐏","🦌","🐕","🐈","🐓","🦚","🦜","🦢","🦩","🦦","🐁","🐿️","🌵","🌲","🌳","🪵","🌱","🍁","🪺","🍄","🐚","🪸","🪨","🌾","🌷","🌻","☀️","🌙","🪐","⭐️","⚡️","☄️","🔥","🌈","☁️","💧","⛱️","🌊","🍎","🍋","🍉","🍇","🫐","🍈","🍒","🍑","🥭","🍍","🥥","🥝","🥑","🌶️","🌽","🥕","🍬","🥜","🫖","☕️","🍵","🧊","🧂","🏔️","⚓️","🛟","🏝️","🛶","🚀","🛰️","⛲️","🏰","🚲","⛺️","🎙️","🧲","⚙️","🔩","🔮","🔭","🔬","🧬","🌡️","🧺","🛎️","🔑","🪑","🧸","🎈","🎀","🎊","♻️","🎵"],idHue=["red","amber","lime","green","emerald","teal","cyan","violet","purple","fuchsia","pink","rose"],keyToEmoji=$=>hexToEmoji($.toHex()),hexToEmoji=$=>toEmoji(parseInt($,16)),toEmoji=$=>idEmoji[$%idEmoji.length],hexToHue=$=>toHue(parseInt($,16)),toHue=$=>idHue[$%idHue.length],keyToFallback=$=>hexToFallback($.toHex()),hexToFallback=$=>toFallback(parseInt($,16)),toFallback=$=>({emoji:toEmoji($),hue:toHue($)}),DEFAULT_WORDLIST=["ack","alabama","alanine","alaska","alpha","angel","apart","april","arizona","arkansas","artist","asparagus","aspen","august","autumn","avocado","bacon","bakerloo","batman","beer","berlin","beryllium","black","blossom","blue","bluebird","bravo","bulldog","burger","butter","california","carbon","cardinal","carolina","carpet","cat","ceiling","charlie","chicken","coffee","cola","cold","colorado","comet","connecticut","crazy","cup","dakota","december","delaware","delta","diet","don","double","early","earth","east","echo","edward","eight","eighteen","eleven","emma","enemy","equal","failed","fanta","fifteen","fillet","finch","fish","five","fix","floor","florida","football","four","fourteen","foxtrot","freddie","friend","fruit","gee","georgia","glucose","golf","green","grey","hamper","happy","harry","hawaii","helium","high","hot","hotel","hydrogen","idaho","illinois","india","indigo","ink","iowa","island","item","jersey","jig","johnny","juliet","july","jupiter","kansas","kentucky","kilo","king","kitten","lactose","lake","lamp","lemon","leopard","lima","lion","lithium","london","louisiana","low","magazine","magnesium","maine","mango","march","mars","maryland","massachusetts","may","mexico","michigan","mike","minnesota","mirror","mississippi","missouri","mobile","mockingbird","monkey","montana","moon","mountain","muppet","music","nebraska","neptune","network","nevada","nine","nineteen","nitrogen","north","november","nuts","october","ohio","oklahoma","one","orange","oranges","oregon","oscar","oven","oxygen","papa","paris","pasta","pennsylvania","pip","pizza","pluto","potato","princess","purple","quebec","queen","quiet","red","river","robert","robin","romeo","rugby","sad","salami","saturn","september","seven","seventeen","shade","sierra","single","sink","six","sixteen","skylark","snake","social","sodium","solar","south","spaghetti","speaker","spring","stairway","steak","stream","summer","sweet","table","tango","ten","tennessee","tennis","texas","thirteen","three","timing","triple","twelve","twenty","two","uncle","undress","uniform","uranus","utah","vegan","venus","vermont","victor","video","violet","virginia","washington","west","whiskey","white","william","winner","winter","wisconsin","wolfram","wyoming","xray","yankee","yellow","zebra","zulu"],HumanHasher=class{constructor($=DEFAULT_WORDLIST){if(this.wordlist=$,$.length!==256)throw new Error("Wordlist must have exactly 256 items");this.wordlist=$}humanize($,I=4,U="-"){const q=$.match(/(..?)/g);if(!q)throw new Error("");const G=q.map(Y=>parseInt(Y,16));return this._compress(G,I).map(Y=>this.wordlist[Y]).join(U)}_compress($,I){const U=$.length;if(I>U)throw new Error("Fewer input bytes than requested output");const q=U/I>>0,G=[];for(let Y=0;Y<q*I;Y+=q)G.push($.slice(Y,Y+q));return G[G.length-1]=G[G.length-1].concat($.slice(I*q)),G.map(Y=>Y.reduce((J,X)=>J^X))}},hasher=new HumanHasher,humanize=$=>($ instanceof export_Buffer||$ instanceof Uint8Array||$ instanceof ArrayBuffer?$=PublicKey.stringify($):$ instanceof PublicKey&&($=$.toHex()),hasher.humanize($)),exponentialBackoffInterval=($,I)=>{let U=I;const q=()=>{$(),U*=2,G=setTimeout(q,U)};let G=setTimeout(q,U);return()=>clearTimeout(G)},arrayToBuffer=$=>export_Buffer.from($.buffer,$.byteOffset,$.byteLength),LOG_MAX_DEPTH=7,jsonlogify=($,I=0,U=new WeakSet)=>{if(I>LOG_MAX_DEPTH)return null;if(typeof $=="function")return null;if(typeof $=="object"&&$!==null){if(U.has($))return null;U.add($);try{if($ instanceof Uint8Array)return arrayToBuffer($).toString("hex");if(Array.isArray($))return $.map(q=>jsonlogify(q,I+1,U));if(typeof $.toJSONL=="function")return $.toJSONL();if(typeof $.toJSON=="function")return $.toJSON();{const q={};for(const G of Object.keys($))q[G]=jsonlogify($[G],I+1,U);return q}}finally{U.delete($)}}else return $},defaultMap=($,I,U)=>{let q=$.get(I);return q===void 0&&(q=typeof U=="function"?U():U,$.set(I,q)),q},safariCheck=()=>typeof navigator<"u"&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),instanceTag=Symbol("instanceTag"),safeInstanceof=$=>I=>{I.prototype[instanceTag]=$,Object.defineProperty(I.prototype,Symbol.hasInstance,{value:U=>(U==null?void 0:U[instanceTag])===$}),Object.defineProperty(I,Symbol.hasInstance,{value:U=>(U==null?void 0:U[instanceTag])===$})},isNotNullOrUndefined=$=>$!=null,symbol=Symbol.for("dxos.instance-contexts"),instanceContexts=globalThis[symbol]??(globalThis[symbol]=new WeakMap),getPrototypeSpecificInstanceId=$=>{const I=Object.getPrototypeOf($),U=defaultMap(instanceContexts,I,()=>({nextId:0,instanceIds:new WeakMap}));let q=U.instanceIds.get($);return q===void 0&&(q=U.nextId++,U.instanceIds.set($,q)),q},getDebugName=$=>$==null?"null":`${Object.getPrototypeOf($).constructor.name}#${getPrototypeSpecificInstanceId($)}`;Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose")),Symbol.asyncDispose??(Symbol.asyncDispose=Symbol("Symbol.asyncDispose"));var notAvailable=()=>{throw new Error("Not available on this platform")},appendFileSync=()=>notAvailable(),mkdirSync=()=>notAvailable(),openSync=()=>notAvailable(),require_path_browserify=__commonJS({"node_modules/.pnpm/path-browserify@1.0.1/node_modules/path-browserify/index.js"($,I){function U(Y){if(typeof Y!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(Y))}function q(Y,J){for(var X="",Z=0,Q=-1,ee=0,te,ne=0;ne<=Y.length;++ne){if(ne<Y.length)te=Y.charCodeAt(ne);else{if(te===47)break;te=47}if(te===47){if(!(Q===ne-1||ee===1))if(Q!==ne-1&&ee===2){if(X.length<2||Z!==2||X.charCodeAt(X.length-1)!==46||X.charCodeAt(X.length-2)!==46){if(X.length>2){var ie=X.lastIndexOf("/");if(ie!==X.length-1){ie===-1?(X="",Z=0):(X=X.slice(0,ie),Z=X.length-1-X.lastIndexOf("/")),Q=ne,ee=0;continue}}else if(X.length===2||X.length===1){X="",Z=0,Q=ne,ee=0;continue}}J&&(X.length>0?X+="/..":X="..",Z=2)}else X.length>0?X+="/"+Y.slice(Q+1,ne):X=Y.slice(Q+1,ne),Z=ne-Q-1;Q=ne,ee=0}else te===46&&ee!==-1?++ee:ee=-1}return X}function G(Y,J){var X=J.dir||J.root,Z=J.base||(J.name||"")+(J.ext||"");return X?X===J.root?X+Z:X+Y+Z:Z}var K={resolve:function(){for(var J="",X=!1,Z,Q=arguments.length-1;Q>=-1&&!X;Q--){var ee;Q>=0?ee=arguments[Q]:(Z===void 0&&(Z=process.cwd()),ee=Z),U(ee),ee.length!==0&&(J=ee+"/"+J,X=ee.charCodeAt(0)===47)}return J=q(J,!X),X?J.length>0?"/"+J:"/":J.length>0?J:"."},normalize:function(J){if(U(J),J.length===0)return".";var X=J.charCodeAt(0)===47,Z=J.charCodeAt(J.length-1)===47;return J=q(J,!X),J.length===0&&!X&&(J="."),J.length>0&&Z&&(J+="/"),X?"/"+J:J},isAbsolute:function(J){return U(J),J.length>0&&J.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var J,X=0;X<arguments.length;++X){var Z=arguments[X];U(Z),Z.length>0&&(J===void 0?J=Z:J+="/"+Z)}return J===void 0?".":K.normalize(J)},relative:function(J,X){if(U(J),U(X),J===X||(J=K.resolve(J),X=K.resolve(X),J===X))return"";for(var Z=1;Z<J.length&&J.charCodeAt(Z)===47;++Z);for(var Q=J.length,ee=Q-Z,te=1;te<X.length&&X.charCodeAt(te)===47;++te);for(var ne=X.length,ie=ne-te,oe=ee<ie?ee:ie,ce=-1,fe=0;fe<=oe;++fe){if(fe===oe){if(ie>oe){if(X.charCodeAt(te+fe)===47)return X.slice(te+fe+1);if(fe===0)return X.slice(te+fe)}else ee>oe&&(J.charCodeAt(Z+fe)===47?ce=fe:fe===0&&(ce=0));break}var se=J.charCodeAt(Z+fe),de=X.charCodeAt(te+fe);if(se!==de)break;se===47&&(ce=fe)}var ue="";for(fe=Z+ce+1;fe<=Q;++fe)(fe===Q||J.charCodeAt(fe)===47)&&(ue.length===0?ue+="..":ue+="/..");return ue.length>0?ue+X.slice(te+ce):(te+=ce,X.charCodeAt(te)===47&&++te,X.slice(te))},_makeLong:function(J){return J},dirname:function(J){if(U(J),J.length===0)return".";for(var X=J.charCodeAt(0),Z=X===47,Q=-1,ee=!0,te=J.length-1;te>=1;--te)if(X=J.charCodeAt(te),X===47){if(!ee){Q=te;break}}else ee=!1;return Q===-1?Z?"/":".":Z&&Q===1?"//":J.slice(0,Q)},basename:function(J,X){if(X!==void 0&&typeof X!="string")throw new TypeError('"ext" argument must be a string');U(J);var Z=0,Q=-1,ee=!0,te;if(X!==void 0&&X.length>0&&X.length<=J.length){if(X.length===J.length&&X===J)return"";var ne=X.length-1,ie=-1;for(te=J.length-1;te>=0;--te){var oe=J.charCodeAt(te);if(oe===47){if(!ee){Z=te+1;break}}else ie===-1&&(ee=!1,ie=te+1),ne>=0&&(oe===X.charCodeAt(ne)?--ne===-1&&(Q=te):(ne=-1,Q=ie))}return Z===Q?Q=ie:Q===-1&&(Q=J.length),J.slice(Z,Q)}else{for(te=J.length-1;te>=0;--te)if(J.charCodeAt(te)===47){if(!ee){Z=te+1;break}}else Q===-1&&(ee=!1,Q=te+1);return Q===-1?"":J.slice(Z,Q)}},extname:function(J){U(J);for(var X=-1,Z=0,Q=-1,ee=!0,te=0,ne=J.length-1;ne>=0;--ne){var ie=J.charCodeAt(ne);if(ie===47){if(!ee){Z=ne+1;break}continue}Q===-1&&(ee=!1,Q=ne+1),ie===46?X===-1?X=ne:te!==1&&(te=1):X!==-1&&(te=-1)}return X===-1||Q===-1||te===0||te===1&&X===Q-1&&X===Z+1?"":J.slice(X,Q)},format:function(J){if(J===null||typeof J!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof J);return G("/",J)},parse:function(J){U(J);var X={root:"",dir:"",base:"",ext:"",name:""};if(J.length===0)return X;var Z=J.charCodeAt(0),Q=Z===47,ee;Q?(X.root="/",ee=1):ee=0;for(var te=-1,ne=0,ie=-1,oe=!0,ce=J.length-1,fe=0;ce>=ee;--ce){if(Z=J.charCodeAt(ce),Z===47){if(!oe){ne=ce+1;break}continue}ie===-1&&(oe=!1,ie=ce+1),Z===46?te===-1?te=ce:fe!==1&&(fe=1):te!==-1&&(fe=-1)}return te===-1||ie===-1||fe===0||fe===1&&te===ie-1&&te===ne+1?ie!==-1&&(ne===0&&Q?X.base=X.name=J.slice(1,ie):X.base=X.name=J.slice(ne,ie)):(ne===0&&Q?(X.name=J.slice(1,te),X.base=J.slice(1,ie)):(X.name=J.slice(ne,te),X.base=J.slice(ne,ie)),X.ext=J.slice(te,ie)),ne>0?X.dir=J.slice(0,ne-1):Q&&(X.dir="/"),X},sep:"/",delimiter:":",win32:null,posix:null};K.posix=K,I.exports=K}});__toESM(require_path_browserify());var import_path_browserify=__toESM(require_path_browserify());import_path_browserify.basename;var export_dirname=import_path_browserify.dirname;import_path_browserify.extname,import_path_browserify.format,import_path_browserify.isAbsolute,import_path_browserify.join,import_path_browserify.normalize,import_path_browserify.parse,import_path_browserify.relative,import_path_browserify.resolve;var LogLevel$1;(function($){$[$.TRACE=5]="TRACE",$[$.DEBUG=10]="DEBUG",$[$.INFO=11]="INFO",$[$.WARN=12]="WARN",$[$.ERROR=13]="ERROR"})(LogLevel$1||(LogLevel$1={}));var levels={trace:5,debug:10,info:11,warn:12,error:13},LogProcessorType;(function($){$.CONSOLE="console",$.BROWSER="browser",$.DEBUG="debug"})(LogProcessorType||(LogProcessorType={}));var logInfoProperties=Symbol("logInfoProperties"),logInfo=($,I,U)=>{($[logInfoProperties]??($[logInfoProperties]=[])).push(I)},gatherLogInfoFromScope=$=>{if(!$)return{};const I={},q=Object.getPrototypeOf($)[logInfoProperties]??[];for(const G of q)try{I[G]=typeof $[G]=="function"?$[G]():$[G]}catch(K){I[G]=K.message}return I},matchFilter=($,I,U)=>I>=$.level&&(!$.pattern||U.includes($.pattern)),shouldLog=($,I)=>I===void 0?!0:I.some(U=>{var q;return matchFilter(U,$.level,((q=$.meta)==null?void 0:q.F)??"")}),getContextFromEntry=$=>{let I;if($.meta){const U=gatherLogInfoFromScope($.meta.S);Object.keys(U).length>0&&(I=Object.assign(I??{},U))}if($.context)if($.context instanceof Error){const U=$.context.context;I=Object.assign(I??{},{error:$.context.stack,...U})}else typeof $.context=="object"&&(I=Object.assign(I??{},$.context));if($.error){const U=$.error.context;I=Object.assign(I??{},{error:$.error,...U})}return I&&Object.keys(I).length>0?I:void 0},nextPromiseId=0,createMethodLogDecorator=$=>(I,U,q)=>(G,K,Y)=>{const J=Y.value,X=K;Y.value=function(...Z){const Q={F:"",L:0,...q??{},S:this},ee=Z.map(te=>export_inspect(te,!1,1,!0)).join(", ");try{const te=performance.now(),ne=J.apply(this,Z);if(isThenable(ne)){const ie=nextPromiseId++;logAsyncBegin($,X,ee,ie,Q),ne.then(oe=>{logAsyncResolved($,X,oe,ie,te,Q)},oe=>{logAsyncRejected($,X,oe,ie,te,Q)})}else logSyncCall($,X,ee,ne,Q);return ne}catch(te){throw logSyncError($,X,ee,te,Q),te}},Object.defineProperty(Y.value,"name",{value:X+"$log"})},isThenable=$=>$&&typeof $.then=="function",logSyncCall=($,I,U,q,G)=>{$.info(`.${formatFunction(I)} (${U}) ${chalk$1.gray("resolve")} ${export_inspect(q,!1,1,!0)}`,{},G)},logSyncError=($,I,U,q,G)=>{$.error(`.${formatFunction(I)} (${U}) 🔥 ${q}`,{},G)},logAsyncBegin=($,I,U,q,G)=>{$.info(`.${formatFunction(I)} ↴ (${U}) ${chalk$1.gray("=>")} ${formatPromise(q)}`,{},G)},logAsyncResolved=($,I,U,q,G,K)=>{U!==void 0?$.info(`.${formatFunction(I)} ↲ ${greenCheck} ${chalk$1.gray("resolve")} ${formatPromise(q)} ${formatTimeElapsed(G)} ${chalk$1.gray("=>")} ${export_inspect(U,!1,1,!0)}`,{},K):$.info(`.${formatFunction(I)} ↲ ${greenCheck} ${chalk$1.gray("resolve")} ${formatPromise(q)} ${formatTimeElapsed(G)}`,{},K)},logAsyncRejected=($,I,U,q,G,K)=>{$.info(`.${formatFunction(I)} ↲ 🔥 ${chalk$1.gray("reject")} ${formatPromise(q)} ${formatTimeElapsed(G)} ${chalk$1.gray("=>")} ${U}`,{},K)},greenCheck=chalk$1.green("✔"),formatTimeElapsed=$=>chalk$1.gray(`${(performance.now()-$).toFixed(0)}ms`),COLOR_FUNCTION=[220,220,170],formatFunction=$=>chalk$1.bold(chalk$1.rgb(...COLOR_FUNCTION)($)),formatPromise=$=>chalk$1.blue(`Promise#${$}`),loadOptions=$=>{let I;if(typeof localStorage>"u"?globalThis.localStorage_dxlog&&(I=globalThis.localStorage_dxlog):I=localStorage.getItem("dxlog")??void 0,!!I)try{return JSON.parse(I)}catch(U){console.info("can't parse dxlog config",U);return}},CONSOLE_PROCESSOR=()=>{},DEBUG_PROCESSOR=($,I)=>{console.log(export_inspect(I,!1,null,!0))},getRelativeFilename=$=>{const I=$.match(/.+\/(packages\/.+\/.+)/);if(I){const[,U]=I;return U}return $},CONFIG=typeof mochaExecutor<"u"?{useTestProcessor:!0,printFileLinks:!0}:{useTestProcessor:!1,printFileLinks:!1},APP_BROWSER_PROCESSOR=($,I)=>{var Z,Q,ee,te;if(!shouldLog(I,$.filters))return;const U=$.prefix??"https://vscode.dev/github.com/dxos/dxos/blob/main/",q=[];let G="";if(I.meta){const ne=getRelativeFilename(I.meta.F);G=`${`${U.replace(/\/$/,"")}/${ne}`}#L${I.meta.L}`}let K=[];if((Z=I.meta)!=null&&Z.S){const ne=(Q=I.meta)==null?void 0:Q.S,ie=ne.name||getDebugName(ne),oe=(ee=I.meta.S)!=null&&ee.hostSessionId?"[worker] ":"";K.push(`%c${oe}${ie}`,"color:#C026D3;font-weight:bold")}K.push(I.message);const Y=getContextFromEntry(I);Y&&K.push(Y);const J={[LogLevel$1.ERROR]:console.error,[LogLevel$1.WARN]:console.warn,[LogLevel$1.DEBUG]:console.log};(CONFIG.printFileLinks||safariCheck())&&(q!=null&&q.length?K=[`%c${G}
|
|
114
|
+
${q.getStack()}`)},$);try{return await U()}finally{clearTimeout(G)}},devtoolsFormatter=Symbol.for("devtoolsFormatter"),register=()=>{typeof window<"u"&&(window.devtoolsFormatters??(window.devtoolsFormatters=[])).push({header:($,I)=>{const U=$[devtoolsFormatter];if(U===void 0)return null;if(typeof U!="object"||U===null||typeof U.header!="function")throw new Error(`Invalid devtools formatter for ${$.constructor.name}`);return U.header(I)},hasBody:($,I)=>{const U=$[devtoolsFormatter];return!U||!U.hasBody?!1:U.hasBody(I)},body:($,I)=>{const U=$[devtoolsFormatter];return!U||!U.body?null:U.body(I)}})};register();var equalsSymbol=Symbol.for("dxos.common.equals"),__require$1=($=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy($,{get:(I,U)=>(typeof require<"u"?require:I)[U]}):$)(function($){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')}),__dxlog_file$a="/home/runner/work/dxos/dxos/packages/common/keys/src/public-key.ts",PUBLIC_KEY_LENGTH=32,PublicKey=class In{static from(I){if(invariant(I,void 0,{F:__dxlog_file$a,L:30,S:this,A:["source",""]}),I instanceof In)return I;if(I instanceof Buffer)return new In(new Uint8Array(I.buffer,I.byteOffset,I.byteLength));if(I instanceof Uint8Array)return new In(I);if(I instanceof ArrayBuffer)return new In(new Uint8Array(I));if(typeof I=="string")return In.fromHex(I);if(I.asUint8Array)return new In(I.asUint8Array());throw new TypeError(`Unable to create PublicKey from ${I}`)}static safeFrom(I){if(I)try{return In.from(I)}catch{return}}static fromHex(I){I.startsWith("0x")&&(I=I.slice(2));const U=Buffer.from(I,"hex");return new In(new Uint8Array(U.buffer,U.byteOffset,U.byteLength))}static random(){return In.from(randomBytes$1(PUBLIC_KEY_LENGTH))}static*randomSequence(){for(let I=0;I<1e4;I++)yield In.random();throw new Error("Too many keys requested")}static isPublicKey(I){return I instanceof In}static assertValidPublicKey(I){if(!this.isPublicKey(I))throw new TypeError("Invalid PublicKey")}static equals(I,U){return In.from(I).equals(U)}static bufferize(I){return invariant(typeof I=="string","Invalid type",{F:__dxlog_file$a,L:129,S:this,A:["typeof str === 'string'","'Invalid type'"]}),Buffer.from(I,"hex")}static stringify(I){return I instanceof In?I=I.asBuffer():I instanceof Uint8Array&&(I=Buffer.from(I.buffer,I.byteOffset,I.byteLength)),invariant(I instanceof Buffer,"Invalid type",{F:__dxlog_file$a,L:148,S:this,A:["key instanceof Buffer","'Invalid type'"]}),I.toString("hex")}static hash(I){return I.toHex()}constructor(I){if(this._value=I,!(I instanceof Uint8Array))throw new TypeError(`Expected Uint8Array, got: ${I}`)}toString(){return this.toHex()}toJSON(){return this.toHex()}toJSONL(){return this.truncate()}get length(){return this._value.length}toHex(){return this.asBuffer().toString("hex")}truncate(I=void 0){return truncateKey(this,I)}asBuffer(){return Buffer.from(this._value.buffer,this._value.byteOffset,this._value.byteLength)}asUint8Array(){return this._value}getInsecureHash(I){return Math.abs(this._value.reduce((U,q)=>U^q|0,0))%I}[export_inspect.custom](I,U){if(!U.colors||typeof process.stdout.hasColors!="function"||!process.stdout.hasColors())return`<PublicKey ${this.truncate()}>`;const q=Y=>`\x1B[${Y}m`,G=["red","green","yellow","blue","magenta","cyan","redBright","greenBright","yellowBright","blueBright","magentaBright","cyanBright","whiteBright"],K=G[this.getInsecureHash(G.length)];return`PublicKey(${q(export_inspect.colors[K][0])}${this.truncate()}${q(export_inspect.colors.reset[0])})`}get[devtoolsFormatter](){return{header:()=>{const I=["darkred","green","orange","blue","darkmagenta","darkcyan","red","green","orange","blue","magenta","darkcyan","black"],U=I[this.getInsecureHash(I.length)];return["span",{},["span",{},"PublicKey("],["span",{style:`color: ${U};`},this.truncate()],["span",{},")"]]}}}equals(I){const U=In.from(I);if(this._value.length!==U._value.length)return!1;let q=!0;for(let G=0;G<this._value.length;G++)q&&(q=this._value[G]===U._value[G]);return q}[equalsSymbol](I){return In.isPublicKey(I)?this.equals(I):!1}},randomBytes$1=$=>{const I=globalThis.crypto??__require$1("@dxos/node-std/crypto").webcrypto,U=new Uint8Array($);return I.getRandomValues(U),U},__dxlog_file3$4="/home/runner/work/dxos/dxos/packages/common/util/src/callback.ts",Callback=class{call(...$){return invariant(this._callback,"Callback not set",{F:__dxlog_file3$4,L:20,S:this,A:["this._callback","'Callback not set'"]}),this._callback(...$)}callIfSet(...$){var I;return(I=this._callback)==null?void 0:I.call(this,...$)}set($){invariant(!this._callback,"Callback already set",{F:__dxlog_file3$4,L:29,S:this,A:["!this._callback","'Callback already set'"]}),this._callback=$}isSet(){return!!this._callback}},MAX_SERIALIZATION_LENGTH=10,ComplexSet=class{constructor($,I){if(this._projection=$,this._values=new Map,I)for(const U of I)this.add(U)}toString(){return inspectObject(this)}toJSON(){return this._values.size>MAX_SERIALIZATION_LENGTH?{size:this._values.size}:Array.from(this._values.values())}[export_inspect.custom](){return inspectObject(this)}add($){return this._values.set(this._projection($),$),this}clear(){this._values.clear()}delete($){return this._values.delete(this._projection($))}forEach($,I){I&&($=$.bind(I)),this._values.forEach(U=>$(U,U,this))}has($){return this._values.has(this._projection($))}get size(){return this._values.size}[Symbol.iterator](){return this._values.values()}*entries(){for(const $ of this._values.values())yield[$,$]}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}get[Symbol.toStringTag](){return"ComplexSet"}},ComplexMap=class{constructor($,I){if(this._keyProjection=$,this._keys=new Map,this._values=new Map,I)for(const[U,q]of I)this.set(U,q)}toString(){return inspectObject(this)}toJSON(){return this._values.size>MAX_SERIALIZATION_LENGTH?{size:this._values.size}:Array.from(this._values.values())}[export_inspect.custom](){return inspectObject(this)}clear(){this._keys.clear(),this._values.clear()}delete($){const I=this._keys.delete(this._keyProjection($)),U=this._values.delete(this._keyProjection($));return I||U}forEach($,I){I&&($=$.bind(I)),this._keys.forEach((U,q)=>$(this._values.get(q)??raise$2(new Error("Map corrupted.")),U,this))}get($){return this._values.get(this._keyProjection($))}has($){return this._keys.has(this._keyProjection($))}set($,I){const U=this._keyProjection($);return this._keys.set(U,$),this._values.set(U,I),this}get size(){return this._keys.size}*[Symbol.iterator](){for(const[$,I]of this._keys){const U=this._values.get($)??raise$2(new Error("Map corrupted."));yield[I,U]}}entries(){return this[Symbol.iterator]()}keys(){return this._keys.values()}values(){return this._values.values()}get[Symbol.toStringTag](){return"ComplexMap"}},idEmoji=["👹","👻","👽","🤖","🎃","🦾","🦿","🦷","👣","👁️","🧶","👑","🐒","🦆","🦉","🐴","🦄","🐝","🦋","🐞","🪲","🐢","🦎","🦕","🦑","🦀","🐠","🐬","🐋","🦭","🐅","🐆","🦓","🦍","🦧","🐘","🐫","🦒","🦘","🦬","🐖","🐏","🦌","🐕","🐈","🐓","🦚","🦜","🦢","🦩","🦦","🐁","🐿️","🌵","🌲","🌳","🪵","🌱","🍁","🪺","🍄","🐚","🪸","🪨","🌾","🌷","🌻","☀️","🌙","🪐","⭐️","⚡️","☄️","🔥","🌈","☁️","💧","⛱️","🌊","🍎","🍋","🍉","🍇","🫐","🍈","🍒","🍑","🥭","🍍","🥥","🥝","🥑","🌶️","🌽","🥕","🍬","🥜","🫖","☕️","🍵","🧊","🧂","🏔️","⚓️","🛟","🏝️","🛶","🚀","🛰️","⛲️","🏰","🚲","⛺️","🎙️","🧲","⚙️","🔩","🔮","🔭","🔬","🧬","🌡️","🧺","🛎️","🔑","🪑","🧸","🎈","🎀","🎊","♻️","🎵"],idHue=["red","amber","lime","green","emerald","teal","cyan","violet","purple","fuchsia","pink","rose"],keyToEmoji=$=>hexToEmoji($.toHex()),hexToEmoji=$=>toEmoji(parseInt($,16)),toEmoji=$=>idEmoji[$%idEmoji.length],hexToHue=$=>toHue(parseInt($,16)),toHue=$=>idHue[$%idHue.length],keyToFallback=$=>hexToFallback($.toHex()),hexToFallback=$=>toFallback(parseInt($,16)),toFallback=$=>({emoji:toEmoji($),hue:toHue($)}),DEFAULT_WORDLIST=["ack","alabama","alanine","alaska","alpha","angel","apart","april","arizona","arkansas","artist","asparagus","aspen","august","autumn","avocado","bacon","bakerloo","batman","beer","berlin","beryllium","black","blossom","blue","bluebird","bravo","bulldog","burger","butter","california","carbon","cardinal","carolina","carpet","cat","ceiling","charlie","chicken","coffee","cola","cold","colorado","comet","connecticut","crazy","cup","dakota","december","delaware","delta","diet","don","double","early","earth","east","echo","edward","eight","eighteen","eleven","emma","enemy","equal","failed","fanta","fifteen","fillet","finch","fish","five","fix","floor","florida","football","four","fourteen","foxtrot","freddie","friend","fruit","gee","georgia","glucose","golf","green","grey","hamper","happy","harry","hawaii","helium","high","hot","hotel","hydrogen","idaho","illinois","india","indigo","ink","iowa","island","item","jersey","jig","johnny","juliet","july","jupiter","kansas","kentucky","kilo","king","kitten","lactose","lake","lamp","lemon","leopard","lima","lion","lithium","london","louisiana","low","magazine","magnesium","maine","mango","march","mars","maryland","massachusetts","may","mexico","michigan","mike","minnesota","mirror","mississippi","missouri","mobile","mockingbird","monkey","montana","moon","mountain","muppet","music","nebraska","neptune","network","nevada","nine","nineteen","nitrogen","north","november","nuts","october","ohio","oklahoma","one","orange","oranges","oregon","oscar","oven","oxygen","papa","paris","pasta","pennsylvania","pip","pizza","pluto","potato","princess","purple","quebec","queen","quiet","red","river","robert","robin","romeo","rugby","sad","salami","saturn","september","seven","seventeen","shade","sierra","single","sink","six","sixteen","skylark","snake","social","sodium","solar","south","spaghetti","speaker","spring","stairway","steak","stream","summer","sweet","table","tango","ten","tennessee","tennis","texas","thirteen","three","timing","triple","twelve","twenty","two","uncle","undress","uniform","uranus","utah","vegan","venus","vermont","victor","video","violet","virginia","washington","west","whiskey","white","william","winner","winter","wisconsin","wolfram","wyoming","xray","yankee","yellow","zebra","zulu"],HumanHasher=class{constructor($=DEFAULT_WORDLIST){if(this.wordlist=$,$.length!==256)throw new Error("Wordlist must have exactly 256 items");this.wordlist=$}humanize($,I=4,U="-"){const q=$.match(/(..?)/g);if(!q)throw new Error("");const G=q.map(Y=>parseInt(Y,16));return this._compress(G,I).map(Y=>this.wordlist[Y]).join(U)}_compress($,I){const U=$.length;if(I>U)throw new Error("Fewer input bytes than requested output");const q=U/I>>0,G=[];for(let Y=0;Y<q*I;Y+=q)G.push($.slice(Y,Y+q));return G[G.length-1]=G[G.length-1].concat($.slice(I*q)),G.map(Y=>Y.reduce((J,X)=>J^X))}},hasher=new HumanHasher,humanize=$=>($ instanceof export_Buffer||$ instanceof Uint8Array||$ instanceof ArrayBuffer?$=PublicKey.stringify($):$ instanceof PublicKey&&($=$.toHex()),hasher.humanize($)),exponentialBackoffInterval=($,I)=>{let U=I;const q=()=>{$(),U*=2,G=setTimeout(q,U)};let G=setTimeout(q,U);return()=>clearTimeout(G)},arrayToBuffer=$=>export_Buffer.from($.buffer,$.byteOffset,$.byteLength),LOG_MAX_DEPTH=7,jsonlogify=($,I=0,U=new WeakSet)=>{if(I>LOG_MAX_DEPTH)return null;if(typeof $=="function")return null;if(typeof $=="object"&&$!==null){if(U.has($))return null;U.add($);try{if($ instanceof Uint8Array)return arrayToBuffer($).toString("hex");if(Array.isArray($))return $.map(q=>jsonlogify(q,I+1,U));if(typeof $.toJSONL=="function")return $.toJSONL();if(typeof $.toJSON=="function")return $.toJSON();{const q={};for(const G of Object.keys($))q[G]=jsonlogify($[G],I+1,U);return q}}finally{U.delete($)}}else return $},defaultMap=($,I,U)=>{let q=$.get(I);return q===void 0&&(q=typeof U=="function"?U():U,$.set(I,q)),q},safariCheck=()=>typeof navigator<"u"&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent),instanceTag=Symbol("instanceTag"),safeInstanceof=$=>I=>{I.prototype[instanceTag]=$,Object.defineProperty(I.prototype,Symbol.hasInstance,{value:U=>(U==null?void 0:U[instanceTag])===$}),Object.defineProperty(I,Symbol.hasInstance,{value:U=>(U==null?void 0:U[instanceTag])===$})},isNotNullOrUndefined=$=>$!=null,symbol=Symbol.for("dxos.instance-contexts"),instanceContexts=globalThis[symbol]??(globalThis[symbol]=new WeakMap),getPrototypeSpecificInstanceId=$=>{const I=Object.getPrototypeOf($),U=defaultMap(instanceContexts,I,()=>({nextId:0,instanceIds:new WeakMap}));let q=U.instanceIds.get($);return q===void 0&&(q=U.nextId++,U.instanceIds.set($,q)),q},getDebugName=$=>$==null?"null":`${Object.getPrototypeOf($).constructor.name}#${getPrototypeSpecificInstanceId($)}`;Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose")),Symbol.asyncDispose??(Symbol.asyncDispose=Symbol("Symbol.asyncDispose"));var notAvailable=()=>{throw new Error("Not available on this platform")},appendFileSync=()=>notAvailable(),mkdirSync=()=>notAvailable(),openSync=()=>notAvailable(),require_path_browserify=__commonJS({"node_modules/.pnpm/path-browserify@1.0.1/node_modules/path-browserify/index.js"($,I){function U(Y){if(typeof Y!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(Y))}function q(Y,J){for(var X="",Z=0,Q=-1,ee=0,te,ne=0;ne<=Y.length;++ne){if(ne<Y.length)te=Y.charCodeAt(ne);else{if(te===47)break;te=47}if(te===47){if(!(Q===ne-1||ee===1))if(Q!==ne-1&&ee===2){if(X.length<2||Z!==2||X.charCodeAt(X.length-1)!==46||X.charCodeAt(X.length-2)!==46){if(X.length>2){var ie=X.lastIndexOf("/");if(ie!==X.length-1){ie===-1?(X="",Z=0):(X=X.slice(0,ie),Z=X.length-1-X.lastIndexOf("/")),Q=ne,ee=0;continue}}else if(X.length===2||X.length===1){X="",Z=0,Q=ne,ee=0;continue}}J&&(X.length>0?X+="/..":X="..",Z=2)}else X.length>0?X+="/"+Y.slice(Q+1,ne):X=Y.slice(Q+1,ne),Z=ne-Q-1;Q=ne,ee=0}else te===46&&ee!==-1?++ee:ee=-1}return X}function G(Y,J){var X=J.dir||J.root,Z=J.base||(J.name||"")+(J.ext||"");return X?X===J.root?X+Z:X+Y+Z:Z}var K={resolve:function(){for(var J="",X=!1,Z,Q=arguments.length-1;Q>=-1&&!X;Q--){var ee;Q>=0?ee=arguments[Q]:(Z===void 0&&(Z=process.cwd()),ee=Z),U(ee),ee.length!==0&&(J=ee+"/"+J,X=ee.charCodeAt(0)===47)}return J=q(J,!X),X?J.length>0?"/"+J:"/":J.length>0?J:"."},normalize:function(J){if(U(J),J.length===0)return".";var X=J.charCodeAt(0)===47,Z=J.charCodeAt(J.length-1)===47;return J=q(J,!X),J.length===0&&!X&&(J="."),J.length>0&&Z&&(J+="/"),X?"/"+J:J},isAbsolute:function(J){return U(J),J.length>0&&J.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var J,X=0;X<arguments.length;++X){var Z=arguments[X];U(Z),Z.length>0&&(J===void 0?J=Z:J+="/"+Z)}return J===void 0?".":K.normalize(J)},relative:function(J,X){if(U(J),U(X),J===X||(J=K.resolve(J),X=K.resolve(X),J===X))return"";for(var Z=1;Z<J.length&&J.charCodeAt(Z)===47;++Z);for(var Q=J.length,ee=Q-Z,te=1;te<X.length&&X.charCodeAt(te)===47;++te);for(var ne=X.length,ie=ne-te,oe=ee<ie?ee:ie,ce=-1,fe=0;fe<=oe;++fe){if(fe===oe){if(ie>oe){if(X.charCodeAt(te+fe)===47)return X.slice(te+fe+1);if(fe===0)return X.slice(te+fe)}else ee>oe&&(J.charCodeAt(Z+fe)===47?ce=fe:fe===0&&(ce=0));break}var se=J.charCodeAt(Z+fe),de=X.charCodeAt(te+fe);if(se!==de)break;se===47&&(ce=fe)}var ue="";for(fe=Z+ce+1;fe<=Q;++fe)(fe===Q||J.charCodeAt(fe)===47)&&(ue.length===0?ue+="..":ue+="/..");return ue.length>0?ue+X.slice(te+ce):(te+=ce,X.charCodeAt(te)===47&&++te,X.slice(te))},_makeLong:function(J){return J},dirname:function(J){if(U(J),J.length===0)return".";for(var X=J.charCodeAt(0),Z=X===47,Q=-1,ee=!0,te=J.length-1;te>=1;--te)if(X=J.charCodeAt(te),X===47){if(!ee){Q=te;break}}else ee=!1;return Q===-1?Z?"/":".":Z&&Q===1?"//":J.slice(0,Q)},basename:function(J,X){if(X!==void 0&&typeof X!="string")throw new TypeError('"ext" argument must be a string');U(J);var Z=0,Q=-1,ee=!0,te;if(X!==void 0&&X.length>0&&X.length<=J.length){if(X.length===J.length&&X===J)return"";var ne=X.length-1,ie=-1;for(te=J.length-1;te>=0;--te){var oe=J.charCodeAt(te);if(oe===47){if(!ee){Z=te+1;break}}else ie===-1&&(ee=!1,ie=te+1),ne>=0&&(oe===X.charCodeAt(ne)?--ne===-1&&(Q=te):(ne=-1,Q=ie))}return Z===Q?Q=ie:Q===-1&&(Q=J.length),J.slice(Z,Q)}else{for(te=J.length-1;te>=0;--te)if(J.charCodeAt(te)===47){if(!ee){Z=te+1;break}}else Q===-1&&(ee=!1,Q=te+1);return Q===-1?"":J.slice(Z,Q)}},extname:function(J){U(J);for(var X=-1,Z=0,Q=-1,ee=!0,te=0,ne=J.length-1;ne>=0;--ne){var ie=J.charCodeAt(ne);if(ie===47){if(!ee){Z=ne+1;break}continue}Q===-1&&(ee=!1,Q=ne+1),ie===46?X===-1?X=ne:te!==1&&(te=1):X!==-1&&(te=-1)}return X===-1||Q===-1||te===0||te===1&&X===Q-1&&X===Z+1?"":J.slice(X,Q)},format:function(J){if(J===null||typeof J!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof J);return G("/",J)},parse:function(J){U(J);var X={root:"",dir:"",base:"",ext:"",name:""};if(J.length===0)return X;var Z=J.charCodeAt(0),Q=Z===47,ee;Q?(X.root="/",ee=1):ee=0;for(var te=-1,ne=0,ie=-1,oe=!0,ce=J.length-1,fe=0;ce>=ee;--ce){if(Z=J.charCodeAt(ce),Z===47){if(!oe){ne=ce+1;break}continue}ie===-1&&(oe=!1,ie=ce+1),Z===46?te===-1?te=ce:fe!==1&&(fe=1):te!==-1&&(fe=-1)}return te===-1||ie===-1||fe===0||fe===1&&te===ie-1&&te===ne+1?ie!==-1&&(ne===0&&Q?X.base=X.name=J.slice(1,ie):X.base=X.name=J.slice(ne,ie)):(ne===0&&Q?(X.name=J.slice(1,te),X.base=J.slice(1,ie)):(X.name=J.slice(ne,te),X.base=J.slice(ne,ie)),X.ext=J.slice(te,ie)),ne>0?X.dir=J.slice(0,ne-1):Q&&(X.dir="/"),X},sep:"/",delimiter:":",win32:null,posix:null};K.posix=K,I.exports=K}});__toESM(require_path_browserify());var import_path_browserify=__toESM(require_path_browserify());import_path_browserify.basename;var export_dirname=import_path_browserify.dirname;import_path_browserify.extname,import_path_browserify.format,import_path_browserify.isAbsolute,import_path_browserify.join,import_path_browserify.normalize,import_path_browserify.parse,import_path_browserify.relative,import_path_browserify.resolve;var LogLevel$1;(function($){$[$.TRACE=5]="TRACE",$[$.DEBUG=10]="DEBUG",$[$.INFO=11]="INFO",$[$.WARN=12]="WARN",$[$.ERROR=13]="ERROR"})(LogLevel$1||(LogLevel$1={}));var levels={trace:5,debug:10,info:11,warn:12,error:13},LogProcessorType;(function($){$.CONSOLE="console",$.BROWSER="browser",$.DEBUG="debug"})(LogProcessorType||(LogProcessorType={}));var logInfoProperties=Symbol("logInfoProperties"),logInfo=($,I,U)=>{($[logInfoProperties]??($[logInfoProperties]=[])).push(I)},gatherLogInfoFromScope=$=>{if(!$)return{};const I={},q=Object.getPrototypeOf($)[logInfoProperties]??[];for(const G of q)try{I[G]=typeof $[G]=="function"?$[G]():$[G]}catch(K){I[G]=K.message}return I},matchFilter=($,I,U)=>I>=$.level&&(!$.pattern||U.includes($.pattern)),shouldLog=($,I)=>I===void 0?!0:I.some(U=>{var q;return matchFilter(U,$.level,((q=$.meta)==null?void 0:q.F)??"")}),getContextFromEntry=$=>{let I;if($.meta){const U=gatherLogInfoFromScope($.meta.S);Object.keys(U).length>0&&(I=Object.assign(I??{},U))}if($.context)if($.context instanceof Error){const U=$.context.context;I=Object.assign(I??{},{error:$.context.stack,...U})}else typeof $.context=="object"&&(I=Object.assign(I??{},$.context));if($.error){const U=$.error.context;I=Object.assign(I??{},{error:$.error,...U})}return I&&Object.keys(I).length>0?I:void 0},nextPromiseId=0,createMethodLogDecorator=$=>(I,U,q)=>(G,K,Y)=>{const J=Y.value,X=K;Y.value=function(...Z){const Q={F:"",L:0,...q??{},S:this},ee=Z.map(te=>export_inspect(te,!1,1,!0)).join(", ");try{const te=performance.now(),ne=J.apply(this,Z);if(isThenable(ne)){const ie=nextPromiseId++;logAsyncBegin($,X,ee,ie,Q),ne.then(oe=>{logAsyncResolved($,X,oe,ie,te,Q)},oe=>{logAsyncRejected($,X,oe,ie,te,Q)})}else logSyncCall($,X,ee,ne,Q);return ne}catch(te){throw logSyncError($,X,ee,te,Q),te}},Object.defineProperty(Y.value,"name",{value:X+"$log"})},isThenable=$=>$&&typeof $.then=="function",logSyncCall=($,I,U,q,G)=>{$.info(`.${formatFunction(I)} (${U}) ${chalk$1.gray("resolve")} ${export_inspect(q,!1,1,!0)}`,{},G)},logSyncError=($,I,U,q,G)=>{$.error(`.${formatFunction(I)} (${U}) 🔥 ${q}`,{},G)},logAsyncBegin=($,I,U,q,G)=>{$.info(`.${formatFunction(I)} ↴ (${U}) ${chalk$1.gray("=>")} ${formatPromise(q)}`,{},G)},logAsyncResolved=($,I,U,q,G,K)=>{U!==void 0?$.info(`.${formatFunction(I)} ↲ ${greenCheck} ${chalk$1.gray("resolve")} ${formatPromise(q)} ${formatTimeElapsed(G)} ${chalk$1.gray("=>")} ${export_inspect(U,!1,1,!0)}`,{},K):$.info(`.${formatFunction(I)} ↲ ${greenCheck} ${chalk$1.gray("resolve")} ${formatPromise(q)} ${formatTimeElapsed(G)}`,{},K)},logAsyncRejected=($,I,U,q,G,K)=>{$.info(`.${formatFunction(I)} ↲ 🔥 ${chalk$1.gray("reject")} ${formatPromise(q)} ${formatTimeElapsed(G)} ${chalk$1.gray("=>")} ${U}`,{},K)},greenCheck=chalk$1.green("✔"),formatTimeElapsed=$=>chalk$1.gray(`${(performance.now()-$).toFixed(0)}ms`),COLOR_FUNCTION=[220,220,170],formatFunction=$=>chalk$1.bold(chalk$1.rgb(...COLOR_FUNCTION)($)),formatPromise=$=>chalk$1.blue(`Promise#${$}`),loadOptions=$=>{let I;if(typeof localStorage>"u"?globalThis.localStorage_dxlog&&(I=globalThis.localStorage_dxlog):I=localStorage.getItem("dxlog")??void 0,!!I)try{return JSON.parse(I)}catch(U){console.info("can't parse dxlog config",U);return}},CONSOLE_PROCESSOR=()=>{},DEBUG_PROCESSOR=($,I)=>{console.log(export_inspect(I,!1,null,!0))},getRelativeFilename=$=>{const I=$.match(/.+\/(packages\/.+\/.+)/);if(I){const[,U]=I;return U}return $},CONFIG=typeof mochaExecutor<"u"?{useTestProcessor:!0,printFileLinks:!0}:{useTestProcessor:!1,printFileLinks:!1},APP_BROWSER_PROCESSOR=($,I)=>{var Z,Q,ee,te;if(!shouldLog(I,$.filters))return;const U=$.prefix??"https://vscode.dev/github.com/dxos/dxos/blob/main/",q=[];let G="";if(I.meta){const ne=getRelativeFilename(I.meta.F);G=`${`${U.replace(/\/$/,"")}/${ne}`}#L${I.meta.L}`}let K=[];if((Z=I.meta)!=null&&Z.S){const ne=(Q=I.meta)==null?void 0:Q.S,ie=ne.name||getDebugName(ne),oe=(ee=I.meta.S)!=null&&ee.hostSessionId?"[worker] ":"";K.push(`%c${oe}${ie}`,"color:#C026D3;font-weight:bold")}K.push(I.message);const Y=getContextFromEntry(I);Y&&K.push(Y);const J={[LogLevel$1.ERROR]:console.error,[LogLevel$1.WARN]:console.warn,[LogLevel$1.DEBUG]:console.log};(CONFIG.printFileLinks||safariCheck())&&(q!=null&&q.length?K=[`%c${G}
|
|
115
115
|
%c${K.join(" ")}`,...q]:K=[G+`
|
|
116
116
|
`,...K]);const X=J[I.level]??console.log;typeof((te=I.meta)==null?void 0:te.C)=="function"?I.meta.C(X,K):X(...K)},TEST_BROWSER_PROCESSOR=($,I)=>{var X,Z,Q;if(!shouldLog(I,$.filters))return;let U="";I.meta&&(U=`${getRelativeFilename(I.meta.F)}:${I.meta.L}`);let q=[];const G=(Z=(X=I.meta)==null?void 0:X.S)!=null&&Z.hostSessionId?"[worker] ":"";q.push(`${G}${I.message}`);const K=getContextFromEntry(I);K&&q.push(K);const Y={[LogLevel$1.ERROR]:console.error,[LogLevel$1.WARN]:console.warn,[LogLevel$1.DEBUG]:console.log};CONFIG.printFileLinks&&(q=[U,...q]);const J=Y[I.level]??console.log;typeof((Q=I.meta)==null?void 0:Q.C)=="function"?I.meta.C(J,q):J(...q)},BROWSER_PROCESSOR=CONFIG.useTestProcessor?TEST_BROWSER_PROCESSOR:APP_BROWSER_PROCESSOR,getRelativeFilename2=$=>{const I=$.match(/.+\/(packages\/.+\/.+)/);if(I){const[,U]=I;return U}return $},EAGAIN_MAX_DURATION=1e3,createFileProcessor=({pathOrFd:$,levels:I,filters:U})=>{let q;return(G,K)=>{if(I.length>0&&!I.includes(K.level)||!shouldLog(K,U))return;if(typeof $=="number")q=$;else{try{mkdirSync(export_dirname($))}catch{}q=openSync()}const Y={...K,timestamp:Date.now(),...K.meta?{meta:{file:getRelativeFilename2(K.meta.F),line:K.meta.L}}:{},context:jsonlogify(getContextFromEntry(K))};let J=0;for(;;)try{return appendFileSync(q,JSON.stringify(Y)+`
|
|
117
117
|
`)}catch(X){if(X.code!=="EAGAIN")throw X;if(J===0)J=performance.now();else if(performance.now()-J>EAGAIN_MAX_DURATION)throw console.log(`could not write after ${EAGAIN_MAX_DURATION}ms of EAGAIN failures, giving up`),X}}},logFilePath,getLogFilePath=()=>(logFilePath??(logFilePath=process.env.LOG_FILE??(process.env.HOME?`${process.env.HOME}/.dxlog/${new Date().toISOString()}.log`:void 0)),logFilePath);createFileProcessor({pathOrFd:getLogFilePath(),levels:[LogLevel$1.ERROR,LogLevel$1.WARN,LogLevel$1.INFO,LogLevel$1.TRACE]});var processors={[LogProcessorType.CONSOLE]:CONSOLE_PROCESSOR,[LogProcessorType.BROWSER]:BROWSER_PROCESSOR,[LogProcessorType.DEBUG]:DEBUG_PROCESSOR},IS_BROWSER=typeof window<"u"||typeof navigator<"u",DEFAULT_PROCESSORS=[IS_BROWSER?BROWSER_PROCESSOR:CONSOLE_PROCESSOR],parseFilter=$=>{if(typeof $=="number")return[{level:$}];const I=(q,G=LogLevel$1.WARN)=>levels[q.toLowerCase()]??G;return(typeof $=="string"?$.split(/,\s*/):$).map(q=>{const[G,K]=q.split(":");return K?{level:I(K),pattern:G}:{level:I(G)}})},getConfig=$=>{const I="process"in globalThis?{file:process.env.LOG_CONFIG,filter:process.env.LOG_FILTER,processor:process.env.LOG_PROCESSOR}:void 0,U=defaultsDeep({},loadOptions(I==null?void 0:I.file),I,$);return{options:U,filters:parseFilter(U.filter??LogLevel$1.INFO),captureFilters:parseFilter(U.captureFilter??LogLevel$1.WARN),processors:U.processor?[processors[U.processor]]:DEFAULT_PROCESSORS,prefix:U.prefix}},createLog=()=>{const $=(...U)=>I(LogLevel$1.DEBUG,...U);$._config=getConfig(),Object.defineProperty($,"runtimeConfig",{get:()=>$._config}),$.addProcessor=U=>{DEFAULT_PROCESSORS.filter(q=>q===U).length===0&&DEFAULT_PROCESSORS.push(U),$._config.processors.filter(q=>q===U).length===0&&$._config.processors.push(U)},$.config=U=>{$._config=getConfig(U)},$.trace=(...U)=>I(LogLevel$1.TRACE,...U),$.debug=(...U)=>I(LogLevel$1.DEBUG,...U),$.info=(...U)=>I(LogLevel$1.INFO,...U),$.warn=(...U)=>I(LogLevel$1.WARN,...U),$.error=(...U)=>I(LogLevel$1.ERROR,...U),$.catch=(U,q,G)=>I(LogLevel$1.ERROR,U.message,q,G,U),$.break=()=>$.info("——————————————————————————————————————————————————"),$.stack=(U,q,G)=>I(LogLevel$1.INFO,`${U??"Stack Dump"}
|
|
@@ -843,13 +843,13 @@ button {
|
|
|
843
843
|
background-color: #61493f;
|
|
844
844
|
}
|
|
845
845
|
|
|
846
|
-
`;function $e5534fc185f7111e$export$2e2bcd8739ae039($){const I=React.useRef(null),U=React.useRef(null);return U.current&&U.current.update($),React.useEffect(()=>(U.current=new $efa000751917694d$export$2e2bcd8739ae039({...$,ref:I}),()=>{U.current=null}),[]),React.createElement("div",{ref:I})}const EmojiPickerToolbarButton=({disabled:$,defaultEmoji:I,emoji:U,onChangeEmoji:q,classNames:G})=>{const{t:K}=useTranslation("os"),[Y,J]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:U,onChange:q,defaultProp:I}),[X,Z]=React.useState(!1),Q=React.useRef(!1),[ee,te]=React.useState(!1);return React.createElement(Tooltip.Root,{open:ee,onOpenChange:ne=>{Q.current?(te(!1),Q.current=!1):te(ne)}},React.createElement(Popover.Root,{open:X,onOpenChange:ne=>{Z(ne),Q.current=!0}},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Popover.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:["gap-2 text-2xl plb-1",G],disabled:$},React.createElement("span",{className:"sr-only"},K("select emoji label")),React.createElement(react.ImageSquare,{className:getSize(5)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},K("select emoji label"),React.createElement(Tooltip.Arrow,null))),React.createElement(Popover.Content,{side:"bottom",onKeyDownCapture:ne=>{ne.key==="Escape"&&(ne.stopPropagation(),Z(!1),Q.current=!0)}},React.createElement($e5534fc185f7111e$export$2e2bcd8739ae039,{data:emojiData,onEmojiSelect:({native:ne})=>{ne&&(J(ne),Z(!1))},autoFocus:!0,maxFrequentRows:0,noCountryFlags:!0}),React.createElement(Popover.Arrow,null))))},HuePreview=({hue:$})=>{const{tx:I}=useThemeContext();return React.createElement("svg",{width:12,height:12,viewBox:"0 0 12 12"},React.createElement("rect",{x:0,y:0,width:12,height:12,className:I("hue.fill","select--hue__preview",{hue:$})}))},HuePickerToolbarButton=({disabled:$,hue:I,onChangeHue:U,classNames:q,defaultHue:G})=>{const{t:K}=useTranslation("os"),[Y,J]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:I,onChange:U,defaultProp:G}),[X,Z]=React.useState(!1),Q=React.useRef(!1),[ee,te]=React.useState(!1);return React.createElement(Tooltip.Root,{open:ee,onOpenChange:ne=>{Q.current?(te(!1),Q.current=!1):te(ne)}},React.createElement(DropdownMenu2.Root,{modal:!1,open:X,onOpenChange:ne=>{Z(ne),Q.current=!0}},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:mx("gap-2 plb-1",q),disabled:$},React.createElement("span",{className:"sr-only"},K("select hue label")),React.createElement(react.Palette,{className:getSize(5)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},K("select hue label"),React.createElement(Tooltip.Arrow,null))),React.createElement(DropdownMenu2.Content,{side:"bottom"},React.createElement(DropdownMenu2.Viewport,null,Object.keys(hueTokenThemes).map(ne=>React.createElement(DropdownMenu2.CheckboxItem,{key:ne,checked:ne===Y,onCheckedChange:()=>J(ne)},React.createElement(HuePreview,{hue:ne}),React.createElement("span",{className:"grow"},K(`${ne} label`)),React.createElement(DropdownMenu2.ItemIndicator,null,React.createElement(react.Check,null))))),React.createElement(DropdownMenu2.Arrow,null))))};var data={adjectives:["abundant","accessible","accomplished","accurate","achievable","adaptable","adaptive","adequate","adjustable","admirable","admiring","adorable","adored","adoring","adroit","adulatory","advanced","advantageous","adventurous","affable","affectionate","affirmative","affluent","affordable","agile","agreeable","alluring","altruistic","amazed","amazing","ambitious","amenable","amiable","amicable","ample","amusing","angelic","appealing","appreciable","appreciated","appreciative","appropriate","ardent","articulate","artistic","assuring","astonished","astonishing","astounded","astounding","athletic","attentive","attractive","audible","auspicious","authentic","autonomous","available","avid","awed","awesome","awestruck","beauteous","beautiful","believable","beloved","beneficent","beneficial","benevolent","blameless","blissful","blithe","bonny","booming","boundless","bountiful","brainiest","brainy","brave","breathtaking","bright","brighter","brightest","brilliant","brisk","brotherly","bullish","buoyant","calm","calming","capable","captivating","carefree","catchy","celebrated","celebratory","champion","charismatic","charitable","charming","chaste","cheaper","cheapest","cheerful","cheery","cherished","chivalrous","classic","classy","clean","cleaner","cleanest","cleanly","clear","cleared","clearer","clever","coherent","cohesive","colorful","comely","comfortable","comforting","comfy","commendable","commodious","compact","compatible","competitive","compliant","conciliatory","concise","confident","congenial","considerate","consistent","constructive","consummate","contrasty","convenient","convincing","cool","coolest","cooperative","correct","courageous","courteous","courtly","cozy","creative","credible","crisp","crisper","cushy","cute","daring","darling","dashing","dauntless","dazzled","dazzling","decent","decisive","dedicated","defeated","deft","delectable","delicate","delicious","delighted","delightful","dependable","deserving","desirable","desirous","detachable","devout","dexterous","dextrous","dignified","diligent","diplomatic","distinctive","diversified","divine","dominated","dumbfounded","durable","dynamic","eager","earnest","eased","easy","easygoing","ebullient","economical","ecstatic","educated","effective","efficacious","efficient","effortless","effusive","elated","elegant","elite","eloquent","eminent","enchanted","enchanting","encouraging","endearing","endorsed","energetic","engaging","engrossing","enhanced","enjoyable","enraptured","enterprising","entertaining","enthralled","enthusiastic","enticing","entranced","entrancing","enviable","envious","equitable","erudite","ethical","euphoric","evaluative","eventful","everlasting","evocative","exalted","exalting","exceeding","excellent","exceptional","excited","exciting","exemplary","exhilarating","expansive","exquisite","exuberant","exultant","fabulous","fair","faithful","famed","famous","fancier","fancy","fantastic","fascinating","fashionable","fast","faster","fastest","faultless","favorable","favored","favorite","fearless","feasible","feisty","felicitous","fertile","fervent","fervid","festive","fiery","fine","finer","finest","firmer","flashy","flatter","flattering","flawless","flexible","flourishing","fluent","fond","foolproof","foremost","formidable","fortuitous","fortunate","fragrant","free","freed","fresh","fresher","freshest","friendly","frugal","fruitful","fun","funny","futuristic","gainful","gallant","galore","generous","genial","gentle","gentlest","genuine","gifted","glad","glamorous","gleeful","glimmering","glistening","glorious","glowing","godlike","gold","golden","good","goodly","gorgeous","graceful","gracious","grand","grateful","gratified","gratifying","great","greatest","guiltless","gutsy","halcyon","hale","hallowed","handier","handsome","handy","happier","happy","hardier","hardy","harmless","harmonious","healthful","healthy","heartening","heartfelt","heartwarming","heavenly","helpful","heroic","hilarious","holy","honest","honorable","honored","hopeful","hospitable","hot","hottest","humane","humble","humorous","humourous","ideal","idolized","idyllic","illuminating","illustrious","imaginative","immaculate","immense","impartial","impassioned","impeccable","important","impressed","impressive","improved","improving","incredible","indebted","indulgent","industrious","inestimable","inexpensive","infallible","influential","ingenious","ingenuous","innocuous","innovative","insightful","inspiring","instructive","instrumental","intelligent","intelligible","interesting","intimate","intricate","intriguing","intuitive","invaluable","inventive","invigorating","invincible","inviolable","inviolate","invulnerable","irresistible","jolly","jovial","joyful","joyous","jubilant","judicious","keen","kindly","laudable","lavish","lawful","leading","lean","legendary","lighter","likable","like","liked","lionhearted","lively","logical","lovable","loved","lovely","loving","loyal","lucid","luckier","luckiest","lucky","lucrative","luminous","lush","lustrous","luxuriant","luxurious","luxury","lyrical","magic","magical","magnanimous","magnificent","majestic","manageable","marvellous","marvelous","masterful","matchless","mature","meaningful","memorable","merciful","meritorious","merry","mesmerized","mesmerizing","meticulous","mighty","miraculous","modern","modest","momentous","monumental","motivated","navigable","neat","neatest","nice","nifty","nimble","noble","noiseless","noteworthy","nourishing","observant","obtainable","optimal","optimistic","opulent","orderly","organized","outstanding","overjoyed","painless","palatial","pampered","panoramic","paramount","passionate","patient","patri","peaceable","peaceful","peerless","peppy","perfect","permissible","personalized","phenomenal","picturesque","playful","pleasant","pleased","pleasing","pleasurable","plentiful","plush","poetic","poignant","poised","polished","polite","popular","portable","posh","positive","powerful","praiseworthy","praising","precious","precise","preeminent","preferable","premier","prestigious","pretty","priceless","principled","privileged","prize","proactive","prodigious","productive","proficient","profound","progressive","prolific","prominent","promised","promising","prompt","proper","propitious","prosperous","protective","proud","proven","prudent","punctual","pure","purposeful","quaint","qualified","quicker","quiet","quieter","radiant","rapid","rapt","rapturous","rational","reachable","readable","ready","realistic","realizable","reasonable","reasoned","receptive","recommended","redeeming","refined","reformed","refreshed","refreshing","regal","rejoicing","relaxed","reliable","remarkable","renewed","renowned","replaceable","reputable","resilient","resolute","resounding","resourceful","respectable","respectful","resplendent","responsive","restful","restored","retractable","reverent","rewarding","rich","righteous","rightful","robust","romantic","roomier","rosy","safe","saintly","salutary","sane","satisfactory","satisfied","satisfying","scenic","seamless","seasoned","secure","selective","sensational","sensible","sensitive","serene","sexy","sharp","sharper","sharpest","shiny","significant","silent","simpler","simplest","simplified","sincere","skilled","skillful","sleek","slick","smart","smarter","smartest","smelly","smiling","smitten","smooth","smoother","smoothest","snappy","snazzy","sociable","soft","softer","solid","soulful","spacious","sparkling","spectacular","speedy","spellbinding","spellbound","spirited","spiritual","splendid","spontaneous","sporty","spotless","sprightly","stable","stainless","stately","statuesque","staunch","steadfast","steadiest","steady","stellar","stimulating","stimulative","streamlined","striking","strong","stronger","strongest","stunned","stunning","stupendous","sturdier","sturdy","stylish","stylized","suave","sublime","subsidized","substantive","succeeding","successful","sufficient","suitable","sumptuous","super","superb","superior","supple","supportive","supreme","surreal","sustainable","swankier","swankiest","swanky","sweeping","sweet","sweetheart","swift","talented","tantalizing","tempting","tenacious","tender","terrific","thankful","thinner","thoughtful","thrifty","thrilled","thrilling","thriving","tidy","timely","titillating","tolerable","top","topnotch","tough","tougher","toughest","tranquil","transparent","trendy","triumphal","triumphant","trusted","trusting","trustworthy","trusty","truthful","twinkly","unabashed","unaffected","unassailable","unbeatable","unbiased","unbound","undamaged","undaunted","undisputable","undisputed","unencumbered","unequivocal","unfettered","unlimited","unmatched","unparalleled","unreal","unrestricted","unrivaled","unselfish","unwavering","upbeat","upscale","usable","useful","valiant","valuable","verifiable","veritable","versatile","vibrant","victorious","viewable","vigilant","virtuous","visionary","vivacious","vivid","warm","warmer","warmhearted","wealthy","welcome","wholesome","wieldy","winning","wise","witty","wonderful","wondrous","workable","worth","worthwhile","worthy","young","youthful","zippy"],animals:["aardvark","albatross","alligator","angelfish","angora","ant","anteater","antelope","armadillo","avocet","baboon","badger","bandicoot","barnacle","barracuda","bat","beagle","bear","beaver","bee","beetle","bird","bison","bloodhound","boar","bobcat","bonobo","buffalo","bulldog","bullfrog","butterfly","buzzard","camel","cat","caterpillar","catfish","cattle","centipede","chameleon","cheetah","chicken","chihuahua","chimpanzee","chin","chinchilla","chipmunk","civet","clam","cockroach","coon","coral","corgi","cougar","cow","coyote","crab","crane","cuttlefish","dachshund","dalmatian","dane","deer","devil","dingo","dodo","dog","dogfish","dollar","dolphin","donkey","dormouse","dragon","dragonfly","duck","dugong","eagle","earwig","eel","elephant","emperor","emu","falcon","ferret","fish","flamingo","flounder","fly","forest","fowl","fox","foxhound","frog","gar","gecko","gerbil","gharial","gibbon","giraffe","goat","goose","gopher","gorilla","grasshopper","greyhound","grouse","guppy","hamster","hare","hedgehog","heron","hippopotamus","hornet","horse","hound","hummingbird","husky","hyena","hyrax","ibis","iguana","impala","insect","jackal","jaguar","jellyfish","kangaroo","kingfisher","kiwi","koala","kudu","labradoodle","ladybird","lemming","lemur","leopard","liger","lion","lionfish","lizard","llama","lobster","lynx","macaque","macaw","magpie","malamute","maltese","mammoth","manatee","mandrill","markhor","marmoset","mastiff","mayfly","meerkat","millipede","mole","mongoose","monkey","monster","moorhen","moose","moth","mouse","mule","newt","nightingale","ocelot","octopus","okapi","orangutan","ostrich","otter","owl","oyster","panda","panther","parrot","peacock","pelican","penguin","pheasant","pig","pike","piranha","platypus","pointer","poodle","porcupine","possum","prawn","puffin","pug","puma","quail","rabbit","raccoon","rat","rattlesnake","ray","reindeer","retriever","rhinoceros","robin","rottweiler","russel","salamander","scorpion","seahorse","seal","shark","sheep","sheepdog","shrew","shrimp","skater","skunk","sloth","slug","snail","snake","snowshoe","spaniel","sparrow","spider","sponge","squid","squirrel","squirt","starfish","stingray","stoat","swan","tapir","tarantula","termite","terrier","tiger","toad","tortoise","toucan","tuatara","turkey","turtle","uakari","urchin","vole","vulture","wallaby","walrus","warthog","wasp","weasel","whale","whippet","wildebeest","wolf","wolfhound","wolverine","wombat","woodlouse","woodpecker","worm","yak","zebra","zebu","zonkey","zorse"]},capitalize=$=>$.charAt(0).toUpperCase()+$.slice(1),generateName=$=>{const I=$.length*2/3,U=$.substring(0,I),q=$.substring(I),G=capitalize(data.adjectives[parseInt(U,16)%data.adjectives.length]),K=capitalize(data.animals[parseInt(q,16)%data.animals.length]);return`${G} ${K}`};const IdentityListItem=React.forwardRef(({identity:$,presence:I,onClick:U,classNames:q,...G},K)=>{var Z,Q,ee,te,ne;const Y=keyToFallback($.identityKey),J=useId("identityListItem__label"),X=((Z=$.profile)==null?void 0:Z.displayName)??generateName($.identityKey.toHex());return React.createElement(ListItem.Root,{...G,classNames:mx("flex gap-2 pis-3 pie-1 items-center",U&&"cursor-pointer",q),onClick:()=>U==null?void 0:U(),"data-testid":"identity-list-item",labelId:J,ref:K},React.createElement(Avatar.Root,{status:I===echo.SpaceMember.PresenceState.ONLINE?"active":"inactive",labelId:J,hue:((ee=(Q=$.profile)==null?void 0:Q.data)==null?void 0:ee.hue)||Y.hue},React.createElement(Avatar.Frame,{classNames:"place-self-center"},React.createElement(Avatar.Fallback,{text:((ne=(te=$.profile)==null?void 0:te.data)==null?void 0:ne.emoji)||Y.emoji})),React.createElement(Avatar.Label,{classNames:"text-sm truncate pli-2"},X)))}),SpaceMemberList=({spaceKey:$,includeSelf:I,onSelect:U})=>{const q=reactClient.useClient(),G=echo.useMembers($),K=React.useMemo(()=>I?G.sort(Y=>Y.identity.identityKey.equals(q.halo.identity.get().identityKey)?-1:1):G.filter(Y=>!Y.identity.identityKey.equals(q.halo.identity.get().identityKey)),[G]);return React.createElement(SpaceMemberListImpl,{members:K,onSelect:U})},SpaceMemberListImpl=({members:$,onSelect:I})=>{const{t:U}=useTranslation("os"),q=$.filter(G=>G.identity);return q.length>0?React.createElement(List,{classNames:"flex flex-col gap-2","data-testid":"space-members-list"},q.map(G=>React.createElement(IdentityListItem,{key:G.identity.identityKey.toHex(),identity:G.identity,presence:G.presence,onClick:I&&(()=>I(G))}))):React.createElement("div",{role:"none",className:"grow flex items-center p-2"},React.createElement("p",{className:mx(descriptionText,"text-center is-full mlb-2")},U("empty space members message")))},iconProps={weight:"duotone",width:24,height:24,x:8,y:8},DeviceListItem=React.forwardRef(({device:$,onClickAdd:I,onClickEdit:U,onClickReset:q,onClickJoinExisting:G,classNames:K,...Y},J)=>{var ne;const{t:X}=useTranslation("os"),Z=keyToFallback($.deviceKey),Q=useId("identityListItem__label"),ee=$.profile?X("device name placeholder",{os:$.profile.os,platform:$.profile.platform}):generateName($.deviceKey.toHex()),te=$.kind===halo.DeviceKind.CURRENT;return React.createElement(ListItem.Root,{...Y,classNames:["flex gap-2 items-center mlb-2",K],"data-testid":`device-list-item${te?"-current":""}`,labelId:Q,ref:J},React.createElement(Avatar.Root,{status:$.presence===halo.Device.PresenceState.ONLINE?"active":"inactive",labelId:Q,hue:Z.hue,variant:"square"},React.createElement(Avatar.Frame,{classNames:"place-self-center"},(ne=$.profile)!=null&&ne.type?$.profile.type===halo.DeviceType.BROWSER?React.createElement(react.Compass,{...iconProps}):$.profile.type===halo.DeviceType.NATIVE?React.createElement(react.Desktop,{...iconProps}):[halo.DeviceType.AGENT,halo.DeviceType.AGENT_MANAGED].includes($.profile.type)?React.createElement(react.Robot,{...iconProps}):$.profile.type===halo.DeviceType.MOBILE?React.createElement(react.DeviceMobile,{...iconProps}):React.createElement(react.Devices,{...iconProps}):React.createElement(Avatar.Fallback,{text:Z.emoji})),te&&React.createElement(Tag,{color:"primary"},X("current device tag label")),React.createElement(Avatar.Label,{classNames:"flex-1 text-sm truncate"},ee),$.kind===halo.DeviceKind.CURRENT&&React.createElement(DropdownMenu2.Root,null,React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Button,{variant:"ghost",classNames:"pli-0 is-[--rail-action] bs-[--rail-action]","data-testid":`device-list-item${te?"-current":""}.options`},React.createElement("span",{className:"sr-only"},X("more options label")),React.createElement(react.DotsThree,{className:getSize(5)}))),React.createElement(DropdownMenu2.Content,null,React.createElement(DropdownMenu2.Viewport,null,React.createElement(DropdownMenu2.Item,{"data-testid":"device-list-item-current.join-existing",onClick:G},React.createElement(react.Intersect,{className:getSize(5)}),X("choose join new identity label")),React.createElement(DropdownMenu2.Item,{"data-testid":"device-list-item-current.reset",onClick:q},React.createElement(react.Power,{className:getSize(5)}),X("reset device label")))))))}),DeviceList=({devices:$,onClickAdd:I,onClickEdit:U,onClickReset:q,onClickJoinExisting:G})=>{const{t:K}=useTranslation("os");return React.createElement(React.Fragment,null,React.createElement("h2",{className:mx(descriptionText,"text-center mbs-4")},K("devices heading")),$.length>0&&React.createElement(List,null,$.map(Y=>React.createElement(DeviceListItem,{key:Y.deviceKey.toHex(),device:Y,onClickEdit:()=>U==null?void 0:U(Y),onClickReset:q,onClickJoinExisting:G}))),React.createElement(Button,{variant:"ghost",classNames:"justify-start gap-2 !pis-0 !pie-3","data-testid":"devices-panel.create-invitation",onClick:I},React.createElement("div",{role:"img",className:mx(getSize(8),"m-1 rounded-sm surface-input grid place-items-center")},React.createElement(react.Plus,{weight:"light",className:getSize(6)})),React.createElement("span",{className:"grow font-medium text-start"},K("choose add device label")),React.createElement(react.CaretRight,{weight:"bold",className:getSize(4)})))},minutesInMonth=43200,minutesInDay=1440;function getTimezoneOffsetInMilliseconds($){const I=toDate($),U=new Date(Date.UTC(I.getFullYear(),I.getMonth(),I.getDate(),I.getHours(),I.getMinutes(),I.getSeconds(),I.getMilliseconds()));return U.setUTCFullYear(I.getFullYear()),+$-+U}function compareAsc($,I){const U=toDate($),q=toDate(I),G=U.getTime()-q.getTime();return G<0?-1:G>0?1:G}function differenceInCalendarMonths($,I){const U=toDate($),q=toDate(I),G=U.getFullYear()-q.getFullYear(),K=U.getMonth()-q.getMonth();return G*12+K}function getRoundingMethod($){return I=>{const q=($?Math[$]:Math.trunc)(I);return q===0?0:q}}function differenceInMilliseconds($,I){return+toDate($)-+toDate(I)}function endOfDay($){const I=toDate($);return I.setHours(23,59,59,999),I}function endOfMonth($){const I=toDate($),U=I.getMonth();return I.setFullYear(I.getFullYear(),U+1,0),I.setHours(23,59,59,999),I}function isLastDayOfMonth($){const I=toDate($);return+endOfDay(I)==+endOfMonth(I)}function differenceInMonths($,I){const U=toDate($),q=toDate(I),G=compareAsc(U,q),K=Math.abs(differenceInCalendarMonths(U,q));let Y;if(K<1)Y=0;else{U.getMonth()===1&&U.getDate()>27&&U.setDate(30),U.setMonth(U.getMonth()-G*K);let J=compareAsc(U,q)===-G;isLastDayOfMonth(toDate($))&&K===1&&compareAsc($,q)===1&&(J=!1),Y=G*(K-Number(J))}return Y===0?0:Y}function differenceInSeconds($,I,U){const q=differenceInMilliseconds($,I)/1e3;return getRoundingMethod(U==null?void 0:U.roundingMethod)(q)}function formatDistance($,I,U){const q=getDefaultOptions(),G=(U==null?void 0:U.locale)??q.locale??enUS$1,K=2520,Y=compareAsc($,I);if(isNaN(Y))throw new RangeError("Invalid time value");const J=Object.assign({},U,{addSuffix:U==null?void 0:U.addSuffix,comparison:Y});let X,Z;Y>0?(X=toDate(I),Z=toDate($)):(X=toDate($),Z=toDate(I));const Q=differenceInSeconds(Z,X),ee=(getTimezoneOffsetInMilliseconds(Z)-getTimezoneOffsetInMilliseconds(X))/1e3,te=Math.round((Q-ee)/60);let ne;if(te<2)return U!=null&&U.includeSeconds?Q<5?G.formatDistance("lessThanXSeconds",5,J):Q<10?G.formatDistance("lessThanXSeconds",10,J):Q<20?G.formatDistance("lessThanXSeconds",20,J):Q<40?G.formatDistance("halfAMinute",0,J):Q<60?G.formatDistance("lessThanXMinutes",1,J):G.formatDistance("xMinutes",1,J):te===0?G.formatDistance("lessThanXMinutes",1,J):G.formatDistance("xMinutes",te,J);if(te<45)return G.formatDistance("xMinutes",te,J);if(te<90)return G.formatDistance("aboutXHours",1,J);if(te<minutesInDay){const ie=Math.round(te/60);return G.formatDistance("aboutXHours",ie,J)}else{if(te<K)return G.formatDistance("xDays",1,J);if(te<minutesInMonth){const ie=Math.round(te/minutesInDay);return G.formatDistance("xDays",ie,J)}else if(te<minutesInMonth*2)return ne=Math.round(te/minutesInMonth),G.formatDistance("aboutXMonths",ne,J)}if(ne=differenceInMonths(Z,X),ne<12){const ie=Math.round(te/minutesInMonth);return G.formatDistance("xMonths",ie,J)}else{const ie=ne%12,oe=Math.trunc(ne/12);return ie<3?G.formatDistance("aboutXYears",oe,J):ie<9?G.formatDistance("overXYears",oe,J):G.formatDistance("almostXYears",oe+1,J)}}function formatDistanceToNow($,I){return formatDistance($,Date.now(),I)}var LogLevel;(function($){$[$.TRACE=5]="TRACE",$[$.DEBUG=10]="DEBUG",$[$.INFO=11]="INFO",$[$.WARN=12]="WARN",$[$.ERROR=13]="ERROR"})(LogLevel||(LogLevel={}));var QueryLogsRequest;(function($){(function(I){I[I.INCLUSIVE=1]="INCLUSIVE",I[I.EXPLICIT=2]="EXPLICIT"})($.MatchingOptions||($.MatchingOptions={}))})(QueryLogsRequest||(QueryLogsRequest={}));var SystemStatus;(function($){$[$.ACTIVE=0]="ACTIVE",$[$.INACTIVE=1]="INACTIVE"})(SystemStatus||(SystemStatus={}));var GetDiagnosticsRequest;(function($){(function(I){I[I.NONE=0]="NONE",I[I.TRUNCATE=1]="TRUNCATE",I[I.HUMANIZE=2]="HUMANIZE"})($.KEY_OPTION||($.KEY_OPTION={}))})(GetDiagnosticsRequest||(GetDiagnosticsRequest={}));var Platform;(function($){(function(I){I[I.BROWSER=0]="BROWSER",I[I.SHARED_WORKER=1]="SHARED_WORKER",I[I.NODE=2]="NODE"})($.PLATFORM_TYPE||($.PLATFORM_TYPE={}))})(Platform||(Platform={}));var DeviceKind;(function($){$[$.CURRENT=0]="CURRENT",$[$.TRUSTED=1]="TRUSTED"})(DeviceKind||(DeviceKind={}));var Device;(function($){(function(I){I[I.OFFLINE=0]="OFFLINE",I[I.ONLINE=1]="ONLINE",I[I.REMOVED=2]="REMOVED"})($.PresenceState||($.PresenceState={}))})(Device||(Device={}));var SpaceMember;(function($){(function(I){I[I.OFFLINE=0]="OFFLINE",I[I.ONLINE=1]="ONLINE",I[I.REMOVED=2]="REMOVED"})($.PresenceState||($.PresenceState={}))})(SpaceMember||(SpaceMember={}));var SpaceState;(function($){$[$.INACTIVE=2]="INACTIVE",$[$.ACTIVE=6]="ACTIVE",$[$.CLOSED=1]="CLOSED",$[$.CONTROL_ONLY=7]="CONTROL_ONLY",$[$.INITIALIZING=4]="INITIALIZING",$[$.READY=3]="READY",$[$.ERROR=5]="ERROR"})(SpaceState||(SpaceState={}));var CreateEpochRequest;(function($){(function(I){I[I.NONE=0]="NONE",I[I.INIT_AUTOMERGE=1]="INIT_AUTOMERGE",I[I.PRUNE_AUTOMERGE_ROOT_HISTORY=2]="PRUNE_AUTOMERGE_ROOT_HISTORY",I[I.FRAGMENT_AUTOMERGE_ROOT=3]="FRAGMENT_AUTOMERGE_ROOT"})($.Migration||($.Migration={}))})(CreateEpochRequest||(CreateEpochRequest={}));var Invitation;(function($){(function(I){I[I.INTERACTIVE=0]="INTERACTIVE",I[I.DELEGATED=1]="DELEGATED",I[I.MULTIUSE=2]="MULTIUSE"})($.Type||($.Type={})),function(I){I[I.DEVICE=0]="DEVICE",I[I.SPACE=1]="SPACE"}($.Kind||($.Kind={})),function(I){I[I.NONE=0]="NONE",I[I.SHARED_SECRET=1]="SHARED_SECRET",I[I.KNOWN_PUBLIC_KEY=2]="KNOWN_PUBLIC_KEY"}($.AuthMethod||($.AuthMethod={})),function(I){I[I.INIT=0]="INIT",I[I.CONNECTING=1]="CONNECTING",I[I.CONNECTED=2]="CONNECTED",I[I.READY_FOR_AUTHENTICATION=3]="READY_FOR_AUTHENTICATION",I[I.AUTHENTICATING=4]="AUTHENTICATING",I[I.SUCCESS=5]="SUCCESS",I[I.CANCELLED=6]="CANCELLED",I[I.TIMEOUT=7]="TIMEOUT",I[I.ERROR=8]="ERROR",I[I.EXPIRED=9]="EXPIRED"}($.State||($.State={}))})(Invitation||(Invitation={}));var QueryInvitationsResponse;(function($){(function(I){I[I.ADDED=0]="ADDED",I[I.REMOVED=1]="REMOVED",I[I.SAVED=2]="SAVED",I[I.LOAD_COMPLETE=3]="LOAD_COMPLETE"})($.Action||($.Action={})),function(I){I[I.CREATED=0]="CREATED",I[I.ACCEPTED=1]="ACCEPTED"}($.Type||($.Type={}))})(QueryInvitationsResponse||(QueryInvitationsResponse={}));var ConnectionState$2;(function($){$[$.OFFLINE=0]="OFFLINE",$[$.ONLINE=1]="ONLINE"})(ConnectionState$2||(ConnectionState$2={}));var ContextDisposedError=class extends Error{constructor(){super("Context disposed.")}};function _ts_decorate$7($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$8="/home/runner/work/dxos/dxos/packages/common/context/src/context.ts",MAX_SAFE_DISPOSE_CALLBACKS=300,_a$1,_b,Context=(_n=class{constructor({onError:I=G=>{if(!(G instanceof ContextDisposedError))throw this.dispose(),G},attributes:U={},parent:q}={}){this._disposeCallbacks=[],this._isDisposed=!1,this._disposePromise=void 0,this._parent=null,this.maxSafeDisposeCallbacks=MAX_SAFE_DISPOSE_CALLBACKS,this[_a$1]="Context",this[_b]=()=>this.toString(),this._onError=I,this._attributes=U,q!==void 0&&(this._parent=q)}static default(){return new _n}get disposed(){return this._isDisposed}get disposeCallbacksLength(){return this._disposeCallbacks.length}onDispose(I){return this._isDisposed&&(async()=>{try{await I()}catch(U){log$2.catch(U,void 0,{F:__dxlog_file$8,L:88,S:this,C:(q,G)=>q(...G)})}})(),this._disposeCallbacks.push(I),this._disposeCallbacks.length>this.maxSafeDisposeCallbacks&&log$2.warn("Context has a large number of dispose callbacks. This might be a memory leak.",{count:this._disposeCallbacks.length,safeThreshold:this.maxSafeDisposeCallbacks},{F:__dxlog_file$8,L:95,S:this,C:(U,q)=>U(...q)}),()=>{const U=this._disposeCallbacks.indexOf(I);U!==-1&&this._disposeCallbacks.splice(U,1)}}dispose(){if(this._disposePromise)return this._disposePromise;this._isDisposed=!0;let I;this._disposePromise=new Promise(G=>{I=G});const U=[],q=Array.from(this._disposeCallbacks).reverse();for(const G of q)U.push((async()=>{try{await G()}catch(K){log$2.catch(K,void 0,{F:__dxlog_file$8,L:138,S:this,C:(Y,J)=>Y(...J)})}})());return this._disposeCallbacks.length=0,Promise.all(U).then(()=>{I()}),this._disposePromise}raise(I){if(!this._isDisposed)try{this._onError(I)}catch(U){Promise.reject(U)}}derive({onError:I,attributes:U}={}){const q=new _n({onError:async K=>{if(!I)this.raise(K);else try{await I(K)}catch{this.raise(K)}},attributes:U}),G=this.onDispose(()=>q.dispose());return q.onDispose(G),q}getAttribute(I){if(I in this._attributes)return this._attributes[I];if(this._parent!==null)return this._parent.getAttribute(I)}toString(){return`Context(${this._isDisposed?"disposed":"active"})`}},_a$1=Symbol.toStringTag,_b=export_inspect.custom,_n);Context=_ts_decorate$7([safeInstanceof("Context")],Context);var cancelWithContext=($,I)=>{let U;return Promise.race([I,new Promise((q,G)=>{U=$.onDispose(()=>G(new ContextDisposedError))})]).finally(()=>U==null?void 0:U())},LifecycleState;(function($){$.CLOSED="CLOSED",$.OPEN="OPEN",$.ERROR="ERROR"})(LifecycleState||(LifecycleState={}));var Observable$2={};Object.defineProperty(Observable$2,"__esModule",{value:!0}),Observable$2.Observable=void 0;const hasSymbol=$=>!!Symbol[$],getSymbol=$=>hasSymbol($)?Symbol[$]:"@@"+$,SymbolIterator=getSymbol("iterator"),SymbolObservable=getSymbol("observable"),SymbolSpecies=getSymbol("species");function getMethod($,I){let U=$[I];if(U!=null){if(typeof U!="function")throw new TypeError(U+" is not a function");return U}}function getSpecies($){let I=$.constructor;return I!==void 0&&(I=I[SymbolSpecies],I===null&&(I=void 0)),I!==void 0?I:Observable$1}function isObservable$1($){return $ instanceof Observable$1}function hostReportError($){hostReportError.log?hostReportError.log($):setTimeout(()=>{throw $})}function enqueue($){Promise.resolve().then(()=>{try{$()}catch(I){hostReportError(I)}})}function cleanupSubscription($){let I=$._cleanup;if(I!==void 0&&($._cleanup=void 0,!!I))try{if(typeof I=="function")I();else{let U=getMethod(I,"unsubscribe");U&&U.call(I)}}catch(U){hostReportError(U)}}function closeSubscription($){$._observer=void 0,$._queue=void 0,$._state="closed"}function flushSubscription($){let I=$._queue;if(I){$._queue=void 0,$._state="ready";for(let U=0;U<I.length&&(notifySubscription($,I[U].type,I[U].value),$._state!=="closed");++U);}}function notifySubscription($,I,U){$._state="running";let q=$._observer;try{let G=getMethod(q,I);switch(I){case"next":G&&G.call(q,U);break;case"error":if(closeSubscription($),G)G.call(q,U);else throw U;break;case"complete":closeSubscription($),G&&G.call(q);break}}catch(G){hostReportError(G)}$._state==="closed"?cleanupSubscription($):$._state==="running"&&($._state="ready")}function onNotify($,I,U){if($._state!=="closed"){if($._state==="buffering"){$._queue.push({type:I,value:U});return}if($._state!=="ready"){$._state="buffering",$._queue=[{type:I,value:U}],enqueue(()=>flushSubscription($));return}notifySubscription($,I,U)}}class Subscription{constructor(I,U){this._cleanup=void 0,this._observer=I,this._queue=void 0,this._state="initializing";let q=this,G={get closed(){return q._state==="closed"},next(K){onNotify(q,"next",K)},error(K){onNotify(q,"error",K)},complete(){onNotify(q,"complete")}};try{this._cleanup=U.call(void 0,G)}catch(K){G.error(K)}this._state==="initializing"&&(this._state="ready")}get closed(){return this._state==="closed"}unsubscribe(){this._state!=="closed"&&(closeSubscription(this),cleanupSubscription(this))}}let Observable$1=class dr{constructor(I){if(!(this instanceof dr))throw new TypeError("Observable cannot be called as a function");if(typeof I!="function")throw new TypeError("Observable initializer must be a function");this._subscriber=I}subscribe(I){return(typeof I!="object"||I===null)&&(I={next:I,error:arguments[1],complete:arguments[2]}),new Subscription(I,this._subscriber)}forEach(I){return new Promise((U,q)=>{if(typeof I!="function"){q(new TypeError(I+" is not a function"));return}function G(){K.unsubscribe(),U()}let K=this.subscribe({next(Y){try{I(Y,G)}catch(J){q(J),K.unsubscribe()}},error:q,complete:U})})}map(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>this.subscribe({next(G){try{G=I(G)}catch(K){return q.error(K)}q.next(G)},error(G){q.error(G)},complete(){q.complete()}}))}filter(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>this.subscribe({next(G){try{if(!I(G))return}catch(K){return q.error(K)}q.next(G)},error(G){q.error(G)},complete(){q.complete()}}))}reduce(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this),q=arguments.length>1,G=!1,Y=arguments[1];return new U(J=>this.subscribe({next(X){let Z=!G;if(G=!0,!Z||q)try{Y=I(Y,X)}catch(Q){return J.error(Q)}else Y=X},error(X){J.error(X)},complete(){if(!G&&!q)return J.error(new TypeError("Cannot reduce an empty sequence"));J.next(Y),J.complete()}}))}async all(){let I=[];return await this.forEach(U=>I.push(U)),I}concat(...I){let U=getSpecies(this);return new U(q=>{let G,K=0;function Y(J){G=J.subscribe({next(X){q.next(X)},error(X){q.error(X)},complete(){K===I.length?(G=void 0,q.complete()):Y(U.from(I[K++]))}})}return Y(this),()=>{G&&(G.unsubscribe(),G=void 0)}})}flatMap(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>{let G=[],K=this.subscribe({next(J){if(I)try{J=I(J)}catch(Z){return q.error(Z)}let X=U.from(J).subscribe({next(Z){q.next(Z)},error(Z){q.error(Z)},complete(){let Z=G.indexOf(X);Z>=0&&G.splice(Z,1),Y()}});G.push(X)},error(J){q.error(J)},complete(){Y()}});function Y(){K.closed&&G.length===0&&q.complete()}return()=>{G.forEach(J=>J.unsubscribe()),K.unsubscribe()}})}[SymbolObservable](){return this}static from(I){let U=typeof this=="function"?this:dr;if(I==null)throw new TypeError(I+" is not an object");let q=getMethod(I,SymbolObservable);if(q){let G=q.call(I);if(Object(G)!==G)throw new TypeError(G+" is not an object");return isObservable$1(G)&&G.constructor===U?G:new U(K=>G.subscribe(K))}if(hasSymbol("iterator")&&(q=getMethod(I,SymbolIterator),q))return new U(G=>{enqueue(()=>{if(!G.closed){for(let K of q.call(I))if(G.next(K),G.closed)return;G.complete()}})});if(Array.isArray(I))return new U(G=>{enqueue(()=>{if(!G.closed){for(let K=0;K<I.length;++K)if(G.next(I[K]),G.closed)return;G.complete()}})});throw new TypeError(I+" is not observable")}static of(...I){let U=typeof this=="function"?this:dr;return new U(q=>{enqueue(()=>{if(!q.closed){for(let G=0;G<I.length;++G)if(q.next(I[G]),q.closed)return;q.complete()}})})}static get[SymbolSpecies](){return this}};Observable$2.Observable=Observable$1,Object.defineProperty(Observable$1,Symbol("extensions"),{value:{symbol:SymbolObservable,hostReportError},configurable:!0});var zenObservable=Observable$2.Observable;const Observable=getDefaultExportFromCjs(zenObservable);var readableBrowser={exports:{}},events={exports:{}},R=typeof Reflect=="object"?Reflect:null,ReflectApply=R&&typeof R.apply=="function"?R.apply:function(I,U,q){return Function.prototype.apply.call(I,U,q)},ReflectOwnKeys;R&&typeof R.ownKeys=="function"?ReflectOwnKeys=R.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(I){return Object.getOwnPropertyNames(I).concat(Object.getOwnPropertySymbols(I))}:ReflectOwnKeys=function(I){return Object.getOwnPropertyNames(I)};function ProcessEmitWarning($){console&&console.warn&&console.warn($)}var NumberIsNaN=Number.isNaN||function(I){return I!==I};function EventEmitter$1(){EventEmitter$1.init.call(this)}events.exports=EventEmitter$1,events.exports.once=once$2,EventEmitter$1.EventEmitter=EventEmitter$1,EventEmitter$1.prototype._events=void 0,EventEmitter$1.prototype._eventsCount=0,EventEmitter$1.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener($){if(typeof $!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof $)}Object.defineProperty(EventEmitter$1,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function($){if(typeof $!="number"||$<0||NumberIsNaN($))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+$+".");defaultMaxListeners=$}}),EventEmitter$1.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter$1.prototype.setMaxListeners=function(I){if(typeof I!="number"||I<0||NumberIsNaN(I))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+I+".");return this._maxListeners=I,this};function _getMaxListeners($){return $._maxListeners===void 0?EventEmitter$1.defaultMaxListeners:$._maxListeners}EventEmitter$1.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter$1.prototype.emit=function(I){for(var U=[],q=1;q<arguments.length;q++)U.push(arguments[q]);var G=I==="error",K=this._events;if(K!==void 0)G=G&&K.error===void 0;else if(!G)return!1;if(G){var Y;if(U.length>0&&(Y=U[0]),Y instanceof Error)throw Y;var J=new Error("Unhandled error."+(Y?" ("+Y.message+")":""));throw J.context=Y,J}var X=K[I];if(X===void 0)return!1;if(typeof X=="function")ReflectApply(X,this,U);else for(var Z=X.length,Q=arrayClone(X,Z),q=0;q<Z;++q)ReflectApply(Q[q],this,U);return!0};function _addListener($,I,U,q){var G,K,Y;if(checkListener(U),K=$._events,K===void 0?(K=$._events=Object.create(null),$._eventsCount=0):(K.newListener!==void 0&&($.emit("newListener",I,U.listener?U.listener:U),K=$._events),Y=K[I]),Y===void 0)Y=K[I]=U,++$._eventsCount;else if(typeof Y=="function"?Y=K[I]=q?[U,Y]:[Y,U]:q?Y.unshift(U):Y.push(U),G=_getMaxListeners($),G>0&&Y.length>G&&!Y.warned){Y.warned=!0;var J=new Error("Possible EventEmitter memory leak detected. "+Y.length+" "+String(I)+" listeners added. Use emitter.setMaxListeners() to increase limit");J.name="MaxListenersExceededWarning",J.emitter=$,J.type=I,J.count=Y.length,ProcessEmitWarning(J)}return $}EventEmitter$1.prototype.addListener=function(I,U){return _addListener(this,I,U,!1)},EventEmitter$1.prototype.on=EventEmitter$1.prototype.addListener,EventEmitter$1.prototype.prependListener=function(I,U){return _addListener(this,I,U,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap($,I,U){var q={fired:!1,wrapFn:void 0,target:$,type:I,listener:U},G=onceWrapper.bind(q);return G.listener=U,q.wrapFn=G,G}EventEmitter$1.prototype.once=function(I,U){return checkListener(U),this.on(I,_onceWrap(this,I,U)),this},EventEmitter$1.prototype.prependOnceListener=function(I,U){return checkListener(U),this.prependListener(I,_onceWrap(this,I,U)),this},EventEmitter$1.prototype.removeListener=function(I,U){var q,G,K,Y,J;if(checkListener(U),G=this._events,G===void 0)return this;if(q=G[I],q===void 0)return this;if(q===U||q.listener===U)--this._eventsCount===0?this._events=Object.create(null):(delete G[I],G.removeListener&&this.emit("removeListener",I,q.listener||U));else if(typeof q!="function"){for(K=-1,Y=q.length-1;Y>=0;Y--)if(q[Y]===U||q[Y].listener===U){J=q[Y].listener,K=Y;break}if(K<0)return this;K===0?q.shift():spliceOne(q,K),q.length===1&&(G[I]=q[0]),G.removeListener!==void 0&&this.emit("removeListener",I,J||U)}return this},EventEmitter$1.prototype.off=EventEmitter$1.prototype.removeListener,EventEmitter$1.prototype.removeAllListeners=function(I){var U,q,G;if(q=this._events,q===void 0)return this;if(q.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):q[I]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete q[I]),this;if(arguments.length===0){var K=Object.keys(q),Y;for(G=0;G<K.length;++G)Y=K[G],Y!=="removeListener"&&this.removeAllListeners(Y);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(U=q[I],typeof U=="function")this.removeListener(I,U);else if(U!==void 0)for(G=U.length-1;G>=0;G--)this.removeListener(I,U[G]);return this};function _listeners($,I,U){var q=$._events;if(q===void 0)return[];var G=q[I];return G===void 0?[]:typeof G=="function"?U?[G.listener||G]:[G]:U?unwrapListeners(G):arrayClone(G,G.length)}EventEmitter$1.prototype.listeners=function(I){return _listeners(this,I,!0)},EventEmitter$1.prototype.rawListeners=function(I){return _listeners(this,I,!1)},EventEmitter$1.listenerCount=function($,I){return typeof $.listenerCount=="function"?$.listenerCount(I):listenerCount.call($,I)},EventEmitter$1.prototype.listenerCount=listenerCount;function listenerCount($){var I=this._events;if(I!==void 0){var U=I[$];if(typeof U=="function")return 1;if(U!==void 0)return U.length}return 0}EventEmitter$1.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone($,I){for(var U=new Array(I),q=0;q<I;++q)U[q]=$[q];return U}function spliceOne($,I){for(;I+1<$.length;I++)$[I]=$[I+1];$.pop()}function unwrapListeners($){for(var I=new Array($.length),U=0;U<I.length;++U)I[U]=$[U].listener||$[U];return I}function once$2($,I){return new Promise(function(U,q){function G(Y){$.removeListener(I,K),q(Y)}function K(){typeof $.removeListener=="function"&&$.removeListener("error",G),U([].slice.call(arguments))}eventTargetAgnosticAddListener($,I,K,{once:!0}),I!=="error"&&addErrorHandlerIfEventEmitter($,G,{once:!0})})}function addErrorHandlerIfEventEmitter($,I,U){typeof $.on=="function"&&eventTargetAgnosticAddListener($,"error",I,U)}function eventTargetAgnosticAddListener($,I,U,q){if(typeof $.on=="function")q.once?$.once(I,U):$.on(I,U);else if(typeof $.addEventListener=="function")$.addEventListener(I,function G(K){q.once&&$.removeEventListener(I,G),U(K)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof $)}var eventsExports=events.exports,streamBrowser=eventsExports.EventEmitter,buffer={},base64Js={};base64Js.byteLength=byteLength,base64Js.toByteArray=toByteArray,base64Js.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i$2=0,len=code.length;i$2<len;++i$2)lookup[i$2]=code[i$2],revLookup[code.charCodeAt(i$2)]=i$2;revLookup[45]=62,revLookup[95]=63;function getLens($){var I=$.length;if(I%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var U=$.indexOf("=");U===-1&&(U=I);var q=U===I?0:4-U%4;return[U,q]}function byteLength($){var I=getLens($),U=I[0],q=I[1];return(U+q)*3/4-q}function _byteLength($,I,U){return(I+U)*3/4-U}function toByteArray($){var I,U=getLens($),q=U[0],G=U[1],K=new Arr(_byteLength($,q,G)),Y=0,J=G>0?q-4:q,X;for(X=0;X<J;X+=4)I=revLookup[$.charCodeAt(X)]<<18|revLookup[$.charCodeAt(X+1)]<<12|revLookup[$.charCodeAt(X+2)]<<6|revLookup[$.charCodeAt(X+3)],K[Y++]=I>>16&255,K[Y++]=I>>8&255,K[Y++]=I&255;return G===2&&(I=revLookup[$.charCodeAt(X)]<<2|revLookup[$.charCodeAt(X+1)]>>4,K[Y++]=I&255),G===1&&(I=revLookup[$.charCodeAt(X)]<<10|revLookup[$.charCodeAt(X+1)]<<4|revLookup[$.charCodeAt(X+2)]>>2,K[Y++]=I>>8&255,K[Y++]=I&255),K}function tripletToBase64($){return lookup[$>>18&63]+lookup[$>>12&63]+lookup[$>>6&63]+lookup[$&63]}function encodeChunk$1($,I,U){for(var q,G=[],K=I;K<U;K+=3)q=($[K]<<16&16711680)+($[K+1]<<8&65280)+($[K+2]&255),G.push(tripletToBase64(q));return G.join("")}function fromByteArray($){for(var I,U=$.length,q=U%3,G=[],K=16383,Y=0,J=U-q;Y<J;Y+=K)G.push(encodeChunk$1($,Y,Y+K>J?J:Y+K));return q===1?(I=$[U-1],G.push(lookup[I>>2]+lookup[I<<4&63]+"==")):q===2&&(I=($[U-2]<<8)+$[U-1],G.push(lookup[I>>10]+lookup[I>>4&63]+lookup[I<<2&63]+"=")),G.join("")}var ieee754={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ieee754.read=function($,I,U,q,G){var K,Y,J=G*8-q-1,X=(1<<J)-1,Z=X>>1,Q=-7,ee=U?G-1:0,te=U?-1:1,ne=$[I+ee];for(ee+=te,K=ne&(1<<-Q)-1,ne>>=-Q,Q+=J;Q>0;K=K*256+$[I+ee],ee+=te,Q-=8);for(Y=K&(1<<-Q)-1,K>>=-Q,Q+=q;Q>0;Y=Y*256+$[I+ee],ee+=te,Q-=8);if(K===0)K=1-Z;else{if(K===X)return Y?NaN:(ne?-1:1)*(1/0);Y=Y+Math.pow(2,q),K=K-Z}return(ne?-1:1)*Y*Math.pow(2,K-q)},ieee754.write=function($,I,U,q,G,K){var Y,J,X,Z=K*8-G-1,Q=(1<<Z)-1,ee=Q>>1,te=G===23?Math.pow(2,-24)-Math.pow(2,-77):0,ne=q?0:K-1,ie=q?1:-1,oe=I<0||I===0&&1/I<0?1:0;for(I=Math.abs(I),isNaN(I)||I===1/0?(J=isNaN(I)?1:0,Y=Q):(Y=Math.floor(Math.log(I)/Math.LN2),I*(X=Math.pow(2,-Y))<1&&(Y--,X*=2),Y+ee>=1?I+=te/X:I+=te*Math.pow(2,1-ee),I*X>=2&&(Y++,X/=2),Y+ee>=Q?(J=0,Y=Q):Y+ee>=1?(J=(I*X-1)*Math.pow(2,G),Y=Y+ee):(J=I*Math.pow(2,ee-1)*Math.pow(2,G),Y=0));G>=8;$[U+ne]=J&255,ne+=ie,J/=256,G-=8);for(Y=Y<<G|J,Z+=G;Z>0;$[U+ne]=Y&255,ne+=ie,Y/=256,Z-=8);$[U+ne-ie]|=oe*128};/*!
|
|
846
|
+
`;function $e5534fc185f7111e$export$2e2bcd8739ae039($){const I=React.useRef(null),U=React.useRef(null);return U.current&&U.current.update($),React.useEffect(()=>(U.current=new $efa000751917694d$export$2e2bcd8739ae039({...$,ref:I}),()=>{U.current=null}),[]),React.createElement("div",{ref:I})}const EmojiPickerToolbarButton=({disabled:$,defaultEmoji:I,emoji:U,onChangeEmoji:q,classNames:G})=>{const{t:K}=useTranslation("os"),[Y,J]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:U,onChange:q,defaultProp:I}),[X,Z]=React.useState(!1),Q=React.useRef(!1),[ee,te]=React.useState(!1);return React.createElement(Tooltip.Root,{open:ee,onOpenChange:ne=>{Q.current?(te(!1),Q.current=!1):te(ne)}},React.createElement(Popover.Root,{open:X,onOpenChange:ne=>{Z(ne),Q.current=!0}},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Popover.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:["gap-2 text-2xl plb-1",G],disabled:$},React.createElement("span",{className:"sr-only"},K("select emoji label")),React.createElement(react.ImageSquare,{className:getSize(5)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},K("select emoji label"),React.createElement(Tooltip.Arrow,null))),React.createElement(Popover.Content,{side:"bottom",onKeyDownCapture:ne=>{ne.key==="Escape"&&(ne.stopPropagation(),Z(!1),Q.current=!0)}},React.createElement($e5534fc185f7111e$export$2e2bcd8739ae039,{data:emojiData,onEmojiSelect:({native:ne})=>{ne&&(J(ne),Z(!1))},autoFocus:!0,maxFrequentRows:0,noCountryFlags:!0}),React.createElement(Popover.Arrow,null))))},HuePreview=({hue:$})=>{const{tx:I}=useThemeContext();return React.createElement("svg",{width:12,height:12,viewBox:"0 0 12 12"},React.createElement("rect",{x:0,y:0,width:12,height:12,className:I("hue.fill","select--hue__preview",{hue:$})}))},HuePickerToolbarButton=({disabled:$,hue:I,onChangeHue:U,classNames:q,defaultHue:G})=>{const{t:K}=useTranslation("os"),[Y,J]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:I,onChange:U,defaultProp:G}),[X,Z]=React.useState(!1),Q=React.useRef(!1),[ee,te]=React.useState(!1);return React.createElement(Tooltip.Root,{open:ee,onOpenChange:ne=>{Q.current?(te(!1),Q.current=!1):te(ne)}},React.createElement(DropdownMenu2.Root,{modal:!1,open:X,onOpenChange:ne=>{Z(ne),Q.current=!0}},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:mx("gap-2 plb-1",q),disabled:$},React.createElement("span",{className:"sr-only"},K("select hue label")),React.createElement(react.Palette,{className:getSize(5)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},K("select hue label"),React.createElement(Tooltip.Arrow,null))),React.createElement(DropdownMenu2.Content,{side:"bottom"},React.createElement(DropdownMenu2.Viewport,null,Object.keys(hueTokenThemes).map(ne=>React.createElement(DropdownMenu2.CheckboxItem,{key:ne,checked:ne===Y,onCheckedChange:()=>J(ne)},React.createElement(HuePreview,{hue:ne}),React.createElement("span",{className:"grow"},K(`${ne} label`)),React.createElement(DropdownMenu2.ItemIndicator,null,React.createElement(react.Check,null))))),React.createElement(DropdownMenu2.Arrow,null))))};var data={adjectives:["abundant","accessible","accomplished","accurate","achievable","adaptable","adaptive","adequate","adjustable","admirable","admiring","adorable","adored","adoring","adroit","adulatory","advanced","advantageous","adventurous","affable","affectionate","affirmative","affluent","affordable","agile","agreeable","alluring","altruistic","amazed","amazing","ambitious","amenable","amiable","amicable","ample","amusing","angelic","appealing","appreciable","appreciated","appreciative","appropriate","ardent","articulate","artistic","assuring","astonished","astonishing","astounded","astounding","athletic","attentive","attractive","audible","auspicious","authentic","autonomous","available","avid","awed","awesome","awestruck","beauteous","beautiful","believable","beloved","beneficent","beneficial","benevolent","blameless","blissful","blithe","bonny","booming","boundless","bountiful","brainiest","brainy","brave","breathtaking","bright","brighter","brightest","brilliant","brisk","brotherly","bullish","buoyant","calm","calming","capable","captivating","carefree","catchy","celebrated","celebratory","champion","charismatic","charitable","charming","chaste","cheaper","cheapest","cheerful","cheery","cherished","chivalrous","classic","classy","clean","cleaner","cleanest","cleanly","clear","cleared","clearer","clever","coherent","cohesive","colorful","comely","comfortable","comforting","comfy","commendable","commodious","compact","compatible","competitive","compliant","conciliatory","concise","confident","congenial","considerate","consistent","constructive","consummate","contrasty","convenient","convincing","cool","coolest","cooperative","correct","courageous","courteous","courtly","cozy","creative","credible","crisp","crisper","cushy","cute","daring","darling","dashing","dauntless","dazzled","dazzling","decent","decisive","dedicated","defeated","deft","delectable","delicate","delicious","delighted","delightful","dependable","deserving","desirable","desirous","detachable","devout","dexterous","dextrous","dignified","diligent","diplomatic","distinctive","diversified","divine","dominated","dumbfounded","durable","dynamic","eager","earnest","eased","easy","easygoing","ebullient","economical","ecstatic","educated","effective","efficacious","efficient","effortless","effusive","elated","elegant","elite","eloquent","eminent","enchanted","enchanting","encouraging","endearing","endorsed","energetic","engaging","engrossing","enhanced","enjoyable","enraptured","enterprising","entertaining","enthralled","enthusiastic","enticing","entranced","entrancing","enviable","envious","equitable","erudite","ethical","euphoric","evaluative","eventful","everlasting","evocative","exalted","exalting","exceeding","excellent","exceptional","excited","exciting","exemplary","exhilarating","expansive","exquisite","exuberant","exultant","fabulous","fair","faithful","famed","famous","fancier","fancy","fantastic","fascinating","fashionable","fast","faster","fastest","faultless","favorable","favored","favorite","fearless","feasible","feisty","felicitous","fertile","fervent","fervid","festive","fiery","fine","finer","finest","firmer","flashy","flatter","flattering","flawless","flexible","flourishing","fluent","fond","foolproof","foremost","formidable","fortuitous","fortunate","fragrant","free","freed","fresh","fresher","freshest","friendly","frugal","fruitful","fun","funny","futuristic","gainful","gallant","galore","generous","genial","gentle","gentlest","genuine","gifted","glad","glamorous","gleeful","glimmering","glistening","glorious","glowing","godlike","gold","golden","good","goodly","gorgeous","graceful","gracious","grand","grateful","gratified","gratifying","great","greatest","guiltless","gutsy","halcyon","hale","hallowed","handier","handsome","handy","happier","happy","hardier","hardy","harmless","harmonious","healthful","healthy","heartening","heartfelt","heartwarming","heavenly","helpful","heroic","hilarious","holy","honest","honorable","honored","hopeful","hospitable","hot","hottest","humane","humble","humorous","humourous","ideal","idolized","idyllic","illuminating","illustrious","imaginative","immaculate","immense","impartial","impassioned","impeccable","important","impressed","impressive","improved","improving","incredible","indebted","indulgent","industrious","inestimable","inexpensive","infallible","influential","ingenious","ingenuous","innocuous","innovative","insightful","inspiring","instructive","instrumental","intelligent","intelligible","interesting","intimate","intricate","intriguing","intuitive","invaluable","inventive","invigorating","invincible","inviolable","inviolate","invulnerable","irresistible","jolly","jovial","joyful","joyous","jubilant","judicious","keen","kindly","laudable","lavish","lawful","leading","lean","legendary","lighter","likable","like","liked","lionhearted","lively","logical","lovable","loved","lovely","loving","loyal","lucid","luckier","luckiest","lucky","lucrative","luminous","lush","lustrous","luxuriant","luxurious","luxury","lyrical","magic","magical","magnanimous","magnificent","majestic","manageable","marvellous","marvelous","masterful","matchless","mature","meaningful","memorable","merciful","meritorious","merry","mesmerized","mesmerizing","meticulous","mighty","miraculous","modern","modest","momentous","monumental","motivated","navigable","neat","neatest","nice","nifty","nimble","noble","noiseless","noteworthy","nourishing","observant","obtainable","optimal","optimistic","opulent","orderly","organized","outstanding","overjoyed","painless","palatial","pampered","panoramic","paramount","passionate","patient","patri","peaceable","peaceful","peerless","peppy","perfect","permissible","personalized","phenomenal","picturesque","playful","pleasant","pleased","pleasing","pleasurable","plentiful","plush","poetic","poignant","poised","polished","polite","popular","portable","posh","positive","powerful","praiseworthy","praising","precious","precise","preeminent","preferable","premier","prestigious","pretty","priceless","principled","privileged","prize","proactive","prodigious","productive","proficient","profound","progressive","prolific","prominent","promised","promising","prompt","proper","propitious","prosperous","protective","proud","proven","prudent","punctual","pure","purposeful","quaint","qualified","quicker","quiet","quieter","radiant","rapid","rapt","rapturous","rational","reachable","readable","ready","realistic","realizable","reasonable","reasoned","receptive","recommended","redeeming","refined","reformed","refreshed","refreshing","regal","rejoicing","relaxed","reliable","remarkable","renewed","renowned","replaceable","reputable","resilient","resolute","resounding","resourceful","respectable","respectful","resplendent","responsive","restful","restored","retractable","reverent","rewarding","rich","righteous","rightful","robust","romantic","roomier","rosy","safe","saintly","salutary","sane","satisfactory","satisfied","satisfying","scenic","seamless","seasoned","secure","selective","sensational","sensible","sensitive","serene","sexy","sharp","sharper","sharpest","shiny","significant","silent","simpler","simplest","simplified","sincere","skilled","skillful","sleek","slick","smart","smarter","smartest","smelly","smiling","smitten","smooth","smoother","smoothest","snappy","snazzy","sociable","soft","softer","solid","soulful","spacious","sparkling","spectacular","speedy","spellbinding","spellbound","spirited","spiritual","splendid","spontaneous","sporty","spotless","sprightly","stable","stainless","stately","statuesque","staunch","steadfast","steadiest","steady","stellar","stimulating","stimulative","streamlined","striking","strong","stronger","strongest","stunned","stunning","stupendous","sturdier","sturdy","stylish","stylized","suave","sublime","subsidized","substantive","succeeding","successful","sufficient","suitable","sumptuous","super","superb","superior","supple","supportive","supreme","surreal","sustainable","swankier","swankiest","swanky","sweeping","sweet","sweetheart","swift","talented","tantalizing","tempting","tenacious","tender","terrific","thankful","thinner","thoughtful","thrifty","thrilled","thrilling","thriving","tidy","timely","titillating","tolerable","top","topnotch","tough","tougher","toughest","tranquil","transparent","trendy","triumphal","triumphant","trusted","trusting","trustworthy","trusty","truthful","twinkly","unabashed","unaffected","unassailable","unbeatable","unbiased","unbound","undamaged","undaunted","undisputable","undisputed","unencumbered","unequivocal","unfettered","unlimited","unmatched","unparalleled","unreal","unrestricted","unrivaled","unselfish","unwavering","upbeat","upscale","usable","useful","valiant","valuable","verifiable","veritable","versatile","vibrant","victorious","viewable","vigilant","virtuous","visionary","vivacious","vivid","warm","warmer","warmhearted","wealthy","welcome","wholesome","wieldy","winning","wise","witty","wonderful","wondrous","workable","worth","worthwhile","worthy","young","youthful","zippy"],animals:["aardvark","albatross","alligator","angelfish","angora","ant","anteater","antelope","armadillo","avocet","baboon","badger","bandicoot","barnacle","barracuda","bat","beagle","bear","beaver","bee","beetle","bird","bison","bloodhound","boar","bobcat","bonobo","buffalo","bulldog","bullfrog","butterfly","buzzard","camel","cat","caterpillar","catfish","cattle","centipede","chameleon","cheetah","chicken","chihuahua","chimpanzee","chin","chinchilla","chipmunk","civet","clam","cockroach","coon","coral","corgi","cougar","cow","coyote","crab","crane","cuttlefish","dachshund","dalmatian","dane","deer","devil","dingo","dodo","dog","dogfish","dollar","dolphin","donkey","dormouse","dragon","dragonfly","duck","dugong","eagle","earwig","eel","elephant","emperor","emu","falcon","ferret","fish","flamingo","flounder","fly","forest","fowl","fox","foxhound","frog","gar","gecko","gerbil","gharial","gibbon","giraffe","goat","goose","gopher","gorilla","grasshopper","greyhound","grouse","guppy","hamster","hare","hedgehog","heron","hippopotamus","hornet","horse","hound","hummingbird","husky","hyena","hyrax","ibis","iguana","impala","insect","jackal","jaguar","jellyfish","kangaroo","kingfisher","kiwi","koala","kudu","labradoodle","ladybird","lemming","lemur","leopard","liger","lion","lionfish","lizard","llama","lobster","lynx","macaque","macaw","magpie","malamute","maltese","mammoth","manatee","mandrill","markhor","marmoset","mastiff","mayfly","meerkat","millipede","mole","mongoose","monkey","monster","moorhen","moose","moth","mouse","mule","newt","nightingale","ocelot","octopus","okapi","orangutan","ostrich","otter","owl","oyster","panda","panther","parrot","peacock","pelican","penguin","pheasant","pig","pike","piranha","platypus","pointer","poodle","porcupine","possum","prawn","puffin","pug","puma","quail","rabbit","raccoon","rat","rattlesnake","ray","reindeer","retriever","rhinoceros","robin","rottweiler","russel","salamander","scorpion","seahorse","seal","shark","sheep","sheepdog","shrew","shrimp","skater","skunk","sloth","slug","snail","snake","snowshoe","spaniel","sparrow","spider","sponge","squid","squirrel","squirt","starfish","stingray","stoat","swan","tapir","tarantula","termite","terrier","tiger","toad","tortoise","toucan","tuatara","turkey","turtle","uakari","urchin","vole","vulture","wallaby","walrus","warthog","wasp","weasel","whale","whippet","wildebeest","wolf","wolfhound","wolverine","wombat","woodlouse","woodpecker","worm","yak","zebra","zebu","zonkey","zorse"]},capitalize=$=>$.charAt(0).toUpperCase()+$.slice(1),generateName=$=>{const I=$.length*2/3,U=$.substring(0,I),q=$.substring(I),G=capitalize(data.adjectives[parseInt(U,16)%data.adjectives.length]),K=capitalize(data.animals[parseInt(q,16)%data.animals.length]);return`${G} ${K}`};const IdentityListItem=React.forwardRef(({identity:$,presence:I,onClick:U,classNames:q,...G},K)=>{var Z,Q,ee,te,ne;const Y=keyToFallback($.identityKey),J=useId("identityListItem__label"),X=((Z=$.profile)==null?void 0:Z.displayName)??generateName($.identityKey.toHex());return React.createElement(ListItem.Root,{...G,classNames:mx("flex gap-2 pis-3 pie-1 items-center",U&&"cursor-pointer",q),onClick:()=>U==null?void 0:U(),"data-testid":"identity-list-item",labelId:J,ref:K},React.createElement(Avatar.Root,{status:I===echo.SpaceMember.PresenceState.ONLINE?"active":"inactive",labelId:J,hue:((ee=(Q=$.profile)==null?void 0:Q.data)==null?void 0:ee.hue)||Y.hue},React.createElement(Avatar.Frame,{classNames:"place-self-center"},React.createElement(Avatar.Fallback,{text:((ne=(te=$.profile)==null?void 0:te.data)==null?void 0:ne.emoji)||Y.emoji})),React.createElement(Avatar.Label,{classNames:"text-sm truncate pli-2"},X)))}),SpaceMemberList=({spaceKey:$,includeSelf:I,onSelect:U})=>{const q=reactClient.useClient(),G=echo.useMembers($),K=React.useMemo(()=>I?G.sort(Y=>Y.identity.identityKey.equals(q.halo.identity.get().identityKey)?-1:1):G.filter(Y=>!Y.identity.identityKey.equals(q.halo.identity.get().identityKey)),[G]);return React.createElement(SpaceMemberListImpl,{members:K,onSelect:U})},SpaceMemberListImpl=({members:$,onSelect:I})=>{const{t:U}=useTranslation("os"),q=$.filter(G=>G.identity);return q.length>0?React.createElement(List,{classNames:"flex flex-col gap-2","data-testid":"space-members-list"},q.map(G=>React.createElement(IdentityListItem,{key:G.identity.identityKey.toHex(),identity:G.identity,presence:G.presence,onClick:I&&(()=>I(G))}))):React.createElement("div",{role:"none",className:"grow flex items-center p-2"},React.createElement("p",{className:mx(descriptionText,"text-center is-full mlb-2")},U("empty space members message")))},iconProps={weight:"duotone",width:24,height:24,x:8,y:8},DeviceListItem=React.forwardRef(({device:$,onClickAdd:I,onClickEdit:U,onClickReset:q,onClickJoinExisting:G,classNames:K,...Y},J)=>{var ne;const{t:X}=useTranslation("os"),Z=keyToFallback($.deviceKey),Q=useId("identityListItem__label"),ee=$.profile?X("device name placeholder",{os:$.profile.os,platform:$.profile.platform}):generateName($.deviceKey.toHex()),te=$.kind===halo.DeviceKind.CURRENT;return React.createElement(ListItem.Root,{...Y,classNames:["flex gap-2 items-center mlb-2",K],"data-testid":`device-list-item${te?"-current":""}`,labelId:Q,ref:J},React.createElement(Avatar.Root,{status:$.presence===halo.Device.PresenceState.ONLINE?"active":"inactive",labelId:Q,hue:Z.hue,variant:"square"},React.createElement(Avatar.Frame,{classNames:"place-self-center"},(ne=$.profile)!=null&&ne.type?$.profile.type===halo.DeviceType.BROWSER?React.createElement(react.Compass,{...iconProps}):$.profile.type===halo.DeviceType.NATIVE?React.createElement(react.Desktop,{...iconProps}):[halo.DeviceType.AGENT,halo.DeviceType.AGENT_MANAGED].includes($.profile.type)?React.createElement(react.Robot,{...iconProps}):$.profile.type===halo.DeviceType.MOBILE?React.createElement(react.DeviceMobile,{...iconProps}):React.createElement(react.Devices,{...iconProps}):React.createElement(Avatar.Fallback,{text:Z.emoji})),te&&React.createElement(Tag,{color:"primary"},X("current device tag label")),React.createElement(Avatar.Label,{classNames:"flex-1 text-sm truncate"},ee),$.kind===halo.DeviceKind.CURRENT&&React.createElement(DropdownMenu2.Root,null,React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Button,{variant:"ghost",classNames:"pli-0 is-[--rail-action] bs-[--rail-action]","data-testid":`device-list-item${te?"-current":""}.options`},React.createElement("span",{className:"sr-only"},X("more options label")),React.createElement(react.DotsThree,{className:getSize(5)}))),React.createElement(DropdownMenu2.Content,null,React.createElement(DropdownMenu2.Viewport,null,React.createElement(DropdownMenu2.Item,{"data-testid":"device-list-item-current.join-existing",onClick:G},React.createElement(react.Intersect,{className:getSize(5)}),X("choose join new identity label")),React.createElement(DropdownMenu2.Item,{"data-testid":"device-list-item-current.reset",onClick:q},React.createElement(react.Power,{className:getSize(5)}),X("reset device label")))))))}),DeviceList=({devices:$,onClickAdd:I,onClickEdit:U,onClickReset:q,onClickJoinExisting:G})=>{const{t:K}=useTranslation("os");return React.createElement(React.Fragment,null,React.createElement("h2",{className:mx(descriptionText,"text-center mbs-4")},K("devices heading")),$.length>0&&React.createElement(List,null,$.map(Y=>React.createElement(DeviceListItem,{key:Y.deviceKey.toHex(),device:Y,onClickEdit:()=>U==null?void 0:U(Y),onClickReset:q,onClickJoinExisting:G}))),React.createElement(Button,{variant:"ghost",classNames:"justify-start gap-2 !pis-0 !pie-3","data-testid":"devices-panel.create-invitation",onClick:I},React.createElement("div",{role:"img",className:mx(getSize(8),"m-1 rounded-sm surface-input grid place-items-center")},React.createElement(react.Plus,{weight:"light",className:getSize(6)})),React.createElement("span",{className:"grow font-medium text-start"},K("choose add device label")),React.createElement(react.CaretRight,{weight:"bold",className:getSize(4)})))},minutesInMonth=43200,minutesInDay=1440;function getTimezoneOffsetInMilliseconds($){const I=toDate($),U=new Date(Date.UTC(I.getFullYear(),I.getMonth(),I.getDate(),I.getHours(),I.getMinutes(),I.getSeconds(),I.getMilliseconds()));return U.setUTCFullYear(I.getFullYear()),+$-+U}function compareAsc($,I){const U=toDate($),q=toDate(I),G=U.getTime()-q.getTime();return G<0?-1:G>0?1:G}function differenceInCalendarMonths($,I){const U=toDate($),q=toDate(I),G=U.getFullYear()-q.getFullYear(),K=U.getMonth()-q.getMonth();return G*12+K}function getRoundingMethod($){return I=>{const q=($?Math[$]:Math.trunc)(I);return q===0?0:q}}function differenceInMilliseconds($,I){return+toDate($)-+toDate(I)}function endOfDay($){const I=toDate($);return I.setHours(23,59,59,999),I}function endOfMonth($){const I=toDate($),U=I.getMonth();return I.setFullYear(I.getFullYear(),U+1,0),I.setHours(23,59,59,999),I}function isLastDayOfMonth($){const I=toDate($);return+endOfDay(I)==+endOfMonth(I)}function differenceInMonths($,I){const U=toDate($),q=toDate(I),G=compareAsc(U,q),K=Math.abs(differenceInCalendarMonths(U,q));let Y;if(K<1)Y=0;else{U.getMonth()===1&&U.getDate()>27&&U.setDate(30),U.setMonth(U.getMonth()-G*K);let J=compareAsc(U,q)===-G;isLastDayOfMonth(toDate($))&&K===1&&compareAsc($,q)===1&&(J=!1),Y=G*(K-Number(J))}return Y===0?0:Y}function differenceInSeconds($,I,U){const q=differenceInMilliseconds($,I)/1e3;return getRoundingMethod(U==null?void 0:U.roundingMethod)(q)}function formatDistance($,I,U){const q=getDefaultOptions(),G=(U==null?void 0:U.locale)??q.locale??enUS$1,K=2520,Y=compareAsc($,I);if(isNaN(Y))throw new RangeError("Invalid time value");const J=Object.assign({},U,{addSuffix:U==null?void 0:U.addSuffix,comparison:Y});let X,Z;Y>0?(X=toDate(I),Z=toDate($)):(X=toDate($),Z=toDate(I));const Q=differenceInSeconds(Z,X),ee=(getTimezoneOffsetInMilliseconds(Z)-getTimezoneOffsetInMilliseconds(X))/1e3,te=Math.round((Q-ee)/60);let ne;if(te<2)return U!=null&&U.includeSeconds?Q<5?G.formatDistance("lessThanXSeconds",5,J):Q<10?G.formatDistance("lessThanXSeconds",10,J):Q<20?G.formatDistance("lessThanXSeconds",20,J):Q<40?G.formatDistance("halfAMinute",0,J):Q<60?G.formatDistance("lessThanXMinutes",1,J):G.formatDistance("xMinutes",1,J):te===0?G.formatDistance("lessThanXMinutes",1,J):G.formatDistance("xMinutes",te,J);if(te<45)return G.formatDistance("xMinutes",te,J);if(te<90)return G.formatDistance("aboutXHours",1,J);if(te<minutesInDay){const ie=Math.round(te/60);return G.formatDistance("aboutXHours",ie,J)}else{if(te<K)return G.formatDistance("xDays",1,J);if(te<minutesInMonth){const ie=Math.round(te/minutesInDay);return G.formatDistance("xDays",ie,J)}else if(te<minutesInMonth*2)return ne=Math.round(te/minutesInMonth),G.formatDistance("aboutXMonths",ne,J)}if(ne=differenceInMonths(Z,X),ne<12){const ie=Math.round(te/minutesInMonth);return G.formatDistance("xMonths",ie,J)}else{const ie=ne%12,oe=Math.trunc(ne/12);return ie<3?G.formatDistance("aboutXYears",oe,J):ie<9?G.formatDistance("overXYears",oe,J):G.formatDistance("almostXYears",oe+1,J)}}function formatDistanceToNow($,I){return formatDistance($,Date.now(),I)}var RPC_TIMEOUT=2e4,LogLevel;(function($){$[$.TRACE=5]="TRACE",$[$.DEBUG=10]="DEBUG",$[$.INFO=11]="INFO",$[$.WARN=12]="WARN",$[$.ERROR=13]="ERROR"})(LogLevel||(LogLevel={}));var QueryLogsRequest;(function($){(function(I){I[I.INCLUSIVE=1]="INCLUSIVE",I[I.EXPLICIT=2]="EXPLICIT"})($.MatchingOptions||($.MatchingOptions={}))})(QueryLogsRequest||(QueryLogsRequest={}));var SystemStatus;(function($){$[$.ACTIVE=0]="ACTIVE",$[$.INACTIVE=1]="INACTIVE"})(SystemStatus||(SystemStatus={}));var GetDiagnosticsRequest;(function($){(function(I){I[I.NONE=0]="NONE",I[I.TRUNCATE=1]="TRUNCATE",I[I.HUMANIZE=2]="HUMANIZE"})($.KEY_OPTION||($.KEY_OPTION={}))})(GetDiagnosticsRequest||(GetDiagnosticsRequest={}));var Platform;(function($){(function(I){I[I.BROWSER=0]="BROWSER",I[I.SHARED_WORKER=1]="SHARED_WORKER",I[I.NODE=2]="NODE"})($.PLATFORM_TYPE||($.PLATFORM_TYPE={}))})(Platform||(Platform={}));var DeviceKind;(function($){$[$.CURRENT=0]="CURRENT",$[$.TRUSTED=1]="TRUSTED"})(DeviceKind||(DeviceKind={}));var Device;(function($){(function(I){I[I.OFFLINE=0]="OFFLINE",I[I.ONLINE=1]="ONLINE",I[I.REMOVED=2]="REMOVED"})($.PresenceState||($.PresenceState={}))})(Device||(Device={}));var SpaceMember;(function($){(function(I){I[I.OFFLINE=0]="OFFLINE",I[I.ONLINE=1]="ONLINE",I[I.REMOVED=2]="REMOVED"})($.PresenceState||($.PresenceState={}))})(SpaceMember||(SpaceMember={}));var SpaceState;(function($){$[$.INACTIVE=2]="INACTIVE",$[$.ACTIVE=6]="ACTIVE",$[$.CLOSED=1]="CLOSED",$[$.CONTROL_ONLY=7]="CONTROL_ONLY",$[$.INITIALIZING=4]="INITIALIZING",$[$.READY=3]="READY",$[$.ERROR=5]="ERROR"})(SpaceState||(SpaceState={}));var CreateEpochRequest;(function($){(function(I){I[I.NONE=0]="NONE",I[I.INIT_AUTOMERGE=1]="INIT_AUTOMERGE",I[I.PRUNE_AUTOMERGE_ROOT_HISTORY=2]="PRUNE_AUTOMERGE_ROOT_HISTORY",I[I.FRAGMENT_AUTOMERGE_ROOT=3]="FRAGMENT_AUTOMERGE_ROOT"})($.Migration||($.Migration={}))})(CreateEpochRequest||(CreateEpochRequest={}));var Invitation;(function($){(function(I){I[I.INTERACTIVE=0]="INTERACTIVE",I[I.DELEGATED=1]="DELEGATED",I[I.MULTIUSE=2]="MULTIUSE"})($.Type||($.Type={})),function(I){I[I.DEVICE=0]="DEVICE",I[I.SPACE=1]="SPACE"}($.Kind||($.Kind={})),function(I){I[I.NONE=0]="NONE",I[I.SHARED_SECRET=1]="SHARED_SECRET",I[I.KNOWN_PUBLIC_KEY=2]="KNOWN_PUBLIC_KEY"}($.AuthMethod||($.AuthMethod={})),function(I){I[I.INIT=0]="INIT",I[I.CONNECTING=1]="CONNECTING",I[I.CONNECTED=2]="CONNECTED",I[I.READY_FOR_AUTHENTICATION=3]="READY_FOR_AUTHENTICATION",I[I.AUTHENTICATING=4]="AUTHENTICATING",I[I.SUCCESS=5]="SUCCESS",I[I.CANCELLED=6]="CANCELLED",I[I.TIMEOUT=7]="TIMEOUT",I[I.ERROR=8]="ERROR",I[I.EXPIRED=9]="EXPIRED"}($.State||($.State={}))})(Invitation||(Invitation={}));var QueryInvitationsResponse;(function($){(function(I){I[I.ADDED=0]="ADDED",I[I.REMOVED=1]="REMOVED",I[I.SAVED=2]="SAVED",I[I.LOAD_COMPLETE=3]="LOAD_COMPLETE"})($.Action||($.Action={})),function(I){I[I.CREATED=0]="CREATED",I[I.ACCEPTED=1]="ACCEPTED"}($.Type||($.Type={}))})(QueryInvitationsResponse||(QueryInvitationsResponse={}));var ConnectionState$2;(function($){$[$.OFFLINE=0]="OFFLINE",$[$.ONLINE=1]="ONLINE"})(ConnectionState$2||(ConnectionState$2={}));var ContextDisposedError=class extends Error{constructor(){super("Context disposed.")}};function _ts_decorate$7($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$8="/home/runner/work/dxos/dxos/packages/common/context/src/context.ts",MAX_SAFE_DISPOSE_CALLBACKS=300,_a$1,_b,Context=(_n=class{constructor({onError:I=G=>{if(!(G instanceof ContextDisposedError))throw this.dispose(),G},attributes:U={},parent:q}={}){this._disposeCallbacks=[],this._isDisposed=!1,this._disposePromise=void 0,this._parent=null,this.maxSafeDisposeCallbacks=MAX_SAFE_DISPOSE_CALLBACKS,this[_a$1]="Context",this[_b]=()=>this.toString(),this._onError=I,this._attributes=U,q!==void 0&&(this._parent=q)}static default(){return new _n}get disposed(){return this._isDisposed}get disposeCallbacksLength(){return this._disposeCallbacks.length}onDispose(I){return this._isDisposed&&(async()=>{try{await I()}catch(U){log$2.catch(U,void 0,{F:__dxlog_file$8,L:88,S:this,C:(q,G)=>q(...G)})}})(),this._disposeCallbacks.push(I),this._disposeCallbacks.length>this.maxSafeDisposeCallbacks&&log$2.warn("Context has a large number of dispose callbacks. This might be a memory leak.",{count:this._disposeCallbacks.length,safeThreshold:this.maxSafeDisposeCallbacks},{F:__dxlog_file$8,L:95,S:this,C:(U,q)=>U(...q)}),()=>{const U=this._disposeCallbacks.indexOf(I);U!==-1&&this._disposeCallbacks.splice(U,1)}}async dispose(){if(this._disposePromise)return this._disposePromise;this._isDisposed=!0;let I;this._disposePromise=new Promise(q=>{I=q});const U=Array.from(this._disposeCallbacks).reverse();this._disposeCallbacks.length=0;for(const q of U)try{await q()}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$8,L:136,S:this,C:(K,Y)=>K(...Y)})}I()}raise(I){if(!this._isDisposed)try{this._onError(I)}catch(U){Promise.reject(U)}}derive({onError:I,attributes:U}={}){const q=new _n({onError:async K=>{if(!I)this.raise(K);else try{await I(K)}catch{this.raise(K)}},attributes:U}),G=this.onDispose(()=>q.dispose());return q.onDispose(G),q}getAttribute(I){if(I in this._attributes)return this._attributes[I];if(this._parent!==null)return this._parent.getAttribute(I)}toString(){return`Context(${this._isDisposed?"disposed":"active"})`}},_a$1=Symbol.toStringTag,_b=export_inspect.custom,_n);Context=_ts_decorate$7([safeInstanceof("Context")],Context);var cancelWithContext=($,I)=>{let U;return Promise.race([I,new Promise((q,G)=>{U=$.onDispose(()=>G(new ContextDisposedError))})]).finally(()=>U==null?void 0:U())},LifecycleState;(function($){$.CLOSED="CLOSED",$.OPEN="OPEN",$.ERROR="ERROR"})(LifecycleState||(LifecycleState={}));var Observable$2={};Object.defineProperty(Observable$2,"__esModule",{value:!0}),Observable$2.Observable=void 0;const hasSymbol=$=>!!Symbol[$],getSymbol=$=>hasSymbol($)?Symbol[$]:"@@"+$,SymbolIterator=getSymbol("iterator"),SymbolObservable=getSymbol("observable"),SymbolSpecies=getSymbol("species");function getMethod($,I){let U=$[I];if(U!=null){if(typeof U!="function")throw new TypeError(U+" is not a function");return U}}function getSpecies($){let I=$.constructor;return I!==void 0&&(I=I[SymbolSpecies],I===null&&(I=void 0)),I!==void 0?I:Observable$1}function isObservable$1($){return $ instanceof Observable$1}function hostReportError($){hostReportError.log?hostReportError.log($):setTimeout(()=>{throw $})}function enqueue($){Promise.resolve().then(()=>{try{$()}catch(I){hostReportError(I)}})}function cleanupSubscription($){let I=$._cleanup;if(I!==void 0&&($._cleanup=void 0,!!I))try{if(typeof I=="function")I();else{let U=getMethod(I,"unsubscribe");U&&U.call(I)}}catch(U){hostReportError(U)}}function closeSubscription($){$._observer=void 0,$._queue=void 0,$._state="closed"}function flushSubscription($){let I=$._queue;if(I){$._queue=void 0,$._state="ready";for(let U=0;U<I.length&&(notifySubscription($,I[U].type,I[U].value),$._state!=="closed");++U);}}function notifySubscription($,I,U){$._state="running";let q=$._observer;try{let G=getMethod(q,I);switch(I){case"next":G&&G.call(q,U);break;case"error":if(closeSubscription($),G)G.call(q,U);else throw U;break;case"complete":closeSubscription($),G&&G.call(q);break}}catch(G){hostReportError(G)}$._state==="closed"?cleanupSubscription($):$._state==="running"&&($._state="ready")}function onNotify($,I,U){if($._state!=="closed"){if($._state==="buffering"){$._queue.push({type:I,value:U});return}if($._state!=="ready"){$._state="buffering",$._queue=[{type:I,value:U}],enqueue(()=>flushSubscription($));return}notifySubscription($,I,U)}}class Subscription{constructor(I,U){this._cleanup=void 0,this._observer=I,this._queue=void 0,this._state="initializing";let q=this,G={get closed(){return q._state==="closed"},next(K){onNotify(q,"next",K)},error(K){onNotify(q,"error",K)},complete(){onNotify(q,"complete")}};try{this._cleanup=U.call(void 0,G)}catch(K){G.error(K)}this._state==="initializing"&&(this._state="ready")}get closed(){return this._state==="closed"}unsubscribe(){this._state!=="closed"&&(closeSubscription(this),cleanupSubscription(this))}}let Observable$1=class dr{constructor(I){if(!(this instanceof dr))throw new TypeError("Observable cannot be called as a function");if(typeof I!="function")throw new TypeError("Observable initializer must be a function");this._subscriber=I}subscribe(I){return(typeof I!="object"||I===null)&&(I={next:I,error:arguments[1],complete:arguments[2]}),new Subscription(I,this._subscriber)}forEach(I){return new Promise((U,q)=>{if(typeof I!="function"){q(new TypeError(I+" is not a function"));return}function G(){K.unsubscribe(),U()}let K=this.subscribe({next(Y){try{I(Y,G)}catch(J){q(J),K.unsubscribe()}},error:q,complete:U})})}map(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>this.subscribe({next(G){try{G=I(G)}catch(K){return q.error(K)}q.next(G)},error(G){q.error(G)},complete(){q.complete()}}))}filter(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>this.subscribe({next(G){try{if(!I(G))return}catch(K){return q.error(K)}q.next(G)},error(G){q.error(G)},complete(){q.complete()}}))}reduce(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this),q=arguments.length>1,G=!1,Y=arguments[1];return new U(J=>this.subscribe({next(X){let Z=!G;if(G=!0,!Z||q)try{Y=I(Y,X)}catch(Q){return J.error(Q)}else Y=X},error(X){J.error(X)},complete(){if(!G&&!q)return J.error(new TypeError("Cannot reduce an empty sequence"));J.next(Y),J.complete()}}))}async all(){let I=[];return await this.forEach(U=>I.push(U)),I}concat(...I){let U=getSpecies(this);return new U(q=>{let G,K=0;function Y(J){G=J.subscribe({next(X){q.next(X)},error(X){q.error(X)},complete(){K===I.length?(G=void 0,q.complete()):Y(U.from(I[K++]))}})}return Y(this),()=>{G&&(G.unsubscribe(),G=void 0)}})}flatMap(I){if(typeof I!="function")throw new TypeError(I+" is not a function");let U=getSpecies(this);return new U(q=>{let G=[],K=this.subscribe({next(J){if(I)try{J=I(J)}catch(Z){return q.error(Z)}let X=U.from(J).subscribe({next(Z){q.next(Z)},error(Z){q.error(Z)},complete(){let Z=G.indexOf(X);Z>=0&&G.splice(Z,1),Y()}});G.push(X)},error(J){q.error(J)},complete(){Y()}});function Y(){K.closed&&G.length===0&&q.complete()}return()=>{G.forEach(J=>J.unsubscribe()),K.unsubscribe()}})}[SymbolObservable](){return this}static from(I){let U=typeof this=="function"?this:dr;if(I==null)throw new TypeError(I+" is not an object");let q=getMethod(I,SymbolObservable);if(q){let G=q.call(I);if(Object(G)!==G)throw new TypeError(G+" is not an object");return isObservable$1(G)&&G.constructor===U?G:new U(K=>G.subscribe(K))}if(hasSymbol("iterator")&&(q=getMethod(I,SymbolIterator),q))return new U(G=>{enqueue(()=>{if(!G.closed){for(let K of q.call(I))if(G.next(K),G.closed)return;G.complete()}})});if(Array.isArray(I))return new U(G=>{enqueue(()=>{if(!G.closed){for(let K=0;K<I.length;++K)if(G.next(I[K]),G.closed)return;G.complete()}})});throw new TypeError(I+" is not observable")}static of(...I){let U=typeof this=="function"?this:dr;return new U(q=>{enqueue(()=>{if(!q.closed){for(let G=0;G<I.length;++G)if(q.next(I[G]),q.closed)return;q.complete()}})})}static get[SymbolSpecies](){return this}};Observable$2.Observable=Observable$1,Object.defineProperty(Observable$1,Symbol("extensions"),{value:{symbol:SymbolObservable,hostReportError},configurable:!0});var zenObservable=Observable$2.Observable;const Observable=getDefaultExportFromCjs(zenObservable);var readableBrowser={exports:{}},events={exports:{}},R=typeof Reflect=="object"?Reflect:null,ReflectApply=R&&typeof R.apply=="function"?R.apply:function(I,U,q){return Function.prototype.apply.call(I,U,q)},ReflectOwnKeys;R&&typeof R.ownKeys=="function"?ReflectOwnKeys=R.ownKeys:Object.getOwnPropertySymbols?ReflectOwnKeys=function(I){return Object.getOwnPropertyNames(I).concat(Object.getOwnPropertySymbols(I))}:ReflectOwnKeys=function(I){return Object.getOwnPropertyNames(I)};function ProcessEmitWarning($){console&&console.warn&&console.warn($)}var NumberIsNaN=Number.isNaN||function(I){return I!==I};function EventEmitter$1(){EventEmitter$1.init.call(this)}events.exports=EventEmitter$1,events.exports.once=once$2,EventEmitter$1.EventEmitter=EventEmitter$1,EventEmitter$1.prototype._events=void 0,EventEmitter$1.prototype._eventsCount=0,EventEmitter$1.prototype._maxListeners=void 0;var defaultMaxListeners=10;function checkListener($){if(typeof $!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof $)}Object.defineProperty(EventEmitter$1,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function($){if(typeof $!="number"||$<0||NumberIsNaN($))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+$+".");defaultMaxListeners=$}}),EventEmitter$1.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},EventEmitter$1.prototype.setMaxListeners=function(I){if(typeof I!="number"||I<0||NumberIsNaN(I))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+I+".");return this._maxListeners=I,this};function _getMaxListeners($){return $._maxListeners===void 0?EventEmitter$1.defaultMaxListeners:$._maxListeners}EventEmitter$1.prototype.getMaxListeners=function(){return _getMaxListeners(this)},EventEmitter$1.prototype.emit=function(I){for(var U=[],q=1;q<arguments.length;q++)U.push(arguments[q]);var G=I==="error",K=this._events;if(K!==void 0)G=G&&K.error===void 0;else if(!G)return!1;if(G){var Y;if(U.length>0&&(Y=U[0]),Y instanceof Error)throw Y;var J=new Error("Unhandled error."+(Y?" ("+Y.message+")":""));throw J.context=Y,J}var X=K[I];if(X===void 0)return!1;if(typeof X=="function")ReflectApply(X,this,U);else for(var Z=X.length,Q=arrayClone(X,Z),q=0;q<Z;++q)ReflectApply(Q[q],this,U);return!0};function _addListener($,I,U,q){var G,K,Y;if(checkListener(U),K=$._events,K===void 0?(K=$._events=Object.create(null),$._eventsCount=0):(K.newListener!==void 0&&($.emit("newListener",I,U.listener?U.listener:U),K=$._events),Y=K[I]),Y===void 0)Y=K[I]=U,++$._eventsCount;else if(typeof Y=="function"?Y=K[I]=q?[U,Y]:[Y,U]:q?Y.unshift(U):Y.push(U),G=_getMaxListeners($),G>0&&Y.length>G&&!Y.warned){Y.warned=!0;var J=new Error("Possible EventEmitter memory leak detected. "+Y.length+" "+String(I)+" listeners added. Use emitter.setMaxListeners() to increase limit");J.name="MaxListenersExceededWarning",J.emitter=$,J.type=I,J.count=Y.length,ProcessEmitWarning(J)}return $}EventEmitter$1.prototype.addListener=function(I,U){return _addListener(this,I,U,!1)},EventEmitter$1.prototype.on=EventEmitter$1.prototype.addListener,EventEmitter$1.prototype.prependListener=function(I,U){return _addListener(this,I,U,!0)};function onceWrapper(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function _onceWrap($,I,U){var q={fired:!1,wrapFn:void 0,target:$,type:I,listener:U},G=onceWrapper.bind(q);return G.listener=U,q.wrapFn=G,G}EventEmitter$1.prototype.once=function(I,U){return checkListener(U),this.on(I,_onceWrap(this,I,U)),this},EventEmitter$1.prototype.prependOnceListener=function(I,U){return checkListener(U),this.prependListener(I,_onceWrap(this,I,U)),this},EventEmitter$1.prototype.removeListener=function(I,U){var q,G,K,Y,J;if(checkListener(U),G=this._events,G===void 0)return this;if(q=G[I],q===void 0)return this;if(q===U||q.listener===U)--this._eventsCount===0?this._events=Object.create(null):(delete G[I],G.removeListener&&this.emit("removeListener",I,q.listener||U));else if(typeof q!="function"){for(K=-1,Y=q.length-1;Y>=0;Y--)if(q[Y]===U||q[Y].listener===U){J=q[Y].listener,K=Y;break}if(K<0)return this;K===0?q.shift():spliceOne(q,K),q.length===1&&(G[I]=q[0]),G.removeListener!==void 0&&this.emit("removeListener",I,J||U)}return this},EventEmitter$1.prototype.off=EventEmitter$1.prototype.removeListener,EventEmitter$1.prototype.removeAllListeners=function(I){var U,q,G;if(q=this._events,q===void 0)return this;if(q.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):q[I]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete q[I]),this;if(arguments.length===0){var K=Object.keys(q),Y;for(G=0;G<K.length;++G)Y=K[G],Y!=="removeListener"&&this.removeAllListeners(Y);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(U=q[I],typeof U=="function")this.removeListener(I,U);else if(U!==void 0)for(G=U.length-1;G>=0;G--)this.removeListener(I,U[G]);return this};function _listeners($,I,U){var q=$._events;if(q===void 0)return[];var G=q[I];return G===void 0?[]:typeof G=="function"?U?[G.listener||G]:[G]:U?unwrapListeners(G):arrayClone(G,G.length)}EventEmitter$1.prototype.listeners=function(I){return _listeners(this,I,!0)},EventEmitter$1.prototype.rawListeners=function(I){return _listeners(this,I,!1)},EventEmitter$1.listenerCount=function($,I){return typeof $.listenerCount=="function"?$.listenerCount(I):listenerCount.call($,I)},EventEmitter$1.prototype.listenerCount=listenerCount;function listenerCount($){var I=this._events;if(I!==void 0){var U=I[$];if(typeof U=="function")return 1;if(U!==void 0)return U.length}return 0}EventEmitter$1.prototype.eventNames=function(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone($,I){for(var U=new Array(I),q=0;q<I;++q)U[q]=$[q];return U}function spliceOne($,I){for(;I+1<$.length;I++)$[I]=$[I+1];$.pop()}function unwrapListeners($){for(var I=new Array($.length),U=0;U<I.length;++U)I[U]=$[U].listener||$[U];return I}function once$2($,I){return new Promise(function(U,q){function G(Y){$.removeListener(I,K),q(Y)}function K(){typeof $.removeListener=="function"&&$.removeListener("error",G),U([].slice.call(arguments))}eventTargetAgnosticAddListener($,I,K,{once:!0}),I!=="error"&&addErrorHandlerIfEventEmitter($,G,{once:!0})})}function addErrorHandlerIfEventEmitter($,I,U){typeof $.on=="function"&&eventTargetAgnosticAddListener($,"error",I,U)}function eventTargetAgnosticAddListener($,I,U,q){if(typeof $.on=="function")q.once?$.once(I,U):$.on(I,U);else if(typeof $.addEventListener=="function")$.addEventListener(I,function G(K){q.once&&$.removeEventListener(I,G),U(K)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof $)}var eventsExports=events.exports,streamBrowser=eventsExports.EventEmitter,buffer={},base64Js={};base64Js.byteLength=byteLength,base64Js.toByteArray=toByteArray,base64Js.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr=typeof Uint8Array<"u"?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i$2=0,len=code.length;i$2<len;++i$2)lookup[i$2]=code[i$2],revLookup[code.charCodeAt(i$2)]=i$2;revLookup[45]=62,revLookup[95]=63;function getLens($){var I=$.length;if(I%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var U=$.indexOf("=");U===-1&&(U=I);var q=U===I?0:4-U%4;return[U,q]}function byteLength($){var I=getLens($),U=I[0],q=I[1];return(U+q)*3/4-q}function _byteLength($,I,U){return(I+U)*3/4-U}function toByteArray($){var I,U=getLens($),q=U[0],G=U[1],K=new Arr(_byteLength($,q,G)),Y=0,J=G>0?q-4:q,X;for(X=0;X<J;X+=4)I=revLookup[$.charCodeAt(X)]<<18|revLookup[$.charCodeAt(X+1)]<<12|revLookup[$.charCodeAt(X+2)]<<6|revLookup[$.charCodeAt(X+3)],K[Y++]=I>>16&255,K[Y++]=I>>8&255,K[Y++]=I&255;return G===2&&(I=revLookup[$.charCodeAt(X)]<<2|revLookup[$.charCodeAt(X+1)]>>4,K[Y++]=I&255),G===1&&(I=revLookup[$.charCodeAt(X)]<<10|revLookup[$.charCodeAt(X+1)]<<4|revLookup[$.charCodeAt(X+2)]>>2,K[Y++]=I>>8&255,K[Y++]=I&255),K}function tripletToBase64($){return lookup[$>>18&63]+lookup[$>>12&63]+lookup[$>>6&63]+lookup[$&63]}function encodeChunk$1($,I,U){for(var q,G=[],K=I;K<U;K+=3)q=($[K]<<16&16711680)+($[K+1]<<8&65280)+($[K+2]&255),G.push(tripletToBase64(q));return G.join("")}function fromByteArray($){for(var I,U=$.length,q=U%3,G=[],K=16383,Y=0,J=U-q;Y<J;Y+=K)G.push(encodeChunk$1($,Y,Y+K>J?J:Y+K));return q===1?(I=$[U-1],G.push(lookup[I>>2]+lookup[I<<4&63]+"==")):q===2&&(I=($[U-2]<<8)+$[U-1],G.push(lookup[I>>10]+lookup[I>>4&63]+lookup[I<<2&63]+"=")),G.join("")}var ieee754={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */ieee754.read=function($,I,U,q,G){var K,Y,J=G*8-q-1,X=(1<<J)-1,Z=X>>1,Q=-7,ee=U?G-1:0,te=U?-1:1,ne=$[I+ee];for(ee+=te,K=ne&(1<<-Q)-1,ne>>=-Q,Q+=J;Q>0;K=K*256+$[I+ee],ee+=te,Q-=8);for(Y=K&(1<<-Q)-1,K>>=-Q,Q+=q;Q>0;Y=Y*256+$[I+ee],ee+=te,Q-=8);if(K===0)K=1-Z;else{if(K===X)return Y?NaN:(ne?-1:1)*(1/0);Y=Y+Math.pow(2,q),K=K-Z}return(ne?-1:1)*Y*Math.pow(2,K-q)},ieee754.write=function($,I,U,q,G,K){var Y,J,X,Z=K*8-G-1,Q=(1<<Z)-1,ee=Q>>1,te=G===23?Math.pow(2,-24)-Math.pow(2,-77):0,ne=q?0:K-1,ie=q?1:-1,oe=I<0||I===0&&1/I<0?1:0;for(I=Math.abs(I),isNaN(I)||I===1/0?(J=isNaN(I)?1:0,Y=Q):(Y=Math.floor(Math.log(I)/Math.LN2),I*(X=Math.pow(2,-Y))<1&&(Y--,X*=2),Y+ee>=1?I+=te/X:I+=te*Math.pow(2,1-ee),I*X>=2&&(Y++,X/=2),Y+ee>=Q?(J=0,Y=Q):Y+ee>=1?(J=(I*X-1)*Math.pow(2,G),Y=Y+ee):(J=I*Math.pow(2,ee-1)*Math.pow(2,G),Y=0));G>=8;$[U+ne]=J&255,ne+=ie,J/=256,G-=8);for(Y=Y<<G|J,Z+=G;Z>0;$[U+ne]=Y&255,ne+=ie,Y/=256,Z-=8);$[U+ne-ie]|=oe*128};/*!
|
|
847
847
|
* The buffer module from node.js, for the browser.
|
|
848
848
|
*
|
|
849
849
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
850
850
|
* @license MIT
|
|
851
|
-
*/(function($){const I=base64Js,U=ieee754,q=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;$.Buffer=J,$.SlowBuffer=se,$.INSPECT_MAX_BYTES=50;const G=2147483647;$.kMaxLength=G,J.TYPED_ARRAY_SUPPORT=K(),!J.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function K(){try{const le=new Uint8Array(1),re={foo:function(){return 42}};return Object.setPrototypeOf(re,Uint8Array.prototype),Object.setPrototypeOf(le,re),le.foo()===42}catch{return!1}}Object.defineProperty(J.prototype,"parent",{enumerable:!0,get:function(){if(J.isBuffer(this))return this.buffer}}),Object.defineProperty(J.prototype,"offset",{enumerable:!0,get:function(){if(J.isBuffer(this))return this.byteOffset}});function Y(le){if(le>G)throw new RangeError('The value "'+le+'" is invalid for option "size"');const re=new Uint8Array(le);return Object.setPrototypeOf(re,J.prototype),re}function J(le,re,ae){if(typeof le=="number"){if(typeof re=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return ee(le)}return X(le,re,ae)}J.poolSize=8192;function X(le,re,ae){if(typeof le=="string")return te(le,re);if(ArrayBuffer.isView(le))return ie(le);if(le==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof le);if(At(le,ArrayBuffer)||le&&At(le.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(At(le,SharedArrayBuffer)||le&&At(le.buffer,SharedArrayBuffer)))return oe(le,re,ae);if(typeof le=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const he=le.valueOf&&le.valueOf();if(he!=null&&he!==le)return J.from(he,re,ae);const we=ce(le);if(we)return we;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof le[Symbol.toPrimitive]=="function")return J.from(le[Symbol.toPrimitive]("string"),re,ae);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof le)}J.from=function(le,re,ae){return X(le,re,ae)},Object.setPrototypeOf(J.prototype,Uint8Array.prototype),Object.setPrototypeOf(J,Uint8Array);function Z(le){if(typeof le!="number")throw new TypeError('"size" argument must be of type number');if(le<0)throw new RangeError('The value "'+le+'" is invalid for option "size"')}function Q(le,re,ae){return Z(le),le<=0?Y(le):re!==void 0?typeof ae=="string"?Y(le).fill(re,ae):Y(le).fill(re):Y(le)}J.alloc=function(le,re,ae){return Q(le,re,ae)};function ee(le){return Z(le),Y(le<0?0:fe(le)|0)}J.allocUnsafe=function(le){return ee(le)},J.allocUnsafeSlow=function(le){return ee(le)};function te(le,re){if((typeof re!="string"||re==="")&&(re="utf8"),!J.isEncoding(re))throw new TypeError("Unknown encoding: "+re);const ae=de(le,re)|0;let he=Y(ae);const we=he.write(le,re);return we!==ae&&(he=he.slice(0,we)),he}function ne(le){const re=le.length<0?0:fe(le.length)|0,ae=Y(re);for(let he=0;he<re;he+=1)ae[he]=le[he]&255;return ae}function ie(le){if(At(le,Uint8Array)){const re=new Uint8Array(le);return oe(re.buffer,re.byteOffset,re.byteLength)}return ne(le)}function oe(le,re,ae){if(re<0||le.byteLength<re)throw new RangeError('"offset" is outside of buffer bounds');if(le.byteLength<re+(ae||0))throw new RangeError('"length" is outside of buffer bounds');let he;return re===void 0&&ae===void 0?he=new Uint8Array(le):ae===void 0?he=new Uint8Array(le,re):he=new Uint8Array(le,re,ae),Object.setPrototypeOf(he,J.prototype),he}function ce(le){if(J.isBuffer(le)){const re=fe(le.length)|0,ae=Y(re);return ae.length===0||le.copy(ae,0,0,re),ae}if(le.length!==void 0)return typeof le.length!="number"||zt(le.length)?Y(0):ne(le);if(le.type==="Buffer"&&Array.isArray(le.data))return ne(le.data)}function fe(le){if(le>=G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");return le|0}function se(le){return+le!=le&&(le=0),J.alloc(+le)}J.isBuffer=function(re){return re!=null&&re._isBuffer===!0&&re!==J.prototype},J.compare=function(re,ae){if(At(re,Uint8Array)&&(re=J.from(re,re.offset,re.byteLength)),At(ae,Uint8Array)&&(ae=J.from(ae,ae.offset,ae.byteLength)),!J.isBuffer(re)||!J.isBuffer(ae))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(re===ae)return 0;let he=re.length,we=ae.length;for(let Ee=0,Le=Math.min(he,we);Ee<Le;++Ee)if(re[Ee]!==ae[Ee]){he=re[Ee],we=ae[Ee];break}return he<we?-1:we<he?1:0},J.isEncoding=function(re){switch(String(re).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},J.concat=function(re,ae){if(!Array.isArray(re))throw new TypeError('"list" argument must be an Array of Buffers');if(re.length===0)return J.alloc(0);let he;if(ae===void 0)for(ae=0,he=0;he<re.length;++he)ae+=re[he].length;const we=J.allocUnsafe(ae);let Ee=0;for(he=0;he<re.length;++he){let Le=re[he];if(At(Le,Uint8Array))Ee+Le.length>we.length?(J.isBuffer(Le)||(Le=J.from(Le)),Le.copy(we,Ee)):Uint8Array.prototype.set.call(we,Le,Ee);else if(J.isBuffer(Le))Le.copy(we,Ee);else throw new TypeError('"list" argument must be an Array of Buffers');Ee+=Le.length}return we};function de(le,re){if(J.isBuffer(le))return le.length;if(ArrayBuffer.isView(le)||At(le,ArrayBuffer))return le.byteLength;if(typeof le!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof le);const ae=le.length,he=arguments.length>2&&arguments[2]===!0;if(!he&&ae===0)return 0;let we=!1;for(;;)switch(re){case"ascii":case"latin1":case"binary":return ae;case"utf8":case"utf-8":return $t(le).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ae*2;case"hex":return ae>>>1;case"base64":return jt(le).length;default:if(we)return he?-1:$t(le).length;re=(""+re).toLowerCase(),we=!0}}J.byteLength=de;function ue(le,re,ae){let he=!1;if((re===void 0||re<0)&&(re=0),re>this.length||((ae===void 0||ae>this.length)&&(ae=this.length),ae<=0)||(ae>>>=0,re>>>=0,ae<=re))return"";for(le||(le="utf8");;)switch(le){case"hex":return it(this,re,ae);case"utf8":case"utf-8":return Be(this,re,ae);case"ascii":return ot(this,re,ae);case"latin1":case"binary":return ft(this,re,ae);case"base64":return De(this,re,ae);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ut(this,re,ae);default:if(he)throw new TypeError("Unknown encoding: "+le);le=(le+"").toLowerCase(),he=!0}}J.prototype._isBuffer=!0;function pe(le,re,ae){const he=le[re];le[re]=le[ae],le[ae]=he}J.prototype.swap16=function(){const re=this.length;if(re%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let ae=0;ae<re;ae+=2)pe(this,ae,ae+1);return this},J.prototype.swap32=function(){const re=this.length;if(re%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let ae=0;ae<re;ae+=4)pe(this,ae,ae+3),pe(this,ae+1,ae+2);return this},J.prototype.swap64=function(){const re=this.length;if(re%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let ae=0;ae<re;ae+=8)pe(this,ae,ae+7),pe(this,ae+1,ae+6),pe(this,ae+2,ae+5),pe(this,ae+3,ae+4);return this},J.prototype.toString=function(){const re=this.length;return re===0?"":arguments.length===0?Be(this,0,re):ue.apply(this,arguments)},J.prototype.toLocaleString=J.prototype.toString,J.prototype.equals=function(re){if(!J.isBuffer(re))throw new TypeError("Argument must be a Buffer");return this===re?!0:J.compare(this,re)===0},J.prototype.inspect=function(){let re="";const ae=$.INSPECT_MAX_BYTES;return re=this.toString("hex",0,ae).replace(/(.{2})/g,"$1 ").trim(),this.length>ae&&(re+=" ... "),"<Buffer "+re+">"},q&&(J.prototype[q]=J.prototype.inspect),J.prototype.compare=function(re,ae,he,we,Ee){if(At(re,Uint8Array)&&(re=J.from(re,re.offset,re.byteLength)),!J.isBuffer(re))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof re);if(ae===void 0&&(ae=0),he===void 0&&(he=re?re.length:0),we===void 0&&(we=0),Ee===void 0&&(Ee=this.length),ae<0||he>re.length||we<0||Ee>this.length)throw new RangeError("out of range index");if(we>=Ee&&ae>=he)return 0;if(we>=Ee)return-1;if(ae>=he)return 1;if(ae>>>=0,he>>>=0,we>>>=0,Ee>>>=0,this===re)return 0;let Le=Ee-we,bt=he-ae;const Lt=Math.min(Le,bt),Ct=this.slice(we,Ee),It=re.slice(ae,he);for(let Tt=0;Tt<Lt;++Tt)if(Ct[Tt]!==It[Tt]){Le=Ct[Tt],bt=It[Tt];break}return Le<bt?-1:bt<Le?1:0};function ve(le,re,ae,he,we){if(le.length===0)return-1;if(typeof ae=="string"?(he=ae,ae=0):ae>2147483647?ae=2147483647:ae<-2147483648&&(ae=-2147483648),ae=+ae,zt(ae)&&(ae=we?0:le.length-1),ae<0&&(ae=le.length+ae),ae>=le.length){if(we)return-1;ae=le.length-1}else if(ae<0)if(we)ae=0;else return-1;if(typeof re=="string"&&(re=J.from(re,he)),J.isBuffer(re))return re.length===0?-1:me(le,re,ae,he,we);if(typeof re=="number")return re=re&255,typeof Uint8Array.prototype.indexOf=="function"?we?Uint8Array.prototype.indexOf.call(le,re,ae):Uint8Array.prototype.lastIndexOf.call(le,re,ae):me(le,[re],ae,he,we);throw new TypeError("val must be string, number or Buffer")}function me(le,re,ae,he,we){let Ee=1,Le=le.length,bt=re.length;if(he!==void 0&&(he=String(he).toLowerCase(),he==="ucs2"||he==="ucs-2"||he==="utf16le"||he==="utf-16le")){if(le.length<2||re.length<2)return-1;Ee=2,Le/=2,bt/=2,ae/=2}function Lt(It,Tt){return Ee===1?It[Tt]:It.readUInt16BE(Tt*Ee)}let Ct;if(we){let It=-1;for(Ct=ae;Ct<Le;Ct++)if(Lt(le,Ct)===Lt(re,It===-1?0:Ct-It)){if(It===-1&&(It=Ct),Ct-It+1===bt)return It*Ee}else It!==-1&&(Ct-=Ct-It),It=-1}else for(ae+bt>Le&&(ae=Le-bt),Ct=ae;Ct>=0;Ct--){let It=!0;for(let Tt=0;Tt<bt;Tt++)if(Lt(le,Ct+Tt)!==Lt(re,Tt)){It=!1;break}if(It)return Ct}return-1}J.prototype.includes=function(re,ae,he){return this.indexOf(re,ae,he)!==-1},J.prototype.indexOf=function(re,ae,he){return ve(this,re,ae,he,!0)},J.prototype.lastIndexOf=function(re,ae,he){return ve(this,re,ae,he,!1)};function be(le,re,ae,he){ae=Number(ae)||0;const we=le.length-ae;he?(he=Number(he),he>we&&(he=we)):he=we;const Ee=re.length;he>Ee/2&&(he=Ee/2);let Le;for(Le=0;Le<he;++Le){const bt=parseInt(re.substr(Le*2,2),16);if(zt(bt))return Le;le[ae+Le]=bt}return Le}function _e(le,re,ae,he){return Gt($t(re,le.length-ae),le,ae,he)}function Se(le,re,ae,he){return Gt(Et(re),le,ae,he)}function xe(le,re,ae,he){return Gt(jt(re),le,ae,he)}function ke(le,re,ae,he){return Gt(rt(re,le.length-ae),le,ae,he)}J.prototype.write=function(re,ae,he,we){if(ae===void 0)we="utf8",he=this.length,ae=0;else if(he===void 0&&typeof ae=="string")we=ae,he=this.length,ae=0;else if(isFinite(ae))ae=ae>>>0,isFinite(he)?(he=he>>>0,we===void 0&&(we="utf8")):(we=he,he=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const Ee=this.length-ae;if((he===void 0||he>Ee)&&(he=Ee),re.length>0&&(he<0||ae<0)||ae>this.length)throw new RangeError("Attempt to write outside buffer bounds");we||(we="utf8");let Le=!1;for(;;)switch(we){case"hex":return be(this,re,ae,he);case"utf8":case"utf-8":return _e(this,re,ae,he);case"ascii":case"latin1":case"binary":return Se(this,re,ae,he);case"base64":return xe(this,re,ae,he);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ke(this,re,ae,he);default:if(Le)throw new TypeError("Unknown encoding: "+we);we=(""+we).toLowerCase(),Le=!0}},J.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function De(le,re,ae){return re===0&&ae===le.length?I.fromByteArray(le):I.fromByteArray(le.slice(re,ae))}function Be(le,re,ae){ae=Math.min(le.length,ae);const he=[];let we=re;for(;we<ae;){const Ee=le[we];let Le=null,bt=Ee>239?4:Ee>223?3:Ee>191?2:1;if(we+bt<=ae){let Lt,Ct,It,Tt;switch(bt){case 1:Ee<128&&(Le=Ee);break;case 2:Lt=le[we+1],(Lt&192)===128&&(Tt=(Ee&31)<<6|Lt&63,Tt>127&&(Le=Tt));break;case 3:Lt=le[we+1],Ct=le[we+2],(Lt&192)===128&&(Ct&192)===128&&(Tt=(Ee&15)<<12|(Lt&63)<<6|Ct&63,Tt>2047&&(Tt<55296||Tt>57343)&&(Le=Tt));break;case 4:Lt=le[we+1],Ct=le[we+2],It=le[we+3],(Lt&192)===128&&(Ct&192)===128&&(It&192)===128&&(Tt=(Ee&15)<<18|(Lt&63)<<12|(Ct&63)<<6|It&63,Tt>65535&&Tt<1114112&&(Le=Tt))}}Le===null?(Le=65533,bt=1):Le>65535&&(Le-=65536,he.push(Le>>>10&1023|55296),Le=56320|Le&1023),he.push(Le),we+=bt}return nt(he)}const Ve=4096;function nt(le){const re=le.length;if(re<=Ve)return String.fromCharCode.apply(String,le);let ae="",he=0;for(;he<re;)ae+=String.fromCharCode.apply(String,le.slice(he,he+=Ve));return ae}function ot(le,re,ae){let he="";ae=Math.min(le.length,ae);for(let we=re;we<ae;++we)he+=String.fromCharCode(le[we]&127);return he}function ft(le,re,ae){let he="";ae=Math.min(le.length,ae);for(let we=re;we<ae;++we)he+=String.fromCharCode(le[we]);return he}function it(le,re,ae){const he=le.length;(!re||re<0)&&(re=0),(!ae||ae<0||ae>he)&&(ae=he);let we="";for(let Ee=re;Ee<ae;++Ee)we+=nn[le[Ee]];return we}function ut(le,re,ae){const he=le.slice(re,ae);let we="";for(let Ee=0;Ee<he.length-1;Ee+=2)we+=String.fromCharCode(he[Ee]+he[Ee+1]*256);return we}J.prototype.slice=function(re,ae){const he=this.length;re=~~re,ae=ae===void 0?he:~~ae,re<0?(re+=he,re<0&&(re=0)):re>he&&(re=he),ae<0?(ae+=he,ae<0&&(ae=0)):ae>he&&(ae=he),ae<re&&(ae=re);const we=this.subarray(re,ae);return Object.setPrototypeOf(we,J.prototype),we};function et(le,re,ae){if(le%1!==0||le<0)throw new RangeError("offset is not uint");if(le+re>ae)throw new RangeError("Trying to access beyond buffer length")}J.prototype.readUintLE=J.prototype.readUIntLE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re],Ee=1,Le=0;for(;++Le<ae&&(Ee*=256);)we+=this[re+Le]*Ee;return we},J.prototype.readUintBE=J.prototype.readUIntBE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re+--ae],Ee=1;for(;ae>0&&(Ee*=256);)we+=this[re+--ae]*Ee;return we},J.prototype.readUint8=J.prototype.readUInt8=function(re,ae){return re=re>>>0,ae||et(re,1,this.length),this[re]},J.prototype.readUint16LE=J.prototype.readUInt16LE=function(re,ae){return re=re>>>0,ae||et(re,2,this.length),this[re]|this[re+1]<<8},J.prototype.readUint16BE=J.prototype.readUInt16BE=function(re,ae){return re=re>>>0,ae||et(re,2,this.length),this[re]<<8|this[re+1]},J.prototype.readUint32LE=J.prototype.readUInt32LE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),(this[re]|this[re+1]<<8|this[re+2]<<16)+this[re+3]*16777216},J.prototype.readUint32BE=J.prototype.readUInt32BE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]*16777216+(this[re+1]<<16|this[re+2]<<8|this[re+3])},J.prototype.readBigUInt64LE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=ae+this[++re]*2**8+this[++re]*2**16+this[++re]*2**24,Ee=this[++re]+this[++re]*2**8+this[++re]*2**16+he*2**24;return BigInt(we)+(BigInt(Ee)<<BigInt(32))}),J.prototype.readBigUInt64BE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=ae*2**24+this[++re]*2**16+this[++re]*2**8+this[++re],Ee=this[++re]*2**24+this[++re]*2**16+this[++re]*2**8+he;return(BigInt(we)<<BigInt(32))+BigInt(Ee)}),J.prototype.readIntLE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re],Ee=1,Le=0;for(;++Le<ae&&(Ee*=256);)we+=this[re+Le]*Ee;return Ee*=128,we>=Ee&&(we-=Math.pow(2,8*ae)),we},J.prototype.readIntBE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=ae,Ee=1,Le=this[re+--we];for(;we>0&&(Ee*=256);)Le+=this[re+--we]*Ee;return Ee*=128,Le>=Ee&&(Le-=Math.pow(2,8*ae)),Le},J.prototype.readInt8=function(re,ae){return re=re>>>0,ae||et(re,1,this.length),this[re]&128?(255-this[re]+1)*-1:this[re]},J.prototype.readInt16LE=function(re,ae){re=re>>>0,ae||et(re,2,this.length);const he=this[re]|this[re+1]<<8;return he&32768?he|4294901760:he},J.prototype.readInt16BE=function(re,ae){re=re>>>0,ae||et(re,2,this.length);const he=this[re+1]|this[re]<<8;return he&32768?he|4294901760:he},J.prototype.readInt32LE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]|this[re+1]<<8|this[re+2]<<16|this[re+3]<<24},J.prototype.readInt32BE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]<<24|this[re+1]<<16|this[re+2]<<8|this[re+3]},J.prototype.readBigInt64LE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=this[re+4]+this[re+5]*2**8+this[re+6]*2**16+(he<<24);return(BigInt(we)<<BigInt(32))+BigInt(ae+this[++re]*2**8+this[++re]*2**16+this[++re]*2**24)}),J.prototype.readBigInt64BE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=(ae<<24)+this[++re]*2**16+this[++re]*2**8+this[++re];return(BigInt(we)<<BigInt(32))+BigInt(this[++re]*2**24+this[++re]*2**16+this[++re]*2**8+he)}),J.prototype.readFloatLE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),U.read(this,re,!0,23,4)},J.prototype.readFloatBE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),U.read(this,re,!1,23,4)},J.prototype.readDoubleLE=function(re,ae){return re=re>>>0,ae||et(re,8,this.length),U.read(this,re,!0,52,8)},J.prototype.readDoubleBE=function(re,ae){return re=re>>>0,ae||et(re,8,this.length),U.read(this,re,!1,52,8)};function Ue(le,re,ae,he,we,Ee){if(!J.isBuffer(le))throw new TypeError('"buffer" argument must be a Buffer instance');if(re>we||re<Ee)throw new RangeError('"value" argument is out of bounds');if(ae+he>le.length)throw new RangeError("Index out of range")}J.prototype.writeUintLE=J.prototype.writeUIntLE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,he=he>>>0,!we){const bt=Math.pow(2,8*he)-1;Ue(this,re,ae,he,bt,0)}let Ee=1,Le=0;for(this[ae]=re&255;++Le<he&&(Ee*=256);)this[ae+Le]=re/Ee&255;return ae+he},J.prototype.writeUintBE=J.prototype.writeUIntBE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,he=he>>>0,!we){const bt=Math.pow(2,8*he)-1;Ue(this,re,ae,he,bt,0)}let Ee=he-1,Le=1;for(this[ae+Ee]=re&255;--Ee>=0&&(Le*=256);)this[ae+Ee]=re/Le&255;return ae+he},J.prototype.writeUint8=J.prototype.writeUInt8=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,1,255,0),this[ae]=re&255,ae+1},J.prototype.writeUint16LE=J.prototype.writeUInt16LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,65535,0),this[ae]=re&255,this[ae+1]=re>>>8,ae+2},J.prototype.writeUint16BE=J.prototype.writeUInt16BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,65535,0),this[ae]=re>>>8,this[ae+1]=re&255,ae+2},J.prototype.writeUint32LE=J.prototype.writeUInt32LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,4294967295,0),this[ae+3]=re>>>24,this[ae+2]=re>>>16,this[ae+1]=re>>>8,this[ae]=re&255,ae+4},J.prototype.writeUint32BE=J.prototype.writeUInt32BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,4294967295,0),this[ae]=re>>>24,this[ae+1]=re>>>16,this[ae+2]=re>>>8,this[ae+3]=re&255,ae+4};function We(le,re,ae,he,we){ye(re,he,we,le,ae,7);let Ee=Number(re&BigInt(4294967295));le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee;let Le=Number(re>>BigInt(32)&BigInt(4294967295));return le[ae++]=Le,Le=Le>>8,le[ae++]=Le,Le=Le>>8,le[ae++]=Le,Le=Le>>8,le[ae++]=Le,ae}function tt(le,re,ae,he,we){ye(re,he,we,le,ae,7);let Ee=Number(re&BigInt(4294967295));le[ae+7]=Ee,Ee=Ee>>8,le[ae+6]=Ee,Ee=Ee>>8,le[ae+5]=Ee,Ee=Ee>>8,le[ae+4]=Ee;let Le=Number(re>>BigInt(32)&BigInt(4294967295));return le[ae+3]=Le,Le=Le>>8,le[ae+2]=Le,Le=Le>>8,le[ae+1]=Le,Le=Le>>8,le[ae]=Le,ae+8}J.prototype.writeBigUInt64LE=St(function(re,ae=0){return We(this,re,ae,BigInt(0),BigInt("0xffffffffffffffff"))}),J.prototype.writeBigUInt64BE=St(function(re,ae=0){return tt(this,re,ae,BigInt(0),BigInt("0xffffffffffffffff"))}),J.prototype.writeIntLE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,!we){const Lt=Math.pow(2,8*he-1);Ue(this,re,ae,he,Lt-1,-Lt)}let Ee=0,Le=1,bt=0;for(this[ae]=re&255;++Ee<he&&(Le*=256);)re<0&&bt===0&&this[ae+Ee-1]!==0&&(bt=1),this[ae+Ee]=(re/Le>>0)-bt&255;return ae+he},J.prototype.writeIntBE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,!we){const Lt=Math.pow(2,8*he-1);Ue(this,re,ae,he,Lt-1,-Lt)}let Ee=he-1,Le=1,bt=0;for(this[ae+Ee]=re&255;--Ee>=0&&(Le*=256);)re<0&&bt===0&&this[ae+Ee+1]!==0&&(bt=1),this[ae+Ee]=(re/Le>>0)-bt&255;return ae+he},J.prototype.writeInt8=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,1,127,-128),re<0&&(re=255+re+1),this[ae]=re&255,ae+1},J.prototype.writeInt16LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,32767,-32768),this[ae]=re&255,this[ae+1]=re>>>8,ae+2},J.prototype.writeInt16BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,32767,-32768),this[ae]=re>>>8,this[ae+1]=re&255,ae+2},J.prototype.writeInt32LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,2147483647,-2147483648),this[ae]=re&255,this[ae+1]=re>>>8,this[ae+2]=re>>>16,this[ae+3]=re>>>24,ae+4},J.prototype.writeInt32BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,2147483647,-2147483648),re<0&&(re=4294967295+re+1),this[ae]=re>>>24,this[ae+1]=re>>>16,this[ae+2]=re>>>8,this[ae+3]=re&255,ae+4},J.prototype.writeBigInt64LE=St(function(re,ae=0){return We(this,re,ae,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),J.prototype.writeBigInt64BE=St(function(re,ae=0){return tt(this,re,ae,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function vt(le,re,ae,he,we,Ee){if(ae+he>le.length)throw new RangeError("Index out of range");if(ae<0)throw new RangeError("Index out of range")}function je(le,re,ae,he,we){return re=+re,ae=ae>>>0,we||vt(le,re,ae,4),U.write(le,re,ae,he,23,4),ae+4}J.prototype.writeFloatLE=function(re,ae,he){return je(this,re,ae,!0,he)},J.prototype.writeFloatBE=function(re,ae,he){return je(this,re,ae,!1,he)};function ze(le,re,ae,he,we){return re=+re,ae=ae>>>0,we||vt(le,re,ae,8),U.write(le,re,ae,he,52,8),ae+8}J.prototype.writeDoubleLE=function(re,ae,he){return ze(this,re,ae,!0,he)},J.prototype.writeDoubleBE=function(re,ae,he){return ze(this,re,ae,!1,he)},J.prototype.copy=function(re,ae,he,we){if(!J.isBuffer(re))throw new TypeError("argument should be a Buffer");if(he||(he=0),!we&&we!==0&&(we=this.length),ae>=re.length&&(ae=re.length),ae||(ae=0),we>0&&we<he&&(we=he),we===he||re.length===0||this.length===0)return 0;if(ae<0)throw new RangeError("targetStart out of bounds");if(he<0||he>=this.length)throw new RangeError("Index out of range");if(we<0)throw new RangeError("sourceEnd out of bounds");we>this.length&&(we=this.length),re.length-ae<we-he&&(we=re.length-ae+he);const Ee=we-he;return this===re&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(ae,he,we):Uint8Array.prototype.set.call(re,this.subarray(he,we),ae),Ee},J.prototype.fill=function(re,ae,he,we){if(typeof re=="string"){if(typeof ae=="string"?(we=ae,ae=0,he=this.length):typeof he=="string"&&(we=he,he=this.length),we!==void 0&&typeof we!="string")throw new TypeError("encoding must be a string");if(typeof we=="string"&&!J.isEncoding(we))throw new TypeError("Unknown encoding: "+we);if(re.length===1){const Le=re.charCodeAt(0);(we==="utf8"&&Le<128||we==="latin1")&&(re=Le)}}else typeof re=="number"?re=re&255:typeof re=="boolean"&&(re=Number(re));if(ae<0||this.length<ae||this.length<he)throw new RangeError("Out of range index");if(he<=ae)return this;ae=ae>>>0,he=he===void 0?this.length:he>>>0,re||(re=0);let Ee;if(typeof re=="number")for(Ee=ae;Ee<he;++Ee)this[Ee]=re;else{const Le=J.isBuffer(re)?re:J.from(re,we),bt=Le.length;if(bt===0)throw new TypeError('The value "'+re+'" is invalid for argument "value"');for(Ee=0;Ee<he-ae;++Ee)this[Ee+ae]=Le[Ee%bt]}return this};const Ae={};function Re(le,re,ae){Ae[le]=class extends ae{constructor(){super(),Object.defineProperty(this,"message",{value:re.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${le}]`,this.stack,delete this.name}get code(){return le}set code(we){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:we,writable:!0})}toString(){return`${this.name} [${le}]: ${this.message}`}}}Re("ERR_BUFFER_OUT_OF_BOUNDS",function(le){return le?`${le} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Re("ERR_INVALID_ARG_TYPE",function(le,re){return`The "${le}" argument must be of type number. Received type ${typeof re}`},TypeError),Re("ERR_OUT_OF_RANGE",function(le,re,ae){let he=`The value of "${le}" is out of range.`,we=ae;return Number.isInteger(ae)&&Math.abs(ae)>2**32?we=Ce(String(ae)):typeof ae=="bigint"&&(we=String(ae),(ae>BigInt(2)**BigInt(32)||ae<-(BigInt(2)**BigInt(32)))&&(we=Ce(we)),we+="n"),he+=` It must be ${re}. Received ${we}`,he},RangeError);function Ce(le){let re="",ae=le.length;const he=le[0]==="-"?1:0;for(;ae>=he+4;ae-=3)re=`_${le.slice(ae-3,ae)}${re}`;return`${le.slice(0,ae)}${re}`}function ge(le,re,ae){Me(re,"offset"),(le[re]===void 0||le[re+ae]===void 0)&&Ke(re,le.length-(ae+1))}function ye(le,re,ae,he,we,Ee){if(le>ae||le<re){const Le=typeof re=="bigint"?"n":"";let bt;throw Ee>3?re===0||re===BigInt(0)?bt=`>= 0${Le} and < 2${Le} ** ${(Ee+1)*8}${Le}`:bt=`>= -(2${Le} ** ${(Ee+1)*8-1}${Le}) and < 2 ** ${(Ee+1)*8-1}${Le}`:bt=`>= ${re}${Le} and <= ${ae}${Le}`,new Ae.ERR_OUT_OF_RANGE("value",bt,le)}ge(he,we,Ee)}function Me(le,re){if(typeof le!="number")throw new Ae.ERR_INVALID_ARG_TYPE(re,"number",le)}function Ke(le,re,ae){throw Math.floor(le)!==le?(Me(le,ae),new Ae.ERR_OUT_OF_RANGE(ae||"offset","an integer",le)):re<0?new Ae.ERR_BUFFER_OUT_OF_BOUNDS:new Ae.ERR_OUT_OF_RANGE(ae||"offset",`>= ${ae?1:0} and <= ${re}`,le)}const st=/[^+/0-9A-Za-z-_]/g;function dt(le){if(le=le.split("=")[0],le=le.trim().replace(st,""),le.length<2)return"";for(;le.length%4!==0;)le=le+"=";return le}function $t(le,re){re=re||1/0;let ae;const he=le.length;let we=null;const Ee=[];for(let Le=0;Le<he;++Le){if(ae=le.charCodeAt(Le),ae>55295&&ae<57344){if(!we){if(ae>56319){(re-=3)>-1&&Ee.push(239,191,189);continue}else if(Le+1===he){(re-=3)>-1&&Ee.push(239,191,189);continue}we=ae;continue}if(ae<56320){(re-=3)>-1&&Ee.push(239,191,189),we=ae;continue}ae=(we-55296<<10|ae-56320)+65536}else we&&(re-=3)>-1&&Ee.push(239,191,189);if(we=null,ae<128){if((re-=1)<0)break;Ee.push(ae)}else if(ae<2048){if((re-=2)<0)break;Ee.push(ae>>6|192,ae&63|128)}else if(ae<65536){if((re-=3)<0)break;Ee.push(ae>>12|224,ae>>6&63|128,ae&63|128)}else if(ae<1114112){if((re-=4)<0)break;Ee.push(ae>>18|240,ae>>12&63|128,ae>>6&63|128,ae&63|128)}else throw new Error("Invalid code point")}return Ee}function Et(le){const re=[];for(let ae=0;ae<le.length;++ae)re.push(le.charCodeAt(ae)&255);return re}function rt(le,re){let ae,he,we;const Ee=[];for(let Le=0;Le<le.length&&!((re-=2)<0);++Le)ae=le.charCodeAt(Le),he=ae>>8,we=ae%256,Ee.push(we),Ee.push(he);return Ee}function jt(le){return I.toByteArray(dt(le))}function Gt(le,re,ae,he){let we;for(we=0;we<he&&!(we+ae>=re.length||we>=le.length);++we)re[we+ae]=le[we];return we}function At(le,re){return le instanceof re||le!=null&&le.constructor!=null&&le.constructor.name!=null&&le.constructor.name===re.name}function zt(le){return le!==le}const nn=function(){const le="0123456789abcdef",re=new Array(256);for(let ae=0;ae<16;++ae){const he=ae*16;for(let we=0;we<16;++we)re[he+we]=le[ae]+le[we]}return re}();function St(le){return typeof BigInt>"u"?Ut:le}function Ut(){throw new Error("BigInt not supported")}})(buffer);const __viteBrowserExternal={},__viteBrowserExternal$1=Object.freeze(Object.defineProperty({__proto__:null,default:__viteBrowserExternal},Symbol.toStringTag,{value:"Module"})),require$$3=getAugmentedNamespace(__viteBrowserExternal$1);var buffer_list,hasRequiredBuffer_list;function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;hasRequiredBuffer_list=1;function $(te,ne){var ie=Object.keys(te);if(Object.getOwnPropertySymbols){var oe=Object.getOwnPropertySymbols(te);ne&&(oe=oe.filter(function(ce){return Object.getOwnPropertyDescriptor(te,ce).enumerable})),ie.push.apply(ie,oe)}return ie}function I(te){for(var ne=1;ne<arguments.length;ne++){var ie=arguments[ne]!=null?arguments[ne]:{};ne%2?$(Object(ie),!0).forEach(function(oe){U(te,oe,ie[oe])}):Object.getOwnPropertyDescriptors?Object.defineProperties(te,Object.getOwnPropertyDescriptors(ie)):$(Object(ie)).forEach(function(oe){Object.defineProperty(te,oe,Object.getOwnPropertyDescriptor(ie,oe))})}return te}function U(te,ne,ie){return ne in te?Object.defineProperty(te,ne,{value:ie,enumerable:!0,configurable:!0,writable:!0}):te[ne]=ie,te}function q(te,ne){if(!(te instanceof ne))throw new TypeError("Cannot call a class as a function")}function G(te,ne){for(var ie=0;ie<ne.length;ie++){var oe=ne[ie];oe.enumerable=oe.enumerable||!1,oe.configurable=!0,"value"in oe&&(oe.writable=!0),Object.defineProperty(te,oe.key,oe)}}function K(te,ne,ie){return ne&&G(te.prototype,ne),ie&&G(te,ie),te}var Y=buffer,J=Y.Buffer,X=require$$3,Z=X.inspect,Q=Z&&Z.custom||"inspect";function ee(te,ne,ie){J.prototype.copy.call(te,ne,ie)}return buffer_list=function(){function te(){q(this,te),this.head=null,this.tail=null,this.length=0}return K(te,[{key:"push",value:function(ie){var oe={data:ie,next:null};this.length>0?this.tail.next=oe:this.head=oe,this.tail=oe,++this.length}},{key:"unshift",value:function(ie){var oe={data:ie,next:this.head};this.length===0&&(this.tail=oe),this.head=oe,++this.length}},{key:"shift",value:function(){if(this.length!==0){var ie=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,ie}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(ie){if(this.length===0)return"";for(var oe=this.head,ce=""+oe.data;oe=oe.next;)ce+=ie+oe.data;return ce}},{key:"concat",value:function(ie){if(this.length===0)return J.alloc(0);for(var oe=J.allocUnsafe(ie>>>0),ce=this.head,fe=0;ce;)ee(ce.data,oe,fe),fe+=ce.data.length,ce=ce.next;return oe}},{key:"consume",value:function(ie,oe){var ce;return ie<this.head.data.length?(ce=this.head.data.slice(0,ie),this.head.data=this.head.data.slice(ie)):ie===this.head.data.length?ce=this.shift():ce=oe?this._getString(ie):this._getBuffer(ie),ce}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(ie){var oe=this.head,ce=1,fe=oe.data;for(ie-=fe.length;oe=oe.next;){var se=oe.data,de=ie>se.length?se.length:ie;if(de===se.length?fe+=se:fe+=se.slice(0,ie),ie-=de,ie===0){de===se.length?(++ce,oe.next?this.head=oe.next:this.head=this.tail=null):(this.head=oe,oe.data=se.slice(de));break}++ce}return this.length-=ce,fe}},{key:"_getBuffer",value:function(ie){var oe=J.allocUnsafe(ie),ce=this.head,fe=1;for(ce.data.copy(oe),ie-=ce.data.length;ce=ce.next;){var se=ce.data,de=ie>se.length?se.length:ie;if(se.copy(oe,oe.length-ie,0,de),ie-=de,ie===0){de===se.length?(++fe,ce.next?this.head=ce.next:this.head=this.tail=null):(this.head=ce,ce.data=se.slice(de));break}++fe}return this.length-=fe,oe}},{key:Q,value:function(ie,oe){return Z(this,I({},oe,{depth:0,customInspect:!1}))}}]),te}(),buffer_list}function destroy($,I){var U=this,q=this._readableState&&this._readableState.destroyed,G=this._writableState&&this._writableState.destroyed;return q||G?(I?I($):$&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,$)):process.nextTick(emitErrorNT,this,$)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy($||null,function(K){!I&&K?U._writableState?U._writableState.errorEmitted?process.nextTick(emitCloseNT,U):(U._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,U,K)):process.nextTick(emitErrorAndCloseNT,U,K):I?(process.nextTick(emitCloseNT,U),I(K)):process.nextTick(emitCloseNT,U)}),this)}function emitErrorAndCloseNT($,I){emitErrorNT($,I),emitCloseNT($)}function emitCloseNT($){$._writableState&&!$._writableState.emitClose||$._readableState&&!$._readableState.emitClose||$.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT($,I){$.emit("error",I)}function errorOrDestroy($,I){var U=$._readableState,q=$._writableState;U&&U.autoDestroy||q&&q.autoDestroy?$.destroy(I):$.emit("error",I)}var destroy_1={destroy,undestroy,errorOrDestroy},errorsBrowser={};function _inheritsLoose($,I){$.prototype=Object.create(I.prototype),$.prototype.constructor=$,$.__proto__=I}var codes={};function createErrorType($,I,U){U||(U=Error);function q(K,Y,J){return typeof I=="string"?I:I(K,Y,J)}var G=function(K){_inheritsLoose(Y,K);function Y(J,X,Z){return K.call(this,q(J,X,Z))||this}return Y}(U);G.prototype.name=U.name,G.prototype.code=$,codes[$]=G}function oneOf($,I){if(Array.isArray($)){var U=$.length;return $=$.map(function(q){return String(q)}),U>2?"one of ".concat(I," ").concat($.slice(0,U-1).join(", "),", or ")+$[U-1]:U===2?"one of ".concat(I," ").concat($[0]," or ").concat($[1]):"of ".concat(I," ").concat($[0])}else return"of ".concat(I," ").concat(String($))}function startsWith($,I,U){return $.substr(!U||U<0?0:+U,I.length)===I}function endsWith($,I,U){return(U===void 0||U>$.length)&&(U=$.length),$.substring(U-I.length,U)===I}function includes($,I,U){return typeof U!="number"&&(U=0),U+I.length>$.length?!1:$.indexOf(I,U)!==-1}createErrorType("ERR_INVALID_OPT_VALUE",function($,I){return'The value "'+I+'" is invalid for option "'+$+'"'},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function($,I,U){var q;typeof I=="string"&&startsWith(I,"not ")?(q="must not be",I=I.replace(/^not /,"")):q="must be";var G;if(endsWith($," argument"))G="The ".concat($," ").concat(q," ").concat(oneOf(I,"type"));else{var K=includes($,".")?"property":"argument";G='The "'.concat($,'" ').concat(K," ").concat(q," ").concat(oneOf(I,"type"))}return G+=". Received type ".concat(typeof U),G},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function($){return"The "+$+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function($){return"Cannot call "+$+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function($){return"Unknown encoding: "+$},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),errorsBrowser.codes=codes;var ERR_INVALID_OPT_VALUE=errorsBrowser.codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom($,I,U){return $.highWaterMark!=null?$.highWaterMark:I?$[U]:null}function getHighWaterMark($,I,U,q){var G=highWaterMarkFrom(I,q,U);if(G!=null){if(!(isFinite(G)&&Math.floor(G)===G)||G<0){var K=q?U:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(K,G)}return Math.floor(G)}return $.objectMode?16:16*1024}var state={getHighWaterMark},inherits_browser={exports:{}};typeof Object.create=="function"?inherits_browser.exports=function(I,U){U&&(I.super_=U,I.prototype=Object.create(U.prototype,{constructor:{value:I,enumerable:!1,writable:!0,configurable:!0}}))}:inherits_browser.exports=function(I,U){if(U){I.super_=U;var q=function(){};q.prototype=U.prototype,I.prototype=new q,I.prototype.constructor=I}};var inherits_browserExports=inherits_browser.exports,browser$4=deprecate;function deprecate($,I){if(config$1("noDeprecation"))return $;var U=!1;function q(){if(!U){if(config$1("throwDeprecation"))throw new Error(I);config$1("traceDeprecation")?console.trace(I):console.warn(I),U=!0}return $.apply(this,arguments)}return q}function config$1($){try{if(!commonjsGlobal.localStorage)return!1}catch{return!1}var I=commonjsGlobal.localStorage[$];return I==null?!1:String(I).toLowerCase()==="true"}var _stream_writable,hasRequired_stream_writable;function require_stream_writable(){if(hasRequired_stream_writable)return _stream_writable;hasRequired_stream_writable=1,_stream_writable=be;function $(je){var ze=this;this.next=null,this.entry=null,this.finish=function(){vt(ze,je)}}var I;be.WritableState=ve;var U={deprecate:browser$4},q=streamBrowser,G=buffer.Buffer,K=commonjsGlobal.Uint8Array||function(){};function Y(je){return G.from(je)}function J(je){return G.isBuffer(je)||je instanceof K}var X=destroy_1,Z=state,Q=Z.getHighWaterMark,ee=errorsBrowser.codes,te=ee.ERR_INVALID_ARG_TYPE,ne=ee.ERR_METHOD_NOT_IMPLEMENTED,ie=ee.ERR_MULTIPLE_CALLBACK,oe=ee.ERR_STREAM_CANNOT_PIPE,ce=ee.ERR_STREAM_DESTROYED,fe=ee.ERR_STREAM_NULL_VALUES,se=ee.ERR_STREAM_WRITE_AFTER_END,de=ee.ERR_UNKNOWN_ENCODING,ue=X.errorOrDestroy;inherits_browserExports(be,q);function pe(){}function ve(je,ze,Ae){I=I||require_stream_duplex(),je=je||{},typeof Ae!="boolean"&&(Ae=ze instanceof I),this.objectMode=!!je.objectMode,Ae&&(this.objectMode=this.objectMode||!!je.writableObjectMode),this.highWaterMark=Q(this,je,"writableHighWaterMark",Ae),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var Re=je.decodeStrings===!1;this.decodeStrings=!Re,this.defaultEncoding=je.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(Ce){nt(ze,Ce)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=je.emitClose!==!1,this.autoDestroy=!!je.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new $(this)}ve.prototype.getBuffer=function(){for(var ze=this.bufferedRequest,Ae=[];ze;)Ae.push(ze),ze=ze.next;return Ae},function(){try{Object.defineProperty(ve.prototype,"buffer",{get:U.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var me;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(me=Function.prototype[Symbol.hasInstance],Object.defineProperty(be,Symbol.hasInstance,{value:function(ze){return me.call(this,ze)?!0:this!==be?!1:ze&&ze._writableState instanceof ve}})):me=function(ze){return ze instanceof this};function be(je){I=I||require_stream_duplex();var ze=this instanceof I;if(!ze&&!me.call(be,this))return new be(je);this._writableState=new ve(je,this,ze),this.writable=!0,je&&(typeof je.write=="function"&&(this._write=je.write),typeof je.writev=="function"&&(this._writev=je.writev),typeof je.destroy=="function"&&(this._destroy=je.destroy),typeof je.final=="function"&&(this._final=je.final)),q.call(this)}be.prototype.pipe=function(){ue(this,new oe)};function _e(je,ze){var Ae=new se;ue(je,Ae),process.nextTick(ze,Ae)}function Se(je,ze,Ae,Re){var Ce;return Ae===null?Ce=new fe:typeof Ae!="string"&&!ze.objectMode&&(Ce=new te("chunk",["string","Buffer"],Ae)),Ce?(ue(je,Ce),process.nextTick(Re,Ce),!1):!0}be.prototype.write=function(je,ze,Ae){var Re=this._writableState,Ce=!1,ge=!Re.objectMode&&J(je);return ge&&!G.isBuffer(je)&&(je=Y(je)),typeof ze=="function"&&(Ae=ze,ze=null),ge?ze="buffer":ze||(ze=Re.defaultEncoding),typeof Ae!="function"&&(Ae=pe),Re.ending?_e(this,Ae):(ge||Se(this,Re,je,Ae))&&(Re.pendingcb++,Ce=ke(this,Re,ge,je,ze,Ae)),Ce},be.prototype.cork=function(){this._writableState.corked++},be.prototype.uncork=function(){var je=this._writableState;je.corked&&(je.corked--,!je.writing&&!je.corked&&!je.bufferProcessing&&je.bufferedRequest&&it(this,je))},be.prototype.setDefaultEncoding=function(ze){if(typeof ze=="string"&&(ze=ze.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((ze+"").toLowerCase())>-1))throw new de(ze);return this._writableState.defaultEncoding=ze,this},Object.defineProperty(be.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function xe(je,ze,Ae){return!je.objectMode&&je.decodeStrings!==!1&&typeof ze=="string"&&(ze=G.from(ze,Ae)),ze}Object.defineProperty(be.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function ke(je,ze,Ae,Re,Ce,ge){if(!Ae){var ye=xe(ze,Re,Ce);Re!==ye&&(Ae=!0,Ce="buffer",Re=ye)}var Me=ze.objectMode?1:Re.length;ze.length+=Me;var Ke=ze.length<ze.highWaterMark;if(Ke||(ze.needDrain=!0),ze.writing||ze.corked){var st=ze.lastBufferedRequest;ze.lastBufferedRequest={chunk:Re,encoding:Ce,isBuf:Ae,callback:ge,next:null},st?st.next=ze.lastBufferedRequest:ze.bufferedRequest=ze.lastBufferedRequest,ze.bufferedRequestCount+=1}else De(je,ze,!1,Me,Re,Ce,ge);return Ke}function De(je,ze,Ae,Re,Ce,ge,ye){ze.writelen=Re,ze.writecb=ye,ze.writing=!0,ze.sync=!0,ze.destroyed?ze.onwrite(new ce("write")):Ae?je._writev(Ce,ze.onwrite):je._write(Ce,ge,ze.onwrite),ze.sync=!1}function Be(je,ze,Ae,Re,Ce){--ze.pendingcb,Ae?(process.nextTick(Ce,Re),process.nextTick(We,je,ze),je._writableState.errorEmitted=!0,ue(je,Re)):(Ce(Re),je._writableState.errorEmitted=!0,ue(je,Re),We(je,ze))}function Ve(je){je.writing=!1,je.writecb=null,je.length-=je.writelen,je.writelen=0}function nt(je,ze){var Ae=je._writableState,Re=Ae.sync,Ce=Ae.writecb;if(typeof Ce!="function")throw new ie;if(Ve(Ae),ze)Be(je,Ae,Re,ze,Ce);else{var ge=ut(Ae)||je.destroyed;!ge&&!Ae.corked&&!Ae.bufferProcessing&&Ae.bufferedRequest&&it(je,Ae),Re?process.nextTick(ot,je,Ae,ge,Ce):ot(je,Ae,ge,Ce)}}function ot(je,ze,Ae,Re){Ae||ft(je,ze),ze.pendingcb--,Re(),We(je,ze)}function ft(je,ze){ze.length===0&&ze.needDrain&&(ze.needDrain=!1,je.emit("drain"))}function it(je,ze){ze.bufferProcessing=!0;var Ae=ze.bufferedRequest;if(je._writev&&Ae&&Ae.next){var Re=ze.bufferedRequestCount,Ce=new Array(Re),ge=ze.corkedRequestsFree;ge.entry=Ae;for(var ye=0,Me=!0;Ae;)Ce[ye]=Ae,Ae.isBuf||(Me=!1),Ae=Ae.next,ye+=1;Ce.allBuffers=Me,De(je,ze,!0,ze.length,Ce,"",ge.finish),ze.pendingcb++,ze.lastBufferedRequest=null,ge.next?(ze.corkedRequestsFree=ge.next,ge.next=null):ze.corkedRequestsFree=new $(ze),ze.bufferedRequestCount=0}else{for(;Ae;){var Ke=Ae.chunk,st=Ae.encoding,dt=Ae.callback,$t=ze.objectMode?1:Ke.length;if(De(je,ze,!1,$t,Ke,st,dt),Ae=Ae.next,ze.bufferedRequestCount--,ze.writing)break}Ae===null&&(ze.lastBufferedRequest=null)}ze.bufferedRequest=Ae,ze.bufferProcessing=!1}be.prototype._write=function(je,ze,Ae){Ae(new ne("_write()"))},be.prototype._writev=null,be.prototype.end=function(je,ze,Ae){var Re=this._writableState;return typeof je=="function"?(Ae=je,je=null,ze=null):typeof ze=="function"&&(Ae=ze,ze=null),je!=null&&this.write(je,ze),Re.corked&&(Re.corked=1,this.uncork()),Re.ending||tt(this,Re,Ae),this},Object.defineProperty(be.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function ut(je){return je.ending&&je.length===0&&je.bufferedRequest===null&&!je.finished&&!je.writing}function et(je,ze){je._final(function(Ae){ze.pendingcb--,Ae&&ue(je,Ae),ze.prefinished=!0,je.emit("prefinish"),We(je,ze)})}function Ue(je,ze){!ze.prefinished&&!ze.finalCalled&&(typeof je._final=="function"&&!ze.destroyed?(ze.pendingcb++,ze.finalCalled=!0,process.nextTick(et,je,ze)):(ze.prefinished=!0,je.emit("prefinish")))}function We(je,ze){var Ae=ut(ze);if(Ae&&(Ue(je,ze),ze.pendingcb===0&&(ze.finished=!0,je.emit("finish"),ze.autoDestroy))){var Re=je._readableState;(!Re||Re.autoDestroy&&Re.endEmitted)&&je.destroy()}return Ae}function tt(je,ze,Ae){ze.ending=!0,We(je,ze),Ae&&(ze.finished?process.nextTick(Ae):je.once("finish",Ae)),ze.ended=!0,je.writable=!1}function vt(je,ze,Ae){var Re=je.entry;for(je.entry=null;Re;){var Ce=Re.callback;ze.pendingcb--,Ce(Ae),Re=Re.next}ze.corkedRequestsFree.next=je}return Object.defineProperty(be.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(ze){this._writableState&&(this._writableState.destroyed=ze)}}),be.prototype.destroy=X.destroy,be.prototype._undestroy=X.undestroy,be.prototype._destroy=function(je,ze){ze(je)},_stream_writable}var _stream_duplex,hasRequired_stream_duplex;function require_stream_duplex(){if(hasRequired_stream_duplex)return _stream_duplex;hasRequired_stream_duplex=1;var $=Object.keys||function(Z){var Q=[];for(var ee in Z)Q.push(ee);return Q};_stream_duplex=Y;var I=require_stream_readable(),U=require_stream_writable();inherits_browserExports(Y,I);for(var q=$(U.prototype),G=0;G<q.length;G++){var K=q[G];Y.prototype[K]||(Y.prototype[K]=U.prototype[K])}function Y(Z){if(!(this instanceof Y))return new Y(Z);I.call(this,Z),U.call(this,Z),this.allowHalfOpen=!0,Z&&(Z.readable===!1&&(this.readable=!1),Z.writable===!1&&(this.writable=!1),Z.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",J)))}Object.defineProperty(Y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(Y.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Y.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function J(){this._writableState.ended||process.nextTick(X,this)}function X(Z){Z.end()}return Object.defineProperty(Y.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(Q){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=Q,this._writableState.destroyed=Q)}}),_stream_duplex}var string_decoder={},safeBuffer={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var hasRequiredSafeBuffer;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,function($,I){var U=buffer,q=U.Buffer;function G(Y,J){for(var X in Y)J[X]=Y[X]}q.from&&q.alloc&&q.allocUnsafe&&q.allocUnsafeSlow?$.exports=U:(G(U,I),I.Buffer=K);function K(Y,J,X){return q(Y,J,X)}K.prototype=Object.create(q.prototype),G(q,K),K.from=function(Y,J,X){if(typeof Y=="number")throw new TypeError("Argument must not be a number");return q(Y,J,X)},K.alloc=function(Y,J,X){if(typeof Y!="number")throw new TypeError("Argument must be a number");var Z=q(Y);return J!==void 0?typeof X=="string"?Z.fill(J,X):Z.fill(J):Z.fill(0),Z},K.allocUnsafe=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return q(Y)},K.allocUnsafeSlow=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return U.SlowBuffer(Y)}}(safeBuffer,safeBuffer.exports)),safeBuffer.exports}var hasRequiredString_decoder;function requireString_decoder(){if(hasRequiredString_decoder)return string_decoder;hasRequiredString_decoder=1;var $=requireSafeBuffer().Buffer,I=$.isEncoding||function(fe){switch(fe=""+fe,fe&&fe.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function U(fe){if(!fe)return"utf8";for(var se;;)switch(fe){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return fe;default:if(se)return;fe=(""+fe).toLowerCase(),se=!0}}function q(fe){var se=U(fe);if(typeof se!="string"&&($.isEncoding===I||!I(fe)))throw new Error("Unknown encoding: "+fe);return se||fe}string_decoder.StringDecoder=G;function G(fe){this.encoding=q(fe);var se;switch(this.encoding){case"utf16le":this.text=ee,this.end=te,se=4;break;case"utf8":this.fillLast=X,se=4;break;case"base64":this.text=ne,this.end=ie,se=3;break;default:this.write=oe,this.end=ce;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=$.allocUnsafe(se)}G.prototype.write=function(fe){if(fe.length===0)return"";var se,de;if(this.lastNeed){if(se=this.fillLast(fe),se===void 0)return"";de=this.lastNeed,this.lastNeed=0}else de=0;return de<fe.length?se?se+this.text(fe,de):this.text(fe,de):se||""},G.prototype.end=Q,G.prototype.text=Z,G.prototype.fillLast=function(fe){if(this.lastNeed<=fe.length)return fe.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);fe.copy(this.lastChar,this.lastTotal-this.lastNeed,0,fe.length),this.lastNeed-=fe.length};function K(fe){return fe<=127?0:fe>>5===6?2:fe>>4===14?3:fe>>3===30?4:fe>>6===2?-1:-2}function Y(fe,se,de){var ue=se.length-1;if(ue<de)return 0;var pe=K(se[ue]);return pe>=0?(pe>0&&(fe.lastNeed=pe-1),pe):--ue<de||pe===-2?0:(pe=K(se[ue]),pe>=0?(pe>0&&(fe.lastNeed=pe-2),pe):--ue<de||pe===-2?0:(pe=K(se[ue]),pe>=0?(pe>0&&(pe===2?pe=0:fe.lastNeed=pe-3),pe):0))}function J(fe,se,de){if((se[0]&192)!==128)return fe.lastNeed=0,"�";if(fe.lastNeed>1&&se.length>1){if((se[1]&192)!==128)return fe.lastNeed=1,"�";if(fe.lastNeed>2&&se.length>2&&(se[2]&192)!==128)return fe.lastNeed=2,"�"}}function X(fe){var se=this.lastTotal-this.lastNeed,de=J(this,fe);if(de!==void 0)return de;if(this.lastNeed<=fe.length)return fe.copy(this.lastChar,se,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);fe.copy(this.lastChar,se,0,fe.length),this.lastNeed-=fe.length}function Z(fe,se){var de=Y(this,fe,se);if(!this.lastNeed)return fe.toString("utf8",se);this.lastTotal=de;var ue=fe.length-(de-this.lastNeed);return fe.copy(this.lastChar,0,ue),fe.toString("utf8",se,ue)}function Q(fe){var se=fe&&fe.length?this.write(fe):"";return this.lastNeed?se+"�":se}function ee(fe,se){if((fe.length-se)%2===0){var de=fe.toString("utf16le",se);if(de){var ue=de.charCodeAt(de.length-1);if(ue>=55296&&ue<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=fe[fe.length-2],this.lastChar[1]=fe[fe.length-1],de.slice(0,-1)}return de}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=fe[fe.length-1],fe.toString("utf16le",se,fe.length-1)}function te(fe){var se=fe&&fe.length?this.write(fe):"";if(this.lastNeed){var de=this.lastTotal-this.lastNeed;return se+this.lastChar.toString("utf16le",0,de)}return se}function ne(fe,se){var de=(fe.length-se)%3;return de===0?fe.toString("base64",se):(this.lastNeed=3-de,this.lastTotal=3,de===1?this.lastChar[0]=fe[fe.length-1]:(this.lastChar[0]=fe[fe.length-2],this.lastChar[1]=fe[fe.length-1]),fe.toString("base64",se,fe.length-de))}function ie(fe){var se=fe&&fe.length?this.write(fe):"";return this.lastNeed?se+this.lastChar.toString("base64",0,3-this.lastNeed):se}function oe(fe){return fe.toString(this.encoding)}function ce(fe){return fe&&fe.length?this.write(fe):""}return string_decoder}var ERR_STREAM_PREMATURE_CLOSE=errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE;function once$1($){var I=!1;return function(){if(!I){I=!0;for(var U=arguments.length,q=new Array(U),G=0;G<U;G++)q[G]=arguments[G];$.apply(this,q)}}}function noop$2(){}function isRequest$1($){return $.setHeader&&typeof $.abort=="function"}function eos$1($,I,U){if(typeof I=="function")return eos$1($,null,I);I||(I={}),U=once$1(U||noop$2);var q=I.readable||I.readable!==!1&&$.readable,G=I.writable||I.writable!==!1&&$.writable,K=function(){$.writable||J()},Y=$._writableState&&$._writableState.finished,J=function(){G=!1,Y=!0,q||U.call($)},X=$._readableState&&$._readableState.endEmitted,Z=function(){q=!1,X=!0,G||U.call($)},Q=function(ie){U.call($,ie)},ee=function(){var ie;if(q&&!X)return(!$._readableState||!$._readableState.ended)&&(ie=new ERR_STREAM_PREMATURE_CLOSE),U.call($,ie);if(G&&!Y)return(!$._writableState||!$._writableState.ended)&&(ie=new ERR_STREAM_PREMATURE_CLOSE),U.call($,ie)},te=function(){$.req.on("finish",J)};return isRequest$1($)?($.on("complete",J),$.on("abort",ee),$.req?te():$.on("request",te)):G&&!$._writableState&&($.on("end",K),$.on("close",K)),$.on("end",Z),$.on("finish",J),I.error!==!1&&$.on("error",Q),$.on("close",ee),function(){$.removeListener("complete",J),$.removeListener("abort",ee),$.removeListener("request",te),$.req&&$.req.removeListener("finish",J),$.removeListener("end",K),$.removeListener("close",K),$.removeListener("finish",J),$.removeListener("end",Z),$.removeListener("error",Q),$.removeListener("close",ee)}}var endOfStream=eos$1,async_iterator,hasRequiredAsync_iterator;function requireAsync_iterator(){if(hasRequiredAsync_iterator)return async_iterator;hasRequiredAsync_iterator=1;var $;function I(fe,se,de){return se in fe?Object.defineProperty(fe,se,{value:de,enumerable:!0,configurable:!0,writable:!0}):fe[se]=de,fe}var U=endOfStream,q=Symbol("lastResolve"),G=Symbol("lastReject"),K=Symbol("error"),Y=Symbol("ended"),J=Symbol("lastPromise"),X=Symbol("handlePromise"),Z=Symbol("stream");function Q(fe,se){return{value:fe,done:se}}function ee(fe){var se=fe[q];if(se!==null){var de=fe[Z].read();de!==null&&(fe[J]=null,fe[q]=null,fe[G]=null,se(Q(de,!1)))}}function te(fe){process.nextTick(ee,fe)}function ne(fe,se){return function(de,ue){fe.then(function(){if(se[Y]){de(Q(void 0,!0));return}se[X](de,ue)},ue)}}var ie=Object.getPrototypeOf(function(){}),oe=Object.setPrototypeOf(($={get stream(){return this[Z]},next:function(){var se=this,de=this[K];if(de!==null)return Promise.reject(de);if(this[Y])return Promise.resolve(Q(void 0,!0));if(this[Z].destroyed)return new Promise(function(me,be){process.nextTick(function(){se[K]?be(se[K]):me(Q(void 0,!0))})});var ue=this[J],pe;if(ue)pe=new Promise(ne(ue,this));else{var ve=this[Z].read();if(ve!==null)return Promise.resolve(Q(ve,!1));pe=new Promise(this[X])}return this[J]=pe,pe}},I($,Symbol.asyncIterator,function(){return this}),I($,"return",function(){var se=this;return new Promise(function(de,ue){se[Z].destroy(null,function(pe){if(pe){ue(pe);return}de(Q(void 0,!0))})})}),$),ie),ce=function(se){var de,ue=Object.create(oe,(de={},I(de,Z,{value:se,writable:!0}),I(de,q,{value:null,writable:!0}),I(de,G,{value:null,writable:!0}),I(de,K,{value:null,writable:!0}),I(de,Y,{value:se._readableState.endEmitted,writable:!0}),I(de,X,{value:function(ve,me){var be=ue[Z].read();be?(ue[J]=null,ue[q]=null,ue[G]=null,ve(Q(be,!1))):(ue[q]=ve,ue[G]=me)},writable:!0}),de));return ue[J]=null,U(se,function(pe){if(pe&&pe.code!=="ERR_STREAM_PREMATURE_CLOSE"){var ve=ue[G];ve!==null&&(ue[J]=null,ue[q]=null,ue[G]=null,ve(pe)),ue[K]=pe;return}var me=ue[q];me!==null&&(ue[J]=null,ue[q]=null,ue[G]=null,me(Q(void 0,!0))),ue[Y]=!0}),se.on("readable",te.bind(null,ue)),ue};return async_iterator=ce,async_iterator}var fromBrowser,hasRequiredFromBrowser;function requireFromBrowser(){return hasRequiredFromBrowser||(hasRequiredFromBrowser=1,fromBrowser=function(){throw new Error("Readable.from is not available in the browser")}),fromBrowser}var _stream_readable,hasRequired_stream_readable;function require_stream_readable(){if(hasRequired_stream_readable)return _stream_readable;hasRequired_stream_readable=1,_stream_readable=_e;var $;_e.ReadableState=be,eventsExports.EventEmitter;var I=function(ye,Me){return ye.listeners(Me).length},U=streamBrowser,q=buffer.Buffer,G=commonjsGlobal.Uint8Array||function(){};function K(ge){return q.from(ge)}function Y(ge){return q.isBuffer(ge)||ge instanceof G}var J=require$$3,X;J&&J.debuglog?X=J.debuglog("stream"):X=function(){};var Z=requireBuffer_list(),Q=destroy_1,ee=state,te=ee.getHighWaterMark,ne=errorsBrowser.codes,ie=ne.ERR_INVALID_ARG_TYPE,oe=ne.ERR_STREAM_PUSH_AFTER_EOF,ce=ne.ERR_METHOD_NOT_IMPLEMENTED,fe=ne.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,se,de,ue;inherits_browserExports(_e,U);var pe=Q.errorOrDestroy,ve=["error","close","destroy","pause","resume"];function me(ge,ye,Me){if(typeof ge.prependListener=="function")return ge.prependListener(ye,Me);!ge._events||!ge._events[ye]?ge.on(ye,Me):Array.isArray(ge._events[ye])?ge._events[ye].unshift(Me):ge._events[ye]=[Me,ge._events[ye]]}function be(ge,ye,Me){$=$||require_stream_duplex(),ge=ge||{},typeof Me!="boolean"&&(Me=ye instanceof $),this.objectMode=!!ge.objectMode,Me&&(this.objectMode=this.objectMode||!!ge.readableObjectMode),this.highWaterMark=te(this,ge,"readableHighWaterMark",Me),this.buffer=new Z,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=ge.emitClose!==!1,this.autoDestroy=!!ge.autoDestroy,this.destroyed=!1,this.defaultEncoding=ge.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,ge.encoding&&(se||(se=requireString_decoder().StringDecoder),this.decoder=new se(ge.encoding),this.encoding=ge.encoding)}function _e(ge){if($=$||require_stream_duplex(),!(this instanceof _e))return new _e(ge);var ye=this instanceof $;this._readableState=new be(ge,this,ye),this.readable=!0,ge&&(typeof ge.read=="function"&&(this._read=ge.read),typeof ge.destroy=="function"&&(this._destroy=ge.destroy)),U.call(this)}Object.defineProperty(_e.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(ye){this._readableState&&(this._readableState.destroyed=ye)}}),_e.prototype.destroy=Q.destroy,_e.prototype._undestroy=Q.undestroy,_e.prototype._destroy=function(ge,ye){ye(ge)},_e.prototype.push=function(ge,ye){var Me=this._readableState,Ke;return Me.objectMode?Ke=!0:typeof ge=="string"&&(ye=ye||Me.defaultEncoding,ye!==Me.encoding&&(ge=q.from(ge,ye),ye=""),Ke=!0),Se(this,ge,ye,!1,Ke)},_e.prototype.unshift=function(ge){return Se(this,ge,null,!0,!1)};function Se(ge,ye,Me,Ke,st){X("readableAddChunk",ye);var dt=ge._readableState;if(ye===null)dt.reading=!1,nt(ge,dt);else{var $t;if(st||($t=ke(dt,ye)),$t)pe(ge,$t);else if(dt.objectMode||ye&&ye.length>0)if(typeof ye!="string"&&!dt.objectMode&&Object.getPrototypeOf(ye)!==q.prototype&&(ye=K(ye)),Ke)dt.endEmitted?pe(ge,new fe):xe(ge,dt,ye,!0);else if(dt.ended)pe(ge,new oe);else{if(dt.destroyed)return!1;dt.reading=!1,dt.decoder&&!Me?(ye=dt.decoder.write(ye),dt.objectMode||ye.length!==0?xe(ge,dt,ye,!1):it(ge,dt)):xe(ge,dt,ye,!1)}else Ke||(dt.reading=!1,it(ge,dt))}return!dt.ended&&(dt.length<dt.highWaterMark||dt.length===0)}function xe(ge,ye,Me,Ke){ye.flowing&&ye.length===0&&!ye.sync?(ye.awaitDrain=0,ge.emit("data",Me)):(ye.length+=ye.objectMode?1:Me.length,Ke?ye.buffer.unshift(Me):ye.buffer.push(Me),ye.needReadable&&ot(ge)),it(ge,ye)}function ke(ge,ye){var Me;return!Y(ye)&&typeof ye!="string"&&ye!==void 0&&!ge.objectMode&&(Me=new ie("chunk",["string","Buffer","Uint8Array"],ye)),Me}_e.prototype.isPaused=function(){return this._readableState.flowing===!1},_e.prototype.setEncoding=function(ge){se||(se=requireString_decoder().StringDecoder);var ye=new se(ge);this._readableState.decoder=ye,this._readableState.encoding=this._readableState.decoder.encoding;for(var Me=this._readableState.buffer.head,Ke="";Me!==null;)Ke+=ye.write(Me.data),Me=Me.next;return this._readableState.buffer.clear(),Ke!==""&&this._readableState.buffer.push(Ke),this._readableState.length=Ke.length,this};var De=1073741824;function Be(ge){return ge>=De?ge=De:(ge--,ge|=ge>>>1,ge|=ge>>>2,ge|=ge>>>4,ge|=ge>>>8,ge|=ge>>>16,ge++),ge}function Ve(ge,ye){return ge<=0||ye.length===0&&ye.ended?0:ye.objectMode?1:ge!==ge?ye.flowing&&ye.length?ye.buffer.head.data.length:ye.length:(ge>ye.highWaterMark&&(ye.highWaterMark=Be(ge)),ge<=ye.length?ge:ye.ended?ye.length:(ye.needReadable=!0,0))}_e.prototype.read=function(ge){X("read",ge),ge=parseInt(ge,10);var ye=this._readableState,Me=ge;if(ge!==0&&(ye.emittedReadable=!1),ge===0&&ye.needReadable&&((ye.highWaterMark!==0?ye.length>=ye.highWaterMark:ye.length>0)||ye.ended))return X("read: emitReadable",ye.length,ye.ended),ye.length===0&&ye.ended?Ae(this):ot(this),null;if(ge=Ve(ge,ye),ge===0&&ye.ended)return ye.length===0&&Ae(this),null;var Ke=ye.needReadable;X("need readable",Ke),(ye.length===0||ye.length-ge<ye.highWaterMark)&&(Ke=!0,X("length less than watermark",Ke)),ye.ended||ye.reading?(Ke=!1,X("reading or ended",Ke)):Ke&&(X("do read"),ye.reading=!0,ye.sync=!0,ye.length===0&&(ye.needReadable=!0),this._read(ye.highWaterMark),ye.sync=!1,ye.reading||(ge=Ve(Me,ye)));var st;return ge>0?st=ze(ge,ye):st=null,st===null?(ye.needReadable=ye.length<=ye.highWaterMark,ge=0):(ye.length-=ge,ye.awaitDrain=0),ye.length===0&&(ye.ended||(ye.needReadable=!0),Me!==ge&&ye.ended&&Ae(this)),st!==null&&this.emit("data",st),st};function nt(ge,ye){if(X("onEofChunk"),!ye.ended){if(ye.decoder){var Me=ye.decoder.end();Me&&Me.length&&(ye.buffer.push(Me),ye.length+=ye.objectMode?1:Me.length)}ye.ended=!0,ye.sync?ot(ge):(ye.needReadable=!1,ye.emittedReadable||(ye.emittedReadable=!0,ft(ge)))}}function ot(ge){var ye=ge._readableState;X("emitReadable",ye.needReadable,ye.emittedReadable),ye.needReadable=!1,ye.emittedReadable||(X("emitReadable",ye.flowing),ye.emittedReadable=!0,process.nextTick(ft,ge))}function ft(ge){var ye=ge._readableState;X("emitReadable_",ye.destroyed,ye.length,ye.ended),!ye.destroyed&&(ye.length||ye.ended)&&(ge.emit("readable"),ye.emittedReadable=!1),ye.needReadable=!ye.flowing&&!ye.ended&&ye.length<=ye.highWaterMark,je(ge)}function it(ge,ye){ye.readingMore||(ye.readingMore=!0,process.nextTick(ut,ge,ye))}function ut(ge,ye){for(;!ye.reading&&!ye.ended&&(ye.length<ye.highWaterMark||ye.flowing&&ye.length===0);){var Me=ye.length;if(X("maybeReadMore read 0"),ge.read(0),Me===ye.length)break}ye.readingMore=!1}_e.prototype._read=function(ge){pe(this,new ce("_read()"))},_e.prototype.pipe=function(ge,ye){var Me=this,Ke=this._readableState;switch(Ke.pipesCount){case 0:Ke.pipes=ge;break;case 1:Ke.pipes=[Ke.pipes,ge];break;default:Ke.pipes.push(ge);break}Ke.pipesCount+=1,X("pipe count=%d opts=%j",Ke.pipesCount,ye);var st=(!ye||ye.end!==!1)&&ge!==process.stdout&&ge!==process.stderr,dt=st?Et:Ut;Ke.endEmitted?process.nextTick(dt):Me.once("end",dt),ge.on("unpipe",$t);function $t(le,re){X("onunpipe"),le===Me&&re&&re.hasUnpiped===!1&&(re.hasUnpiped=!0,Gt())}function Et(){X("onend"),ge.end()}var rt=et(Me);ge.on("drain",rt);var jt=!1;function Gt(){X("cleanup"),ge.removeListener("close",nn),ge.removeListener("finish",St),ge.removeListener("drain",rt),ge.removeListener("error",zt),ge.removeListener("unpipe",$t),Me.removeListener("end",Et),Me.removeListener("end",Ut),Me.removeListener("data",At),jt=!0,Ke.awaitDrain&&(!ge._writableState||ge._writableState.needDrain)&&rt()}Me.on("data",At);function At(le){X("ondata");var re=ge.write(le);X("dest.write",re),re===!1&&((Ke.pipesCount===1&&Ke.pipes===ge||Ke.pipesCount>1&&Ce(Ke.pipes,ge)!==-1)&&!jt&&(X("false write response, pause",Ke.awaitDrain),Ke.awaitDrain++),Me.pause())}function zt(le){X("onerror",le),Ut(),ge.removeListener("error",zt),I(ge,"error")===0&&pe(ge,le)}me(ge,"error",zt);function nn(){ge.removeListener("finish",St),Ut()}ge.once("close",nn);function St(){X("onfinish"),ge.removeListener("close",nn),Ut()}ge.once("finish",St);function Ut(){X("unpipe"),Me.unpipe(ge)}return ge.emit("pipe",Me),Ke.flowing||(X("pipe resume"),Me.resume()),ge};function et(ge){return function(){var Me=ge._readableState;X("pipeOnDrain",Me.awaitDrain),Me.awaitDrain&&Me.awaitDrain--,Me.awaitDrain===0&&I(ge,"data")&&(Me.flowing=!0,je(ge))}}_e.prototype.unpipe=function(ge){var ye=this._readableState,Me={hasUnpiped:!1};if(ye.pipesCount===0)return this;if(ye.pipesCount===1)return ge&&ge!==ye.pipes?this:(ge||(ge=ye.pipes),ye.pipes=null,ye.pipesCount=0,ye.flowing=!1,ge&&ge.emit("unpipe",this,Me),this);if(!ge){var Ke=ye.pipes,st=ye.pipesCount;ye.pipes=null,ye.pipesCount=0,ye.flowing=!1;for(var dt=0;dt<st;dt++)Ke[dt].emit("unpipe",this,{hasUnpiped:!1});return this}var $t=Ce(ye.pipes,ge);return $t===-1?this:(ye.pipes.splice($t,1),ye.pipesCount-=1,ye.pipesCount===1&&(ye.pipes=ye.pipes[0]),ge.emit("unpipe",this,Me),this)},_e.prototype.on=function(ge,ye){var Me=U.prototype.on.call(this,ge,ye),Ke=this._readableState;return ge==="data"?(Ke.readableListening=this.listenerCount("readable")>0,Ke.flowing!==!1&&this.resume()):ge==="readable"&&!Ke.endEmitted&&!Ke.readableListening&&(Ke.readableListening=Ke.needReadable=!0,Ke.flowing=!1,Ke.emittedReadable=!1,X("on readable",Ke.length,Ke.reading),Ke.length?ot(this):Ke.reading||process.nextTick(We,this)),Me},_e.prototype.addListener=_e.prototype.on,_e.prototype.removeListener=function(ge,ye){var Me=U.prototype.removeListener.call(this,ge,ye);return ge==="readable"&&process.nextTick(Ue,this),Me},_e.prototype.removeAllListeners=function(ge){var ye=U.prototype.removeAllListeners.apply(this,arguments);return(ge==="readable"||ge===void 0)&&process.nextTick(Ue,this),ye};function Ue(ge){var ye=ge._readableState;ye.readableListening=ge.listenerCount("readable")>0,ye.resumeScheduled&&!ye.paused?ye.flowing=!0:ge.listenerCount("data")>0&&ge.resume()}function We(ge){X("readable nexttick read 0"),ge.read(0)}_e.prototype.resume=function(){var ge=this._readableState;return ge.flowing||(X("resume"),ge.flowing=!ge.readableListening,tt(this,ge)),ge.paused=!1,this};function tt(ge,ye){ye.resumeScheduled||(ye.resumeScheduled=!0,process.nextTick(vt,ge,ye))}function vt(ge,ye){X("resume",ye.reading),ye.reading||ge.read(0),ye.resumeScheduled=!1,ge.emit("resume"),je(ge),ye.flowing&&!ye.reading&&ge.read(0)}_e.prototype.pause=function(){return X("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(X("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function je(ge){var ye=ge._readableState;for(X("flow",ye.flowing);ye.flowing&&ge.read()!==null;);}_e.prototype.wrap=function(ge){var ye=this,Me=this._readableState,Ke=!1;ge.on("end",function(){if(X("wrapped end"),Me.decoder&&!Me.ended){var $t=Me.decoder.end();$t&&$t.length&&ye.push($t)}ye.push(null)}),ge.on("data",function($t){if(X("wrapped data"),Me.decoder&&($t=Me.decoder.write($t)),!(Me.objectMode&&$t==null)&&!(!Me.objectMode&&(!$t||!$t.length))){var Et=ye.push($t);Et||(Ke=!0,ge.pause())}});for(var st in ge)this[st]===void 0&&typeof ge[st]=="function"&&(this[st]=function(Et){return function(){return ge[Et].apply(ge,arguments)}}(st));for(var dt=0;dt<ve.length;dt++)ge.on(ve[dt],this.emit.bind(this,ve[dt]));return this._read=function($t){X("wrapped _read",$t),Ke&&(Ke=!1,ge.resume())},this},typeof Symbol=="function"&&(_e.prototype[Symbol.asyncIterator]=function(){return de===void 0&&(de=requireAsync_iterator()),de(this)}),Object.defineProperty(_e.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_e.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_e.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(ye){this._readableState&&(this._readableState.flowing=ye)}}),_e._fromList=ze,Object.defineProperty(_e.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function ze(ge,ye){if(ye.length===0)return null;var Me;return ye.objectMode?Me=ye.buffer.shift():!ge||ge>=ye.length?(ye.decoder?Me=ye.buffer.join(""):ye.buffer.length===1?Me=ye.buffer.first():Me=ye.buffer.concat(ye.length),ye.buffer.clear()):Me=ye.buffer.consume(ge,ye.decoder),Me}function Ae(ge){var ye=ge._readableState;X("endReadable",ye.endEmitted),ye.endEmitted||(ye.ended=!0,process.nextTick(Re,ye,ge))}function Re(ge,ye){if(X("endReadableNT",ge.endEmitted,ge.length),!ge.endEmitted&&ge.length===0&&(ge.endEmitted=!0,ye.readable=!1,ye.emit("end"),ge.autoDestroy)){var Me=ye._writableState;(!Me||Me.autoDestroy&&Me.finished)&&ye.destroy()}}typeof Symbol=="function"&&(_e.from=function(ge,ye){return ue===void 0&&(ue=requireFromBrowser()),ue(_e,ge,ye)});function Ce(ge,ye){for(var Me=0,Ke=ge.length;Me<Ke;Me++)if(ge[Me]===ye)return Me;return-1}return _stream_readable}var _stream_transform=Transform$1,_require$codes$1=errorsBrowser.codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes$1.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes$1.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require_stream_duplex();inherits_browserExports(Transform$1,Duplex);function afterTransform($,I){var U=this._transformState;U.transforming=!1;var q=U.writecb;if(q===null)return this.emit("error",new ERR_MULTIPLE_CALLBACK);U.writechunk=null,U.writecb=null,I!=null&&this.push(I),q($);var G=this._readableState;G.reading=!1,(G.needReadable||G.length<G.highWaterMark)&&this._read(G.highWaterMark)}function Transform$1($){if(!(this instanceof Transform$1))return new Transform$1($);Duplex.call(this,$),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,$&&(typeof $.transform=="function"&&(this._transform=$.transform),typeof $.flush=="function"&&(this._flush=$.flush)),this.on("prefinish",prefinish)}function prefinish(){var $=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(I,U){done$1($,I,U)}):done$1(this,null,null)}Transform$1.prototype.push=function($,I){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,$,I)},Transform$1.prototype._transform=function($,I,U){U(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform$1.prototype._write=function($,I,U){var q=this._transformState;if(q.writecb=U,q.writechunk=$,q.writeencoding=I,!q.transforming){var G=this._readableState;(q.needTransform||G.needReadable||G.length<G.highWaterMark)&&this._read(G.highWaterMark)}},Transform$1.prototype._read=function($){var I=this._transformState;I.writechunk!==null&&!I.transforming?(I.transforming=!0,this._transform(I.writechunk,I.writeencoding,I.afterTransform)):I.needTransform=!0},Transform$1.prototype._destroy=function($,I){Duplex.prototype._destroy.call(this,$,function(U){I(U)})};function done$1($,I,U){if(I)return $.emit("error",I);if(U!=null&&$.push(U),$._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if($._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return $.push(null)}var _stream_passthrough=PassThrough,Transform=_stream_transform;inherits_browserExports(PassThrough,Transform);function PassThrough($){if(!(this instanceof PassThrough))return new PassThrough($);Transform.call(this,$)}PassThrough.prototype._transform=function($,I,U){U(null,$)};var eos;function once($){var I=!1;return function(){I||(I=!0,$.apply(void 0,arguments))}}var _require$codes=errorsBrowser.codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop$1($){if($)throw $}function isRequest($){return $.setHeader&&typeof $.abort=="function"}function destroyer($,I,U,q){q=once(q);var G=!1;$.on("close",function(){G=!0}),eos===void 0&&(eos=endOfStream),eos($,{readable:I,writable:U},function(Y){if(Y)return q(Y);G=!0,q()});var K=!1;return function(Y){if(!G&&!K){if(K=!0,isRequest($))return $.abort();if(typeof $.destroy=="function")return $.destroy();q(Y||new ERR_STREAM_DESTROYED("pipe"))}}}function call($){$()}function pipe($,I){return $.pipe(I)}function popCallback($){return!$.length||typeof $[$.length-1]!="function"?noop$1:$.pop()}function pipeline(){for(var $=arguments.length,I=new Array($),U=0;U<$;U++)I[U]=arguments[U];var q=popCallback(I);if(Array.isArray(I[0])&&(I=I[0]),I.length<2)throw new ERR_MISSING_ARGS("streams");var G,K=I.map(function(Y,J){var X=J<I.length-1,Z=J>0;return destroyer(Y,X,Z,function(Q){G||(G=Q),Q&&K.forEach(call),!X&&(K.forEach(call),q(G))})});return I.reduce(pipe)}var pipeline_1=pipeline;(function($,I){I=$.exports=require_stream_readable(),I.Stream=I,I.Readable=I,I.Writable=require_stream_writable(),I.Duplex=require_stream_duplex(),I.Transform=_stream_transform,I.PassThrough=_stream_passthrough,I.finished=endOfStream,I.pipeline=pipeline_1})(readableBrowser,readableBrowser.exports);var readableBrowserExports=readableBrowser.exports,createPromiseFromCallback=$=>new Promise((I,U)=>{$((q,G)=>{q?U(q):I(G)})}),TimeoutError=class extends Error{constructor($,I){super($?`Timeout [${$.toLocaleString()}ms]${I===void 0?"":`: ${I}`}`:"Timeout")}},sleep=$=>new Promise(I=>{const U=Date.now()+$,q=()=>{const G=U-Date.now();G>0?setTimeout(q,G):I()};q()}),asyncTimeout=async($,I,U)=>{let q;const G=U===void 0||typeof U=="string"?new TimeoutError(I,U):U,K=new Promise((J,X)=>{q=setTimeout(()=>{X(G)},I),unrefTimeout(q)}),Y=typeof $=="function"?createPromiseFromCallback($):$;return await Promise.race([Y,K]).finally(()=>{clearTimeout(q)})},unrefTimeout=$=>{typeof $=="object"&&"unref"in $&&$.unref()},Event$1=class hr{constructor(){this._listeners=new Set,this._effects=new Set}static wrap(I,U){const q=new hr;return q.addEffect(()=>{const G=K=>q.emit(K);return I.on(U,G),()=>I.off(U,G)}),q}emit(I){for(const U of this._listeners)U.trigger(I),U.once&&this._listeners.delete(U)}on(I,U,q){const[G,K]=I instanceof Context?[I,U]:[new Context,I],Y=!!(q!=null&&q.weak),J=!!(q!=null&&q.once),X=new EventListener(this,K,G,J,Y);return this._addListener(X),()=>{this._removeListener(X)}}off(I){for(const U of this._listeners)U.derefCallback()===I&&this._removeListener(U)}once(I,U){const[q,G]=I instanceof Context?[I,U]:[new Context,I],K=new EventListener(this,G,q,!0,!1);return this._addListener(K),()=>{this._removeListener(K)}}async*[Symbol.asyncIterator](){for(;;)yield await new Promise(I=>{this.once(I)})}waitFor(I){return new Promise(U=>{const q=this.on(G=>{I(G)&&(q(),U(G))})})}waitForCount(I){let U=0;return this.waitFor(()=>++U===I)}async waitForCondition(I){I()||await this.waitFor(I)}listenerCount(){return this._listeners.size}addEffect(I){const U={effect:I,cleanup:void 0};return this.listenerCount()>0&&(U.cleanup=U.effect()),this._effects.add(U),()=>{var q;(q=U.cleanup)==null||q.call(U),this._effects.delete(U)}}debounce(I=0){let U,q;const G=new hr;return G.addEffect(()=>{const K=this.on(()=>{if(!U){const Y=!q||Date.now()-q>I?I/8:I;U=setTimeout(()=>{q=Date.now(),U=void 0,G.emit()},Y)}});return()=>{K(),clearTimeout(U)}}),G}discardParameter(){return this}toJSON(){return{listenerCount:this.listenerCount()}}_addListener(I){this._listeners.add(I),this.listenerCount()===1&&this._runEffects()}_removeListener(I){this._listeners.delete(I),I.remove(),this.listenerCount()===0&&this._cleanupEffects()}_runEffects(){for(const I of this._effects)I.cleanup=I.effect()}_cleanupEffects(){var I;for(const U of this._effects)(I=U.cleanup)==null||I.call(U),U.cleanup=void 0}},EventListener=class{constructor($,I,U,q,G){this.ctx=U,this.once=q,this.weak=G,this._clearDispose=void 0,this._clearDispose=U.onDispose(()=>{$._removeListener(this)}),G?(this.callback=new WeakRef(I),weakListeners().registry.register(I,{event:new WeakRef($),listener:this},this)):this.callback=I}derefCallback(){return this.weak?this.callback.deref():this.callback}async trigger($){try{const I=this.derefCallback();await(I==null?void 0:I($))}catch(I){this.ctx.raise(I)}}remove(){var $;($=this._clearDispose)==null||$.call(this),weakListeners().registry.unregister(this)}},weakListenersState=null,weakListeners=()=>(weakListenersState??(weakListenersState=new FinalizationRegistry(({event:$,listener:I})=>{var U;(U=$.deref())==null||U._removeListener(I)})),{registry:weakListenersState}),Trigger=class{constructor($={autoReset:!1}){this._options=$,this.reset()}async wait({timeout:$}={}){return $?asyncTimeout(this._promise,$,new TimeoutError($)):this._promise}wake($){return this._wake($),this._options.autoReset?this.reset():this}reset(){return this._promise=new Promise($=>{this._wake=$}),this}throw($){return this._wake(Promise.reject($)),this._options.autoReset?this.reset():this}},MulticastObservable=class Jn extends Observable{constructor(I,U){super(q=>this._subscribe(q)),this._value=U,this._observers=new Set,this._completed=new Trigger,this._handlers={next:q=>{this._value=q,this._observers.forEach(G=>{var K;return(K=G.next)==null?void 0:K.call(G,q)})},error:q=>{this._observers.forEach(G=>{var K;return(K=G.error)==null?void 0:K.call(G,q)})},complete:()=>{this._completed.wake(),this._observers.forEach(q=>{var G;return(G=q.complete)==null?void 0:G.call(q)})}},this._observable=typeof I=="function"?new Observable(I):I,this._observable.subscribe(this._handlers)}static from(I,U){if("emit"in I)return new Jn(G=>{I.on(K=>{G.next(K)})},U);const q=Observable.from(I);return new Jn(q,U)}static of(...I){return new Jn(Observable.of(...I.slice(1)),I[0])}static empty(){return EMPTY_OBSERVABLE}get(){if(this._value===void 0)throw new Error("MulticastObservable is not initialized.");return this._value}async wait({timeout:I}={}){return await this._completed.wait({timeout:I}),this.get()}forEach(I){return this._observable.forEach(I)}map(I){return new Jn(this._observable.map(I),this._value&&I(this._value))}filter(I){return new Jn(this._observable.filter(I),this._value&&I(this._value)?this._value:void 0)}reduce(I,U){return new Jn(U?this._observable.reduce(I,U):this._observable.reduce(I),U??this._value)}flatMap(I){return new Jn(this._observable.flatMap(I),this._value&&I(this._value).get())}concat(...I){return new Jn(this._observable.concat(...I),this._value)}losslessConcat(I,...U){const q=U.filter(K=>K instanceof Jn),G=I(this._value,q.map(K=>K.get()));return new Jn(this._observable.concat(...U),G)}_subscribe(I){var U;return this._observers.has(I)||this._observers.add(I),this._value!==void 0&&((U=I.next)==null||U.call(I,this._value)),()=>{this._observers.delete(I)}}},EMPTY_OBSERVABLE=MulticastObservable.of(null),Mutex=class{constructor(){this._queue=Promise.resolve(),this._tag=null}get tag(){return this._tag}async acquire($){const I=this._queue;let U;return this._queue=new Promise(q=>{U=new MutexGuard(()=>{this._tag=null,q()})}),await I,$!==void 0&&(this._tag=$),U}async executeSynchronized($){const I=await this.acquire();try{return await $()}finally{I.release()}}},MutexGuard=class{constructor($){this._release=$}release(){this._release()}[Symbol.dispose](){this.release()}},classMutexSymbol=Symbol("class-mutex"),enableWarning=globalThis.mochaExecutor,synchronized=($,I,U)=>{const q=U.value;U.value=async function(...K){const Y=this[classMutexSymbol]??(this[classMutexSymbol]=new Mutex),J=`${$.constructor.name}.${I}`;let X;enableWarning?X=await warnAfterTimeout(1e4,`lock on ${J} (taken by ${Y.tag})`,()=>Y.acquire(J)):X=await Y.acquire(J);try{return await q.apply(this,K)}finally{X.release()}},Object.defineProperty(U.value,"name",{value:I+"$synchronized"})},__dxlog_file2$5="/home/runner/work/dxos/dxos/packages/common/async/src/track-leaks.ts",enabled=typeof process<"u"&&!!process.env.DX_TRACK_LEAKS,openResources=new Set,trackResource=$=>{if(!enabled)return()=>{};const I=$();return openResources.add(I),()=>{openResources.delete(I)}},dumpLeaks=()=>{if(enabled){log$2.info(`Leaked resources ${openResources.size}:`,void 0,{F:__dxlog_file2$5,L:82,S:void 0,C:($,I)=>$(...I)});for(const $ of openResources)log$2.info(`- ${$.name} at`,void 0,{F:__dxlog_file2$5,L:84,S:void 0,C:(I,U)=>I(...U)}),log$2.info($.openStack.getStack(1),void 0,{F:__dxlog_file2$5,L:85,S:void 0,C:(I,U)=>I(...U)}),log$2.info(`
|
|
852
|
-
`,void 0,{F:__dxlog_file2$5,L:86,S:void 0,C:(I,U)=>I(...U)})}};enabled&&(global.dxDumpLeaks=dumpLeaks);var DeferredTask=class{constructor($,I){this._ctx=$,this._callback=I,this._scheduled=!1,this._promise=null}schedule(){this._scheduled||(scheduleTask(this._ctx,async()=>{await this._promise,this._scheduled=!1,this._promise=runInContextAsync(this._ctx,()=>this._callback())}),this._scheduled=!0)}},runInContextAsync=async($,I)=>{try{await I()}catch(U){$.raise(U)}},scheduleTask=($,I,U)=>{const q=trackResource(()=>({name:`task (${I.name||"anonymous"})`,openStack:new StackTrace})),G=setTimeout(async()=>{K(),await runInContextAsync($,I),q()},U),K=$.onDispose(()=>{q(),clearTimeout(G)})},scheduleTaskInterval=($,I,U)=>{const q=trackResource(()=>({name:`repeating task (${I.name||"anonymous"})`,openStack:new StackTrace}));let G;const K=async()=>{await runInContextAsync($,I),!$.disposed&&(G=setTimeout(K,U))};G=setTimeout(K,U),$.onDispose(()=>{q(),clearTimeout(G)})},__dxlog_file$7="/home/runner/work/dxos/dxos/packages/sdk/react-client/src/invitations/useInvitationStatus.ts",useInvitationStatus=$=>{const[I,U]=React.useReducer((Y,J)=>(log$2("useInvitationStatus",{action:J},{F:__dxlog_file$7,L:81,S:void 0,C:(X,Z)=>X(...Z)}),{...Y,status:J.status,result:J.status===Invitation.State.SUCCESS?J.result:Y.result,...J.status===Invitation.State.ERROR&&{error:J.error},...(J.status===Invitation.State.ERROR||J.status===Invitation.State.CANCELLED||J.status===Invitation.State.TIMEOUT)&&{haltedAt:typeof Y.haltedAt>"u"?J.haltedAt:Y.haltedAt},observable:J.status===Invitation.State.CONNECTING?J.observable??Y.observable:Y.observable}),null,Y=>({status:Invitation.State.INIT,result:{spaceKey:null,identityKey:null,swarmKey:null,target:null},observable:$}));React.useEffect(()=>{var Z,Q;const Y=ee=>{switch(ee.state){case Invitation.State.CONNECTED:case Invitation.State.READY_FOR_AUTHENTICATION:case Invitation.State.AUTHENTICATING:{U({status:ee.state});break}case Invitation.State.SUCCESS:{U({status:ee.state,result:{spaceKey:ee.spaceKey||null,identityKey:ee.identityKey||null,swarmKey:ee.swarmKey||null,target:ee.target||null}});break}case Invitation.State.CANCELLED:case Invitation.State.TIMEOUT:{U({status:ee.state,haltedAt:I.status});break}}},J=(Z=I.observable)==null?void 0:Z.subscribe(Y,ee=>{U({status:Invitation.State.ERROR,error:ee,haltedAt:I.status})}),X=(Q=I.observable)==null?void 0:Q.get();return X&&Y(X),()=>J==null?void 0:J.unsubscribe()},[I.observable,I.status]);const q=React.useCallback(Y=>{U({status:Invitation.State.CONNECTING,observable:Y})},[]),G=React.useCallback(Y=>(log$2("authenticating...",{authCode:Y},{F:__dxlog_file$7,L:165,S:void 0,C:(J,X)=>J(...X)}),I.observable.authenticate(Y)),[I.observable]),K=React.useCallback(async()=>{var Y;return(Y=I.observable)==null?void 0:Y.cancel()},[I.observable]);return React.useMemo(()=>{var X;const Y=(X=I.observable)==null?void 0:X.get();return{status:I.status,haltedAt:I.haltedAt,result:I.result,error:I.error,cancel:K,connect:q,authenticate:G,id:Y==null?void 0:Y.invitationId,multiUse:Y==null?void 0:Y.multiUse,invitationCode:Y?clientProtocol.InvitationEncoder.encode(Y):void 0,authCode:Y==null?void 0:Y.authCode,authMethod:Y==null?void 0:Y.authMethod,type:Y==null?void 0:Y.type}},[I,K,q,G])};const AuthCode=$=>{const{code:I,large:U,classNames:q}=$,G=(I==null?void 0:I.length)??0,K=I==null?void 0:I.slice(0,G/2),Y=I==null?void 0:I.slice(G/2),J=()=>{navigator.clipboard.writeText(I??"")};return React.createElement("span",{className:mx(U?"text-6xl":"text-2xl","font-mono pli-2.5 flex gap-1.5 rounded cursor-pointer",q),onClick:J},React.createElement("span",null,K),React.createElement("span",null,Y))},InvitationListItem=$=>{const{invitation:I}=$,U=useInvitationStatus(I);return React.createElement(InvitationListItemImpl,{...$,invitationStatus:U})},avatarProps={size:10,variant:"circle"},AvatarStackEffect=({animation:$,status:I,reverseEffects:U})=>{const{tx:q}=useThemeContext();return React.createElement(React.Fragment,null,React.createElement("span",{role:"none",className:mx("absolute inline-end-auto opacity-20",U?"inline-start-3":"inline-start-1",getSize(avatarProps.size))},React.createElement("span",{role:"none",className:q("avatar.ring","avatar__ring",{...avatarProps,status:I,animation:$}),style:{animationDelay:"400ms"}})),React.createElement("span",{role:"none",className:mx("absolute inline-end-auto opacity-50","inline-start-2",getSize(avatarProps.size))},React.createElement("span",{role:"none",className:q("avatar.ring","avatar__ring",{...avatarProps,status:I,animation:$}),style:{animationDelay:"200ms"}})))},InvitationListItemImpl=({invitation:$,invitationStatus:I,send:U,onClickRemove:q,createInvitationUrl:G,reverseEffects:K,...Y})=>{const{t:J}=useTranslation("os"),{cancel:X,status:Z,invitationCode:Q,authCode:ee,multiUse:te}=I,ne=!([Invitation.State.ERROR,Invitation.State.TIMEOUT,Invitation.State.CANCELLED].indexOf(Z)>=0),ie=te||[Invitation.State.INIT,Invitation.State.CONNECTING,Invitation.State.CONNECTED].indexOf(Z)>=0,oe=Z===Invitation.State.READY_FOR_AUTHENTICATION,ce=React.useCallback(()=>q==null?void 0:q($),[$,q]),fe=Q&&G(Q),se=$==null?void 0:$.get().invitationId,de=$==null?void 0:$.get().lifetime,ue=$!=null&&$.expiry?formatDistanceToNow($==null?void 0:$.expiry,{addSuffix:!0}):void 0,pe=[Invitation.State.INIT,Invitation.State.CONNECTING,Invitation.State.CONNECTED,Invitation.State.READY_FOR_AUTHENTICATION,Invitation.State.AUTHENTICATING].includes(Z)?"pulse":"none",ve=[Invitation.State.ERROR,Invitation.State.TIMEOUT,Invitation.State.CANCELLED].includes(Z),me=[Invitation.State.CONNECTED,Invitation.State.READY_FOR_AUTHENTICATION,Invitation.State.AUTHENTICATING,Invitation.State.SUCCESS].includes(Z),be=ve?"error":me?"active":"inactive";return React.createElement(ListItem.Root,{id:Q,...Y,classNames:["flex gap-2 pis-3 pie-1 items-center relative",Y.classNames]},React.createElement(ListItem.Heading,{classNames:"sr-only"},J(te?"invite many list item label":"invite one list item label")),te&&React.createElement(AvatarStackEffect,{status:be,animation:pe,reverseEffects:K}),React.createElement(Tooltip.Root,null,React.createElement(Avatar.Root,{...avatarProps,animation:pe,status:be},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Avatar.Frame,{tabIndex:0,classNames:[focusRing,"relative rounded-full place-self-center"]},React.createElement(Avatar.Fallback,{text:hexToEmoji(se)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"left",classNames:"z-[70]"},J(te?"invite many qr label":"invite one qr label"),React.createElement(Tooltip.Arrow,null)))),ie&&fe?React.createElement(Tooltip.Root,null,React.createElement(React.Fragment,null,React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Button,{variant:"ghost",classNames:"grow justify-start font-medium",onClick:()=>U({type:"selectInvitation",invitation:$}),"data-testid":"show-qrcode"},React.createElement("span",null,J("open share panel label")))),React.createElement(CopyButtonIconOnly,{variant:"ghost",value:fe})),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"left",classNames:"z-[70]"},de&&React.createElement("span",null,"Expires ",ue)))):oe?React.createElement(AuthCode,{code:ee,classNames:"grow"}):Z===Invitation.State.CONNECTING?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Connecting..."):Z===Invitation.State.AUTHENTICATING?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Authenticating..."):Z===Invitation.State.ERROR||Z===Invitation.State.TIMEOUT?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Failed"):Z===Invitation.State.CANCELLED?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Cancelled"):Z===Invitation.State.SUCCESS?React.createElement("span",{className:"pli-2 grow truncate"},"User joined"):React.createElement("span",{className:"grow"}," "),ne?React.createElement(Button,{variant:"ghost",classNames:"flex gap-1 pli-0",onClick:X,"data-testid":"cancel-invitation"},React.createElement("span",{className:"sr-only"},J("cancel invitation label")),React.createElement(react.X,{className:getSize(4)})):React.createElement(Button,{variant:"ghost",classNames:"flex gap-1 pli-0",onClick:ce,"data-testid":"remove-invitation"},React.createElement("span",{className:"sr-only"},J("remove invitation label")),React.createElement(react.X,{className:getSize(4)})))},InvitationList=({invitations:$,send:I,...U})=>{const{className:q,InvitationListItem:G=InvitationListItem}=U;return React.createElement(List,{classNames:mx("flex flex-col gap-2",q)},$.map(K=>{const Y=K.get().invitationId;return React.createElement(G,{key:Y,send:I,invitation:K,...U})}))},defaultActions={noopAction:{label:"No-op",description:"",icon:react.Placeholder,onClick:()=>{}}},BifurcatedAction=React.forwardRef(($,I)=>{const{classNames:U,variant:q,isFull:G=!0,actions:K=defaultActions,activeAction:Y,onChangeActiveAction:J,defaultActiveAction:X,...Z}=$,[Q=Object.keys(K)[0],ee]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:Y,onChange:J,defaultProp:X}),te=K[Q]??{},{t:ne}=useTranslation("os");return React.createElement("div",{role:"none",className:mx("mbs-2 flex gap-px items-center",G&&"is-full")},React.createElement(Button,{...Z,classNames:["bs-11 flex-1 min-is-0 flex gap-2 rounded-ie-none",U],ref:I,variant:q,onClick:te.onClick},te.icon&&React.createElement(te.icon,{className:getSize(5)}),React.createElement("span",null,te.label)),React.createElement(DropdownMenu2.Root,null,React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Button,{classNames:["bs-11 flex-none rounded-is-none",U]},React.createElement("span",{className:"sr-only"},ne("invite options label")),React.createElement(react.CaretDown,{className:getSize(4)}))),React.createElement(DropdownMenu2.Content,null,React.createElement(DropdownMenu2.Viewport,null,Object.entries(K).map(([ie,oe])=>React.createElement(DropdownMenu2.CheckboxItem,{key:ie,"aria-labelledby":`${ie}__label`,"aria-describedby":`${ie}__description`,checked:Q===ie,onCheckedChange:ce=>ce&&ee(ie),classNames:"gap-2"},oe.icon&&React.createElement(oe.icon,{className:getSize(5)}),React.createElement("div",{role:"none",className:"flex-1 min-is-0 space-b-1"},React.createElement("p",{id:`${ie}__label`},oe.label),oe.description&&React.createElement("p",{id:`${ie}__description`,className:descriptionText},oe.description)),React.createElement(DropdownMenu2.ItemIndicator,{asChild:!0},React.createElement(react.Check,{weight:"bold",className:getSize(4)}))))),React.createElement(DropdownMenu2.Arrow,null))))}),Action=React.forwardRef(($,I)=>{const{children:U,classNames:q,variant:G,isFull:K=!0,...Y}=$;return React.createElement(Button,{...Y,classNames:[K&&"is-full","bs-11 flex gap-2 mbs-2",q],ref:I,variant:G},U)}),Actions=React.forwardRef(({classNames:$,children:I,...U},q)=>React.createElement("div",{...U,className:mx("flex flex-col gap-2 mbs-2",Array.isArray(I)&&I.length>1?"justify-between":"justify-center",$),ref:q},I)),CloseButton=({onDone:$,...I})=>{const{t:U}=useTranslation("os");return React.createElement(Button,{variant:"ghost",classNames:mx("plb-0 pli-2 absolute block-start-0 inline-end-0 z-[1]"),onClick:()=>$==null?void 0:$(),...I},React.createElement(react.X,{weight:"bold",className:getSize(4)}),React.createElement("span",{className:"sr-only"},U("exit label")))},Emoji=({text:$,className:I})=>React.createElement("div",{role:"none",className:mx(getSize(14),"rounded relative pointer-events-none",I)},React.createElement("svg",{viewBox:`0 0 ${14*4} ${14*4}`,width:14*4,height:14*4},React.createElement("text",{x:"50%",y:"50%",textAnchor:"middle",dominantBaseline:"middle",baselineShift:"-0.25rem",fontSize:"2.25rem"},$))),Centered=$=>{const{children:I}=$;return React.createElement("div",{role:"none",className:"absolute inset-0 flex items-center justify-center"},I)},Heading=React.forwardRef(({titleId:$,title:I,titleSrOnly:U,children:q,corner:G},K)=>React.createElement("div",{role:"none",className:"pbe-2 relative",ref:K},G,React.createElement("h1",{...!U&&{id:$},className:mx(descriptionText,"text-center mlb-2",U&&"invisible")},I),U&&React.createElement("span",{id:$},I),q)),Label=$=>{const{children:I}=$;return React.createElement("span",{className:mx(descriptionText,"text-center mli-6 whitespace-normal")},I)},Input=({validationMessage:$,label:I,...U})=>React.createElement(Input$1.Root,null,React.createElement(Input$1.Label,null,I),React.createElement(Input$1.TextInput,{...U,classNames:"plb-3 mbs-2 text-center"}),React.createElement(Input$1.DescriptionAndValidation,null,$&&React.createElement(Input$1.Validation,null,$))),StepHeading=React.forwardRef(({children:$,className:I,...U},q)=>React.createElement("h2",{...U,className:mx("font-normal text-sm mbe-4 mli-1 text-center",I),ref:q},$));/*!
|
|
851
|
+
*/(function($){const I=base64Js,U=ieee754,q=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;$.Buffer=J,$.SlowBuffer=se,$.INSPECT_MAX_BYTES=50;const G=2147483647;$.kMaxLength=G,J.TYPED_ARRAY_SUPPORT=K(),!J.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function K(){try{const le=new Uint8Array(1),re={foo:function(){return 42}};return Object.setPrototypeOf(re,Uint8Array.prototype),Object.setPrototypeOf(le,re),le.foo()===42}catch{return!1}}Object.defineProperty(J.prototype,"parent",{enumerable:!0,get:function(){if(J.isBuffer(this))return this.buffer}}),Object.defineProperty(J.prototype,"offset",{enumerable:!0,get:function(){if(J.isBuffer(this))return this.byteOffset}});function Y(le){if(le>G)throw new RangeError('The value "'+le+'" is invalid for option "size"');const re=new Uint8Array(le);return Object.setPrototypeOf(re,J.prototype),re}function J(le,re,ae){if(typeof le=="number"){if(typeof re=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return ee(le)}return X(le,re,ae)}J.poolSize=8192;function X(le,re,ae){if(typeof le=="string")return te(le,re);if(ArrayBuffer.isView(le))return ie(le);if(le==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof le);if(At(le,ArrayBuffer)||le&&At(le.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(At(le,SharedArrayBuffer)||le&&At(le.buffer,SharedArrayBuffer)))return oe(le,re,ae);if(typeof le=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const he=le.valueOf&&le.valueOf();if(he!=null&&he!==le)return J.from(he,re,ae);const we=ce(le);if(we)return we;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof le[Symbol.toPrimitive]=="function")return J.from(le[Symbol.toPrimitive]("string"),re,ae);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof le)}J.from=function(le,re,ae){return X(le,re,ae)},Object.setPrototypeOf(J.prototype,Uint8Array.prototype),Object.setPrototypeOf(J,Uint8Array);function Z(le){if(typeof le!="number")throw new TypeError('"size" argument must be of type number');if(le<0)throw new RangeError('The value "'+le+'" is invalid for option "size"')}function Q(le,re,ae){return Z(le),le<=0?Y(le):re!==void 0?typeof ae=="string"?Y(le).fill(re,ae):Y(le).fill(re):Y(le)}J.alloc=function(le,re,ae){return Q(le,re,ae)};function ee(le){return Z(le),Y(le<0?0:fe(le)|0)}J.allocUnsafe=function(le){return ee(le)},J.allocUnsafeSlow=function(le){return ee(le)};function te(le,re){if((typeof re!="string"||re==="")&&(re="utf8"),!J.isEncoding(re))throw new TypeError("Unknown encoding: "+re);const ae=de(le,re)|0;let he=Y(ae);const we=he.write(le,re);return we!==ae&&(he=he.slice(0,we)),he}function ne(le){const re=le.length<0?0:fe(le.length)|0,ae=Y(re);for(let he=0;he<re;he+=1)ae[he]=le[he]&255;return ae}function ie(le){if(At(le,Uint8Array)){const re=new Uint8Array(le);return oe(re.buffer,re.byteOffset,re.byteLength)}return ne(le)}function oe(le,re,ae){if(re<0||le.byteLength<re)throw new RangeError('"offset" is outside of buffer bounds');if(le.byteLength<re+(ae||0))throw new RangeError('"length" is outside of buffer bounds');let he;return re===void 0&&ae===void 0?he=new Uint8Array(le):ae===void 0?he=new Uint8Array(le,re):he=new Uint8Array(le,re,ae),Object.setPrototypeOf(he,J.prototype),he}function ce(le){if(J.isBuffer(le)){const re=fe(le.length)|0,ae=Y(re);return ae.length===0||le.copy(ae,0,0,re),ae}if(le.length!==void 0)return typeof le.length!="number"||zt(le.length)?Y(0):ne(le);if(le.type==="Buffer"&&Array.isArray(le.data))return ne(le.data)}function fe(le){if(le>=G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");return le|0}function se(le){return+le!=le&&(le=0),J.alloc(+le)}J.isBuffer=function(re){return re!=null&&re._isBuffer===!0&&re!==J.prototype},J.compare=function(re,ae){if(At(re,Uint8Array)&&(re=J.from(re,re.offset,re.byteLength)),At(ae,Uint8Array)&&(ae=J.from(ae,ae.offset,ae.byteLength)),!J.isBuffer(re)||!J.isBuffer(ae))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(re===ae)return 0;let he=re.length,we=ae.length;for(let Ee=0,Le=Math.min(he,we);Ee<Le;++Ee)if(re[Ee]!==ae[Ee]){he=re[Ee],we=ae[Ee];break}return he<we?-1:we<he?1:0},J.isEncoding=function(re){switch(String(re).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},J.concat=function(re,ae){if(!Array.isArray(re))throw new TypeError('"list" argument must be an Array of Buffers');if(re.length===0)return J.alloc(0);let he;if(ae===void 0)for(ae=0,he=0;he<re.length;++he)ae+=re[he].length;const we=J.allocUnsafe(ae);let Ee=0;for(he=0;he<re.length;++he){let Le=re[he];if(At(Le,Uint8Array))Ee+Le.length>we.length?(J.isBuffer(Le)||(Le=J.from(Le)),Le.copy(we,Ee)):Uint8Array.prototype.set.call(we,Le,Ee);else if(J.isBuffer(Le))Le.copy(we,Ee);else throw new TypeError('"list" argument must be an Array of Buffers');Ee+=Le.length}return we};function de(le,re){if(J.isBuffer(le))return le.length;if(ArrayBuffer.isView(le)||At(le,ArrayBuffer))return le.byteLength;if(typeof le!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof le);const ae=le.length,he=arguments.length>2&&arguments[2]===!0;if(!he&&ae===0)return 0;let we=!1;for(;;)switch(re){case"ascii":case"latin1":case"binary":return ae;case"utf8":case"utf-8":return $t(le).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ae*2;case"hex":return ae>>>1;case"base64":return jt(le).length;default:if(we)return he?-1:$t(le).length;re=(""+re).toLowerCase(),we=!0}}J.byteLength=de;function ue(le,re,ae){let he=!1;if((re===void 0||re<0)&&(re=0),re>this.length||((ae===void 0||ae>this.length)&&(ae=this.length),ae<=0)||(ae>>>=0,re>>>=0,ae<=re))return"";for(le||(le="utf8");;)switch(le){case"hex":return it(this,re,ae);case"utf8":case"utf-8":return Be(this,re,ae);case"ascii":return ot(this,re,ae);case"latin1":case"binary":return ft(this,re,ae);case"base64":return De(this,re,ae);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ut(this,re,ae);default:if(he)throw new TypeError("Unknown encoding: "+le);le=(le+"").toLowerCase(),he=!0}}J.prototype._isBuffer=!0;function pe(le,re,ae){const he=le[re];le[re]=le[ae],le[ae]=he}J.prototype.swap16=function(){const re=this.length;if(re%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let ae=0;ae<re;ae+=2)pe(this,ae,ae+1);return this},J.prototype.swap32=function(){const re=this.length;if(re%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let ae=0;ae<re;ae+=4)pe(this,ae,ae+3),pe(this,ae+1,ae+2);return this},J.prototype.swap64=function(){const re=this.length;if(re%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let ae=0;ae<re;ae+=8)pe(this,ae,ae+7),pe(this,ae+1,ae+6),pe(this,ae+2,ae+5),pe(this,ae+3,ae+4);return this},J.prototype.toString=function(){const re=this.length;return re===0?"":arguments.length===0?Be(this,0,re):ue.apply(this,arguments)},J.prototype.toLocaleString=J.prototype.toString,J.prototype.equals=function(re){if(!J.isBuffer(re))throw new TypeError("Argument must be a Buffer");return this===re?!0:J.compare(this,re)===0},J.prototype.inspect=function(){let re="";const ae=$.INSPECT_MAX_BYTES;return re=this.toString("hex",0,ae).replace(/(.{2})/g,"$1 ").trim(),this.length>ae&&(re+=" ... "),"<Buffer "+re+">"},q&&(J.prototype[q]=J.prototype.inspect),J.prototype.compare=function(re,ae,he,we,Ee){if(At(re,Uint8Array)&&(re=J.from(re,re.offset,re.byteLength)),!J.isBuffer(re))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof re);if(ae===void 0&&(ae=0),he===void 0&&(he=re?re.length:0),we===void 0&&(we=0),Ee===void 0&&(Ee=this.length),ae<0||he>re.length||we<0||Ee>this.length)throw new RangeError("out of range index");if(we>=Ee&&ae>=he)return 0;if(we>=Ee)return-1;if(ae>=he)return 1;if(ae>>>=0,he>>>=0,we>>>=0,Ee>>>=0,this===re)return 0;let Le=Ee-we,bt=he-ae;const Lt=Math.min(Le,bt),Ct=this.slice(we,Ee),It=re.slice(ae,he);for(let Tt=0;Tt<Lt;++Tt)if(Ct[Tt]!==It[Tt]){Le=Ct[Tt],bt=It[Tt];break}return Le<bt?-1:bt<Le?1:0};function ve(le,re,ae,he,we){if(le.length===0)return-1;if(typeof ae=="string"?(he=ae,ae=0):ae>2147483647?ae=2147483647:ae<-2147483648&&(ae=-2147483648),ae=+ae,zt(ae)&&(ae=we?0:le.length-1),ae<0&&(ae=le.length+ae),ae>=le.length){if(we)return-1;ae=le.length-1}else if(ae<0)if(we)ae=0;else return-1;if(typeof re=="string"&&(re=J.from(re,he)),J.isBuffer(re))return re.length===0?-1:me(le,re,ae,he,we);if(typeof re=="number")return re=re&255,typeof Uint8Array.prototype.indexOf=="function"?we?Uint8Array.prototype.indexOf.call(le,re,ae):Uint8Array.prototype.lastIndexOf.call(le,re,ae):me(le,[re],ae,he,we);throw new TypeError("val must be string, number or Buffer")}function me(le,re,ae,he,we){let Ee=1,Le=le.length,bt=re.length;if(he!==void 0&&(he=String(he).toLowerCase(),he==="ucs2"||he==="ucs-2"||he==="utf16le"||he==="utf-16le")){if(le.length<2||re.length<2)return-1;Ee=2,Le/=2,bt/=2,ae/=2}function Lt(It,Tt){return Ee===1?It[Tt]:It.readUInt16BE(Tt*Ee)}let Ct;if(we){let It=-1;for(Ct=ae;Ct<Le;Ct++)if(Lt(le,Ct)===Lt(re,It===-1?0:Ct-It)){if(It===-1&&(It=Ct),Ct-It+1===bt)return It*Ee}else It!==-1&&(Ct-=Ct-It),It=-1}else for(ae+bt>Le&&(ae=Le-bt),Ct=ae;Ct>=0;Ct--){let It=!0;for(let Tt=0;Tt<bt;Tt++)if(Lt(le,Ct+Tt)!==Lt(re,Tt)){It=!1;break}if(It)return Ct}return-1}J.prototype.includes=function(re,ae,he){return this.indexOf(re,ae,he)!==-1},J.prototype.indexOf=function(re,ae,he){return ve(this,re,ae,he,!0)},J.prototype.lastIndexOf=function(re,ae,he){return ve(this,re,ae,he,!1)};function be(le,re,ae,he){ae=Number(ae)||0;const we=le.length-ae;he?(he=Number(he),he>we&&(he=we)):he=we;const Ee=re.length;he>Ee/2&&(he=Ee/2);let Le;for(Le=0;Le<he;++Le){const bt=parseInt(re.substr(Le*2,2),16);if(zt(bt))return Le;le[ae+Le]=bt}return Le}function _e(le,re,ae,he){return Gt($t(re,le.length-ae),le,ae,he)}function Se(le,re,ae,he){return Gt(Et(re),le,ae,he)}function xe(le,re,ae,he){return Gt(jt(re),le,ae,he)}function ke(le,re,ae,he){return Gt(rt(re,le.length-ae),le,ae,he)}J.prototype.write=function(re,ae,he,we){if(ae===void 0)we="utf8",he=this.length,ae=0;else if(he===void 0&&typeof ae=="string")we=ae,he=this.length,ae=0;else if(isFinite(ae))ae=ae>>>0,isFinite(he)?(he=he>>>0,we===void 0&&(we="utf8")):(we=he,he=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const Ee=this.length-ae;if((he===void 0||he>Ee)&&(he=Ee),re.length>0&&(he<0||ae<0)||ae>this.length)throw new RangeError("Attempt to write outside buffer bounds");we||(we="utf8");let Le=!1;for(;;)switch(we){case"hex":return be(this,re,ae,he);case"utf8":case"utf-8":return _e(this,re,ae,he);case"ascii":case"latin1":case"binary":return Se(this,re,ae,he);case"base64":return xe(this,re,ae,he);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ke(this,re,ae,he);default:if(Le)throw new TypeError("Unknown encoding: "+we);we=(""+we).toLowerCase(),Le=!0}},J.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function De(le,re,ae){return re===0&&ae===le.length?I.fromByteArray(le):I.fromByteArray(le.slice(re,ae))}function Be(le,re,ae){ae=Math.min(le.length,ae);const he=[];let we=re;for(;we<ae;){const Ee=le[we];let Le=null,bt=Ee>239?4:Ee>223?3:Ee>191?2:1;if(we+bt<=ae){let Lt,Ct,It,Tt;switch(bt){case 1:Ee<128&&(Le=Ee);break;case 2:Lt=le[we+1],(Lt&192)===128&&(Tt=(Ee&31)<<6|Lt&63,Tt>127&&(Le=Tt));break;case 3:Lt=le[we+1],Ct=le[we+2],(Lt&192)===128&&(Ct&192)===128&&(Tt=(Ee&15)<<12|(Lt&63)<<6|Ct&63,Tt>2047&&(Tt<55296||Tt>57343)&&(Le=Tt));break;case 4:Lt=le[we+1],Ct=le[we+2],It=le[we+3],(Lt&192)===128&&(Ct&192)===128&&(It&192)===128&&(Tt=(Ee&15)<<18|(Lt&63)<<12|(Ct&63)<<6|It&63,Tt>65535&&Tt<1114112&&(Le=Tt))}}Le===null?(Le=65533,bt=1):Le>65535&&(Le-=65536,he.push(Le>>>10&1023|55296),Le=56320|Le&1023),he.push(Le),we+=bt}return nt(he)}const Ve=4096;function nt(le){const re=le.length;if(re<=Ve)return String.fromCharCode.apply(String,le);let ae="",he=0;for(;he<re;)ae+=String.fromCharCode.apply(String,le.slice(he,he+=Ve));return ae}function ot(le,re,ae){let he="";ae=Math.min(le.length,ae);for(let we=re;we<ae;++we)he+=String.fromCharCode(le[we]&127);return he}function ft(le,re,ae){let he="";ae=Math.min(le.length,ae);for(let we=re;we<ae;++we)he+=String.fromCharCode(le[we]);return he}function it(le,re,ae){const he=le.length;(!re||re<0)&&(re=0),(!ae||ae<0||ae>he)&&(ae=he);let we="";for(let Ee=re;Ee<ae;++Ee)we+=nn[le[Ee]];return we}function ut(le,re,ae){const he=le.slice(re,ae);let we="";for(let Ee=0;Ee<he.length-1;Ee+=2)we+=String.fromCharCode(he[Ee]+he[Ee+1]*256);return we}J.prototype.slice=function(re,ae){const he=this.length;re=~~re,ae=ae===void 0?he:~~ae,re<0?(re+=he,re<0&&(re=0)):re>he&&(re=he),ae<0?(ae+=he,ae<0&&(ae=0)):ae>he&&(ae=he),ae<re&&(ae=re);const we=this.subarray(re,ae);return Object.setPrototypeOf(we,J.prototype),we};function et(le,re,ae){if(le%1!==0||le<0)throw new RangeError("offset is not uint");if(le+re>ae)throw new RangeError("Trying to access beyond buffer length")}J.prototype.readUintLE=J.prototype.readUIntLE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re],Ee=1,Le=0;for(;++Le<ae&&(Ee*=256);)we+=this[re+Le]*Ee;return we},J.prototype.readUintBE=J.prototype.readUIntBE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re+--ae],Ee=1;for(;ae>0&&(Ee*=256);)we+=this[re+--ae]*Ee;return we},J.prototype.readUint8=J.prototype.readUInt8=function(re,ae){return re=re>>>0,ae||et(re,1,this.length),this[re]},J.prototype.readUint16LE=J.prototype.readUInt16LE=function(re,ae){return re=re>>>0,ae||et(re,2,this.length),this[re]|this[re+1]<<8},J.prototype.readUint16BE=J.prototype.readUInt16BE=function(re,ae){return re=re>>>0,ae||et(re,2,this.length),this[re]<<8|this[re+1]},J.prototype.readUint32LE=J.prototype.readUInt32LE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),(this[re]|this[re+1]<<8|this[re+2]<<16)+this[re+3]*16777216},J.prototype.readUint32BE=J.prototype.readUInt32BE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]*16777216+(this[re+1]<<16|this[re+2]<<8|this[re+3])},J.prototype.readBigUInt64LE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=ae+this[++re]*2**8+this[++re]*2**16+this[++re]*2**24,Ee=this[++re]+this[++re]*2**8+this[++re]*2**16+he*2**24;return BigInt(we)+(BigInt(Ee)<<BigInt(32))}),J.prototype.readBigUInt64BE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=ae*2**24+this[++re]*2**16+this[++re]*2**8+this[++re],Ee=this[++re]*2**24+this[++re]*2**16+this[++re]*2**8+he;return(BigInt(we)<<BigInt(32))+BigInt(Ee)}),J.prototype.readIntLE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=this[re],Ee=1,Le=0;for(;++Le<ae&&(Ee*=256);)we+=this[re+Le]*Ee;return Ee*=128,we>=Ee&&(we-=Math.pow(2,8*ae)),we},J.prototype.readIntBE=function(re,ae,he){re=re>>>0,ae=ae>>>0,he||et(re,ae,this.length);let we=ae,Ee=1,Le=this[re+--we];for(;we>0&&(Ee*=256);)Le+=this[re+--we]*Ee;return Ee*=128,Le>=Ee&&(Le-=Math.pow(2,8*ae)),Le},J.prototype.readInt8=function(re,ae){return re=re>>>0,ae||et(re,1,this.length),this[re]&128?(255-this[re]+1)*-1:this[re]},J.prototype.readInt16LE=function(re,ae){re=re>>>0,ae||et(re,2,this.length);const he=this[re]|this[re+1]<<8;return he&32768?he|4294901760:he},J.prototype.readInt16BE=function(re,ae){re=re>>>0,ae||et(re,2,this.length);const he=this[re+1]|this[re]<<8;return he&32768?he|4294901760:he},J.prototype.readInt32LE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]|this[re+1]<<8|this[re+2]<<16|this[re+3]<<24},J.prototype.readInt32BE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),this[re]<<24|this[re+1]<<16|this[re+2]<<8|this[re+3]},J.prototype.readBigInt64LE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=this[re+4]+this[re+5]*2**8+this[re+6]*2**16+(he<<24);return(BigInt(we)<<BigInt(32))+BigInt(ae+this[++re]*2**8+this[++re]*2**16+this[++re]*2**24)}),J.prototype.readBigInt64BE=St(function(re){re=re>>>0,Me(re,"offset");const ae=this[re],he=this[re+7];(ae===void 0||he===void 0)&&Ke(re,this.length-8);const we=(ae<<24)+this[++re]*2**16+this[++re]*2**8+this[++re];return(BigInt(we)<<BigInt(32))+BigInt(this[++re]*2**24+this[++re]*2**16+this[++re]*2**8+he)}),J.prototype.readFloatLE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),U.read(this,re,!0,23,4)},J.prototype.readFloatBE=function(re,ae){return re=re>>>0,ae||et(re,4,this.length),U.read(this,re,!1,23,4)},J.prototype.readDoubleLE=function(re,ae){return re=re>>>0,ae||et(re,8,this.length),U.read(this,re,!0,52,8)},J.prototype.readDoubleBE=function(re,ae){return re=re>>>0,ae||et(re,8,this.length),U.read(this,re,!1,52,8)};function Ue(le,re,ae,he,we,Ee){if(!J.isBuffer(le))throw new TypeError('"buffer" argument must be a Buffer instance');if(re>we||re<Ee)throw new RangeError('"value" argument is out of bounds');if(ae+he>le.length)throw new RangeError("Index out of range")}J.prototype.writeUintLE=J.prototype.writeUIntLE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,he=he>>>0,!we){const bt=Math.pow(2,8*he)-1;Ue(this,re,ae,he,bt,0)}let Ee=1,Le=0;for(this[ae]=re&255;++Le<he&&(Ee*=256);)this[ae+Le]=re/Ee&255;return ae+he},J.prototype.writeUintBE=J.prototype.writeUIntBE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,he=he>>>0,!we){const bt=Math.pow(2,8*he)-1;Ue(this,re,ae,he,bt,0)}let Ee=he-1,Le=1;for(this[ae+Ee]=re&255;--Ee>=0&&(Le*=256);)this[ae+Ee]=re/Le&255;return ae+he},J.prototype.writeUint8=J.prototype.writeUInt8=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,1,255,0),this[ae]=re&255,ae+1},J.prototype.writeUint16LE=J.prototype.writeUInt16LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,65535,0),this[ae]=re&255,this[ae+1]=re>>>8,ae+2},J.prototype.writeUint16BE=J.prototype.writeUInt16BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,65535,0),this[ae]=re>>>8,this[ae+1]=re&255,ae+2},J.prototype.writeUint32LE=J.prototype.writeUInt32LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,4294967295,0),this[ae+3]=re>>>24,this[ae+2]=re>>>16,this[ae+1]=re>>>8,this[ae]=re&255,ae+4},J.prototype.writeUint32BE=J.prototype.writeUInt32BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,4294967295,0),this[ae]=re>>>24,this[ae+1]=re>>>16,this[ae+2]=re>>>8,this[ae+3]=re&255,ae+4};function We(le,re,ae,he,we){ye(re,he,we,le,ae,7);let Ee=Number(re&BigInt(4294967295));le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee,Ee=Ee>>8,le[ae++]=Ee;let Le=Number(re>>BigInt(32)&BigInt(4294967295));return le[ae++]=Le,Le=Le>>8,le[ae++]=Le,Le=Le>>8,le[ae++]=Le,Le=Le>>8,le[ae++]=Le,ae}function tt(le,re,ae,he,we){ye(re,he,we,le,ae,7);let Ee=Number(re&BigInt(4294967295));le[ae+7]=Ee,Ee=Ee>>8,le[ae+6]=Ee,Ee=Ee>>8,le[ae+5]=Ee,Ee=Ee>>8,le[ae+4]=Ee;let Le=Number(re>>BigInt(32)&BigInt(4294967295));return le[ae+3]=Le,Le=Le>>8,le[ae+2]=Le,Le=Le>>8,le[ae+1]=Le,Le=Le>>8,le[ae]=Le,ae+8}J.prototype.writeBigUInt64LE=St(function(re,ae=0){return We(this,re,ae,BigInt(0),BigInt("0xffffffffffffffff"))}),J.prototype.writeBigUInt64BE=St(function(re,ae=0){return tt(this,re,ae,BigInt(0),BigInt("0xffffffffffffffff"))}),J.prototype.writeIntLE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,!we){const Lt=Math.pow(2,8*he-1);Ue(this,re,ae,he,Lt-1,-Lt)}let Ee=0,Le=1,bt=0;for(this[ae]=re&255;++Ee<he&&(Le*=256);)re<0&&bt===0&&this[ae+Ee-1]!==0&&(bt=1),this[ae+Ee]=(re/Le>>0)-bt&255;return ae+he},J.prototype.writeIntBE=function(re,ae,he,we){if(re=+re,ae=ae>>>0,!we){const Lt=Math.pow(2,8*he-1);Ue(this,re,ae,he,Lt-1,-Lt)}let Ee=he-1,Le=1,bt=0;for(this[ae+Ee]=re&255;--Ee>=0&&(Le*=256);)re<0&&bt===0&&this[ae+Ee+1]!==0&&(bt=1),this[ae+Ee]=(re/Le>>0)-bt&255;return ae+he},J.prototype.writeInt8=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,1,127,-128),re<0&&(re=255+re+1),this[ae]=re&255,ae+1},J.prototype.writeInt16LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,32767,-32768),this[ae]=re&255,this[ae+1]=re>>>8,ae+2},J.prototype.writeInt16BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,2,32767,-32768),this[ae]=re>>>8,this[ae+1]=re&255,ae+2},J.prototype.writeInt32LE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,2147483647,-2147483648),this[ae]=re&255,this[ae+1]=re>>>8,this[ae+2]=re>>>16,this[ae+3]=re>>>24,ae+4},J.prototype.writeInt32BE=function(re,ae,he){return re=+re,ae=ae>>>0,he||Ue(this,re,ae,4,2147483647,-2147483648),re<0&&(re=4294967295+re+1),this[ae]=re>>>24,this[ae+1]=re>>>16,this[ae+2]=re>>>8,this[ae+3]=re&255,ae+4},J.prototype.writeBigInt64LE=St(function(re,ae=0){return We(this,re,ae,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),J.prototype.writeBigInt64BE=St(function(re,ae=0){return tt(this,re,ae,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function vt(le,re,ae,he,we,Ee){if(ae+he>le.length)throw new RangeError("Index out of range");if(ae<0)throw new RangeError("Index out of range")}function je(le,re,ae,he,we){return re=+re,ae=ae>>>0,we||vt(le,re,ae,4),U.write(le,re,ae,he,23,4),ae+4}J.prototype.writeFloatLE=function(re,ae,he){return je(this,re,ae,!0,he)},J.prototype.writeFloatBE=function(re,ae,he){return je(this,re,ae,!1,he)};function ze(le,re,ae,he,we){return re=+re,ae=ae>>>0,we||vt(le,re,ae,8),U.write(le,re,ae,he,52,8),ae+8}J.prototype.writeDoubleLE=function(re,ae,he){return ze(this,re,ae,!0,he)},J.prototype.writeDoubleBE=function(re,ae,he){return ze(this,re,ae,!1,he)},J.prototype.copy=function(re,ae,he,we){if(!J.isBuffer(re))throw new TypeError("argument should be a Buffer");if(he||(he=0),!we&&we!==0&&(we=this.length),ae>=re.length&&(ae=re.length),ae||(ae=0),we>0&&we<he&&(we=he),we===he||re.length===0||this.length===0)return 0;if(ae<0)throw new RangeError("targetStart out of bounds");if(he<0||he>=this.length)throw new RangeError("Index out of range");if(we<0)throw new RangeError("sourceEnd out of bounds");we>this.length&&(we=this.length),re.length-ae<we-he&&(we=re.length-ae+he);const Ee=we-he;return this===re&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(ae,he,we):Uint8Array.prototype.set.call(re,this.subarray(he,we),ae),Ee},J.prototype.fill=function(re,ae,he,we){if(typeof re=="string"){if(typeof ae=="string"?(we=ae,ae=0,he=this.length):typeof he=="string"&&(we=he,he=this.length),we!==void 0&&typeof we!="string")throw new TypeError("encoding must be a string");if(typeof we=="string"&&!J.isEncoding(we))throw new TypeError("Unknown encoding: "+we);if(re.length===1){const Le=re.charCodeAt(0);(we==="utf8"&&Le<128||we==="latin1")&&(re=Le)}}else typeof re=="number"?re=re&255:typeof re=="boolean"&&(re=Number(re));if(ae<0||this.length<ae||this.length<he)throw new RangeError("Out of range index");if(he<=ae)return this;ae=ae>>>0,he=he===void 0?this.length:he>>>0,re||(re=0);let Ee;if(typeof re=="number")for(Ee=ae;Ee<he;++Ee)this[Ee]=re;else{const Le=J.isBuffer(re)?re:J.from(re,we),bt=Le.length;if(bt===0)throw new TypeError('The value "'+re+'" is invalid for argument "value"');for(Ee=0;Ee<he-ae;++Ee)this[Ee+ae]=Le[Ee%bt]}return this};const Ae={};function Re(le,re,ae){Ae[le]=class extends ae{constructor(){super(),Object.defineProperty(this,"message",{value:re.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${le}]`,this.stack,delete this.name}get code(){return le}set code(we){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:we,writable:!0})}toString(){return`${this.name} [${le}]: ${this.message}`}}}Re("ERR_BUFFER_OUT_OF_BOUNDS",function(le){return le?`${le} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Re("ERR_INVALID_ARG_TYPE",function(le,re){return`The "${le}" argument must be of type number. Received type ${typeof re}`},TypeError),Re("ERR_OUT_OF_RANGE",function(le,re,ae){let he=`The value of "${le}" is out of range.`,we=ae;return Number.isInteger(ae)&&Math.abs(ae)>2**32?we=Ce(String(ae)):typeof ae=="bigint"&&(we=String(ae),(ae>BigInt(2)**BigInt(32)||ae<-(BigInt(2)**BigInt(32)))&&(we=Ce(we)),we+="n"),he+=` It must be ${re}. Received ${we}`,he},RangeError);function Ce(le){let re="",ae=le.length;const he=le[0]==="-"?1:0;for(;ae>=he+4;ae-=3)re=`_${le.slice(ae-3,ae)}${re}`;return`${le.slice(0,ae)}${re}`}function ge(le,re,ae){Me(re,"offset"),(le[re]===void 0||le[re+ae]===void 0)&&Ke(re,le.length-(ae+1))}function ye(le,re,ae,he,we,Ee){if(le>ae||le<re){const Le=typeof re=="bigint"?"n":"";let bt;throw Ee>3?re===0||re===BigInt(0)?bt=`>= 0${Le} and < 2${Le} ** ${(Ee+1)*8}${Le}`:bt=`>= -(2${Le} ** ${(Ee+1)*8-1}${Le}) and < 2 ** ${(Ee+1)*8-1}${Le}`:bt=`>= ${re}${Le} and <= ${ae}${Le}`,new Ae.ERR_OUT_OF_RANGE("value",bt,le)}ge(he,we,Ee)}function Me(le,re){if(typeof le!="number")throw new Ae.ERR_INVALID_ARG_TYPE(re,"number",le)}function Ke(le,re,ae){throw Math.floor(le)!==le?(Me(le,ae),new Ae.ERR_OUT_OF_RANGE(ae||"offset","an integer",le)):re<0?new Ae.ERR_BUFFER_OUT_OF_BOUNDS:new Ae.ERR_OUT_OF_RANGE(ae||"offset",`>= ${ae?1:0} and <= ${re}`,le)}const st=/[^+/0-9A-Za-z-_]/g;function dt(le){if(le=le.split("=")[0],le=le.trim().replace(st,""),le.length<2)return"";for(;le.length%4!==0;)le=le+"=";return le}function $t(le,re){re=re||1/0;let ae;const he=le.length;let we=null;const Ee=[];for(let Le=0;Le<he;++Le){if(ae=le.charCodeAt(Le),ae>55295&&ae<57344){if(!we){if(ae>56319){(re-=3)>-1&&Ee.push(239,191,189);continue}else if(Le+1===he){(re-=3)>-1&&Ee.push(239,191,189);continue}we=ae;continue}if(ae<56320){(re-=3)>-1&&Ee.push(239,191,189),we=ae;continue}ae=(we-55296<<10|ae-56320)+65536}else we&&(re-=3)>-1&&Ee.push(239,191,189);if(we=null,ae<128){if((re-=1)<0)break;Ee.push(ae)}else if(ae<2048){if((re-=2)<0)break;Ee.push(ae>>6|192,ae&63|128)}else if(ae<65536){if((re-=3)<0)break;Ee.push(ae>>12|224,ae>>6&63|128,ae&63|128)}else if(ae<1114112){if((re-=4)<0)break;Ee.push(ae>>18|240,ae>>12&63|128,ae>>6&63|128,ae&63|128)}else throw new Error("Invalid code point")}return Ee}function Et(le){const re=[];for(let ae=0;ae<le.length;++ae)re.push(le.charCodeAt(ae)&255);return re}function rt(le,re){let ae,he,we;const Ee=[];for(let Le=0;Le<le.length&&!((re-=2)<0);++Le)ae=le.charCodeAt(Le),he=ae>>8,we=ae%256,Ee.push(we),Ee.push(he);return Ee}function jt(le){return I.toByteArray(dt(le))}function Gt(le,re,ae,he){let we;for(we=0;we<he&&!(we+ae>=re.length||we>=le.length);++we)re[we+ae]=le[we];return we}function At(le,re){return le instanceof re||le!=null&&le.constructor!=null&&le.constructor.name!=null&&le.constructor.name===re.name}function zt(le){return le!==le}const nn=function(){const le="0123456789abcdef",re=new Array(256);for(let ae=0;ae<16;++ae){const he=ae*16;for(let we=0;we<16;++we)re[he+we]=le[ae]+le[we]}return re}();function St(le){return typeof BigInt>"u"?Ut:le}function Ut(){throw new Error("BigInt not supported")}})(buffer);const __viteBrowserExternal={},__viteBrowserExternal$1=Object.freeze(Object.defineProperty({__proto__:null,default:__viteBrowserExternal},Symbol.toStringTag,{value:"Module"})),require$$3=getAugmentedNamespace(__viteBrowserExternal$1);var buffer_list,hasRequiredBuffer_list;function requireBuffer_list(){if(hasRequiredBuffer_list)return buffer_list;hasRequiredBuffer_list=1;function $(te,ne){var ie=Object.keys(te);if(Object.getOwnPropertySymbols){var oe=Object.getOwnPropertySymbols(te);ne&&(oe=oe.filter(function(ce){return Object.getOwnPropertyDescriptor(te,ce).enumerable})),ie.push.apply(ie,oe)}return ie}function I(te){for(var ne=1;ne<arguments.length;ne++){var ie=arguments[ne]!=null?arguments[ne]:{};ne%2?$(Object(ie),!0).forEach(function(oe){U(te,oe,ie[oe])}):Object.getOwnPropertyDescriptors?Object.defineProperties(te,Object.getOwnPropertyDescriptors(ie)):$(Object(ie)).forEach(function(oe){Object.defineProperty(te,oe,Object.getOwnPropertyDescriptor(ie,oe))})}return te}function U(te,ne,ie){return ne in te?Object.defineProperty(te,ne,{value:ie,enumerable:!0,configurable:!0,writable:!0}):te[ne]=ie,te}function q(te,ne){if(!(te instanceof ne))throw new TypeError("Cannot call a class as a function")}function G(te,ne){for(var ie=0;ie<ne.length;ie++){var oe=ne[ie];oe.enumerable=oe.enumerable||!1,oe.configurable=!0,"value"in oe&&(oe.writable=!0),Object.defineProperty(te,oe.key,oe)}}function K(te,ne,ie){return ne&&G(te.prototype,ne),ie&&G(te,ie),te}var Y=buffer,J=Y.Buffer,X=require$$3,Z=X.inspect,Q=Z&&Z.custom||"inspect";function ee(te,ne,ie){J.prototype.copy.call(te,ne,ie)}return buffer_list=function(){function te(){q(this,te),this.head=null,this.tail=null,this.length=0}return K(te,[{key:"push",value:function(ie){var oe={data:ie,next:null};this.length>0?this.tail.next=oe:this.head=oe,this.tail=oe,++this.length}},{key:"unshift",value:function(ie){var oe={data:ie,next:this.head};this.length===0&&(this.tail=oe),this.head=oe,++this.length}},{key:"shift",value:function(){if(this.length!==0){var ie=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,ie}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(ie){if(this.length===0)return"";for(var oe=this.head,ce=""+oe.data;oe=oe.next;)ce+=ie+oe.data;return ce}},{key:"concat",value:function(ie){if(this.length===0)return J.alloc(0);for(var oe=J.allocUnsafe(ie>>>0),ce=this.head,fe=0;ce;)ee(ce.data,oe,fe),fe+=ce.data.length,ce=ce.next;return oe}},{key:"consume",value:function(ie,oe){var ce;return ie<this.head.data.length?(ce=this.head.data.slice(0,ie),this.head.data=this.head.data.slice(ie)):ie===this.head.data.length?ce=this.shift():ce=oe?this._getString(ie):this._getBuffer(ie),ce}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(ie){var oe=this.head,ce=1,fe=oe.data;for(ie-=fe.length;oe=oe.next;){var se=oe.data,de=ie>se.length?se.length:ie;if(de===se.length?fe+=se:fe+=se.slice(0,ie),ie-=de,ie===0){de===se.length?(++ce,oe.next?this.head=oe.next:this.head=this.tail=null):(this.head=oe,oe.data=se.slice(de));break}++ce}return this.length-=ce,fe}},{key:"_getBuffer",value:function(ie){var oe=J.allocUnsafe(ie),ce=this.head,fe=1;for(ce.data.copy(oe),ie-=ce.data.length;ce=ce.next;){var se=ce.data,de=ie>se.length?se.length:ie;if(se.copy(oe,oe.length-ie,0,de),ie-=de,ie===0){de===se.length?(++fe,ce.next?this.head=ce.next:this.head=this.tail=null):(this.head=ce,ce.data=se.slice(de));break}++fe}return this.length-=fe,oe}},{key:Q,value:function(ie,oe){return Z(this,I({},oe,{depth:0,customInspect:!1}))}}]),te}(),buffer_list}function destroy($,I){var U=this,q=this._readableState&&this._readableState.destroyed,G=this._writableState&&this._writableState.destroyed;return q||G?(I?I($):$&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(emitErrorNT,this,$)):process.nextTick(emitErrorNT,this,$)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy($||null,function(K){!I&&K?U._writableState?U._writableState.errorEmitted?process.nextTick(emitCloseNT,U):(U._writableState.errorEmitted=!0,process.nextTick(emitErrorAndCloseNT,U,K)):process.nextTick(emitErrorAndCloseNT,U,K):I?(process.nextTick(emitCloseNT,U),I(K)):process.nextTick(emitCloseNT,U)}),this)}function emitErrorAndCloseNT($,I){emitErrorNT($,I),emitCloseNT($)}function emitCloseNT($){$._writableState&&!$._writableState.emitClose||$._readableState&&!$._readableState.emitClose||$.emit("close")}function undestroy(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function emitErrorNT($,I){$.emit("error",I)}function errorOrDestroy($,I){var U=$._readableState,q=$._writableState;U&&U.autoDestroy||q&&q.autoDestroy?$.destroy(I):$.emit("error",I)}var destroy_1={destroy,undestroy,errorOrDestroy},errorsBrowser={};function _inheritsLoose($,I){$.prototype=Object.create(I.prototype),$.prototype.constructor=$,$.__proto__=I}var codes={};function createErrorType($,I,U){U||(U=Error);function q(K,Y,J){return typeof I=="string"?I:I(K,Y,J)}var G=function(K){_inheritsLoose(Y,K);function Y(J,X,Z){return K.call(this,q(J,X,Z))||this}return Y}(U);G.prototype.name=U.name,G.prototype.code=$,codes[$]=G}function oneOf($,I){if(Array.isArray($)){var U=$.length;return $=$.map(function(q){return String(q)}),U>2?"one of ".concat(I," ").concat($.slice(0,U-1).join(", "),", or ")+$[U-1]:U===2?"one of ".concat(I," ").concat($[0]," or ").concat($[1]):"of ".concat(I," ").concat($[0])}else return"of ".concat(I," ").concat(String($))}function startsWith($,I,U){return $.substr(!U||U<0?0:+U,I.length)===I}function endsWith($,I,U){return(U===void 0||U>$.length)&&(U=$.length),$.substring(U-I.length,U)===I}function includes($,I,U){return typeof U!="number"&&(U=0),U+I.length>$.length?!1:$.indexOf(I,U)!==-1}createErrorType("ERR_INVALID_OPT_VALUE",function($,I){return'The value "'+I+'" is invalid for option "'+$+'"'},TypeError),createErrorType("ERR_INVALID_ARG_TYPE",function($,I,U){var q;typeof I=="string"&&startsWith(I,"not ")?(q="must not be",I=I.replace(/^not /,"")):q="must be";var G;if(endsWith($," argument"))G="The ".concat($," ").concat(q," ").concat(oneOf(I,"type"));else{var K=includes($,".")?"property":"argument";G='The "'.concat($,'" ').concat(K," ").concat(q," ").concat(oneOf(I,"type"))}return G+=". Received type ".concat(typeof U),G},TypeError),createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),createErrorType("ERR_METHOD_NOT_IMPLEMENTED",function($){return"The "+$+" method is not implemented"}),createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close"),createErrorType("ERR_STREAM_DESTROYED",function($){return"Cannot call "+$+" after a stream was destroyed"}),createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),createErrorType("ERR_UNKNOWN_ENCODING",function($){return"Unknown encoding: "+$},TypeError),createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),errorsBrowser.codes=codes;var ERR_INVALID_OPT_VALUE=errorsBrowser.codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom($,I,U){return $.highWaterMark!=null?$.highWaterMark:I?$[U]:null}function getHighWaterMark($,I,U,q){var G=highWaterMarkFrom(I,q,U);if(G!=null){if(!(isFinite(G)&&Math.floor(G)===G)||G<0){var K=q?U:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(K,G)}return Math.floor(G)}return $.objectMode?16:16*1024}var state={getHighWaterMark},inherits_browser={exports:{}};typeof Object.create=="function"?inherits_browser.exports=function(I,U){U&&(I.super_=U,I.prototype=Object.create(U.prototype,{constructor:{value:I,enumerable:!1,writable:!0,configurable:!0}}))}:inherits_browser.exports=function(I,U){if(U){I.super_=U;var q=function(){};q.prototype=U.prototype,I.prototype=new q,I.prototype.constructor=I}};var inherits_browserExports=inherits_browser.exports,browser$4=deprecate;function deprecate($,I){if(config$1("noDeprecation"))return $;var U=!1;function q(){if(!U){if(config$1("throwDeprecation"))throw new Error(I);config$1("traceDeprecation")?console.trace(I):console.warn(I),U=!0}return $.apply(this,arguments)}return q}function config$1($){try{if(!commonjsGlobal.localStorage)return!1}catch{return!1}var I=commonjsGlobal.localStorage[$];return I==null?!1:String(I).toLowerCase()==="true"}var _stream_writable,hasRequired_stream_writable;function require_stream_writable(){if(hasRequired_stream_writable)return _stream_writable;hasRequired_stream_writable=1,_stream_writable=be;function $(je){var ze=this;this.next=null,this.entry=null,this.finish=function(){vt(ze,je)}}var I;be.WritableState=ve;var U={deprecate:browser$4},q=streamBrowser,G=buffer.Buffer,K=commonjsGlobal.Uint8Array||function(){};function Y(je){return G.from(je)}function J(je){return G.isBuffer(je)||je instanceof K}var X=destroy_1,Z=state,Q=Z.getHighWaterMark,ee=errorsBrowser.codes,te=ee.ERR_INVALID_ARG_TYPE,ne=ee.ERR_METHOD_NOT_IMPLEMENTED,ie=ee.ERR_MULTIPLE_CALLBACK,oe=ee.ERR_STREAM_CANNOT_PIPE,ce=ee.ERR_STREAM_DESTROYED,fe=ee.ERR_STREAM_NULL_VALUES,se=ee.ERR_STREAM_WRITE_AFTER_END,de=ee.ERR_UNKNOWN_ENCODING,ue=X.errorOrDestroy;inherits_browserExports(be,q);function pe(){}function ve(je,ze,Ae){I=I||require_stream_duplex(),je=je||{},typeof Ae!="boolean"&&(Ae=ze instanceof I),this.objectMode=!!je.objectMode,Ae&&(this.objectMode=this.objectMode||!!je.writableObjectMode),this.highWaterMark=Q(this,je,"writableHighWaterMark",Ae),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var Re=je.decodeStrings===!1;this.decodeStrings=!Re,this.defaultEncoding=je.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(Ce){nt(ze,Ce)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=je.emitClose!==!1,this.autoDestroy=!!je.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new $(this)}ve.prototype.getBuffer=function(){for(var ze=this.bufferedRequest,Ae=[];ze;)Ae.push(ze),ze=ze.next;return Ae},function(){try{Object.defineProperty(ve.prototype,"buffer",{get:U.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var me;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(me=Function.prototype[Symbol.hasInstance],Object.defineProperty(be,Symbol.hasInstance,{value:function(ze){return me.call(this,ze)?!0:this!==be?!1:ze&&ze._writableState instanceof ve}})):me=function(ze){return ze instanceof this};function be(je){I=I||require_stream_duplex();var ze=this instanceof I;if(!ze&&!me.call(be,this))return new be(je);this._writableState=new ve(je,this,ze),this.writable=!0,je&&(typeof je.write=="function"&&(this._write=je.write),typeof je.writev=="function"&&(this._writev=je.writev),typeof je.destroy=="function"&&(this._destroy=je.destroy),typeof je.final=="function"&&(this._final=je.final)),q.call(this)}be.prototype.pipe=function(){ue(this,new oe)};function _e(je,ze){var Ae=new se;ue(je,Ae),process.nextTick(ze,Ae)}function Se(je,ze,Ae,Re){var Ce;return Ae===null?Ce=new fe:typeof Ae!="string"&&!ze.objectMode&&(Ce=new te("chunk",["string","Buffer"],Ae)),Ce?(ue(je,Ce),process.nextTick(Re,Ce),!1):!0}be.prototype.write=function(je,ze,Ae){var Re=this._writableState,Ce=!1,ge=!Re.objectMode&&J(je);return ge&&!G.isBuffer(je)&&(je=Y(je)),typeof ze=="function"&&(Ae=ze,ze=null),ge?ze="buffer":ze||(ze=Re.defaultEncoding),typeof Ae!="function"&&(Ae=pe),Re.ending?_e(this,Ae):(ge||Se(this,Re,je,Ae))&&(Re.pendingcb++,Ce=ke(this,Re,ge,je,ze,Ae)),Ce},be.prototype.cork=function(){this._writableState.corked++},be.prototype.uncork=function(){var je=this._writableState;je.corked&&(je.corked--,!je.writing&&!je.corked&&!je.bufferProcessing&&je.bufferedRequest&&it(this,je))},be.prototype.setDefaultEncoding=function(ze){if(typeof ze=="string"&&(ze=ze.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((ze+"").toLowerCase())>-1))throw new de(ze);return this._writableState.defaultEncoding=ze,this},Object.defineProperty(be.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function xe(je,ze,Ae){return!je.objectMode&&je.decodeStrings!==!1&&typeof ze=="string"&&(ze=G.from(ze,Ae)),ze}Object.defineProperty(be.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function ke(je,ze,Ae,Re,Ce,ge){if(!Ae){var ye=xe(ze,Re,Ce);Re!==ye&&(Ae=!0,Ce="buffer",Re=ye)}var Me=ze.objectMode?1:Re.length;ze.length+=Me;var Ke=ze.length<ze.highWaterMark;if(Ke||(ze.needDrain=!0),ze.writing||ze.corked){var st=ze.lastBufferedRequest;ze.lastBufferedRequest={chunk:Re,encoding:Ce,isBuf:Ae,callback:ge,next:null},st?st.next=ze.lastBufferedRequest:ze.bufferedRequest=ze.lastBufferedRequest,ze.bufferedRequestCount+=1}else De(je,ze,!1,Me,Re,Ce,ge);return Ke}function De(je,ze,Ae,Re,Ce,ge,ye){ze.writelen=Re,ze.writecb=ye,ze.writing=!0,ze.sync=!0,ze.destroyed?ze.onwrite(new ce("write")):Ae?je._writev(Ce,ze.onwrite):je._write(Ce,ge,ze.onwrite),ze.sync=!1}function Be(je,ze,Ae,Re,Ce){--ze.pendingcb,Ae?(process.nextTick(Ce,Re),process.nextTick(We,je,ze),je._writableState.errorEmitted=!0,ue(je,Re)):(Ce(Re),je._writableState.errorEmitted=!0,ue(je,Re),We(je,ze))}function Ve(je){je.writing=!1,je.writecb=null,je.length-=je.writelen,je.writelen=0}function nt(je,ze){var Ae=je._writableState,Re=Ae.sync,Ce=Ae.writecb;if(typeof Ce!="function")throw new ie;if(Ve(Ae),ze)Be(je,Ae,Re,ze,Ce);else{var ge=ut(Ae)||je.destroyed;!ge&&!Ae.corked&&!Ae.bufferProcessing&&Ae.bufferedRequest&&it(je,Ae),Re?process.nextTick(ot,je,Ae,ge,Ce):ot(je,Ae,ge,Ce)}}function ot(je,ze,Ae,Re){Ae||ft(je,ze),ze.pendingcb--,Re(),We(je,ze)}function ft(je,ze){ze.length===0&&ze.needDrain&&(ze.needDrain=!1,je.emit("drain"))}function it(je,ze){ze.bufferProcessing=!0;var Ae=ze.bufferedRequest;if(je._writev&&Ae&&Ae.next){var Re=ze.bufferedRequestCount,Ce=new Array(Re),ge=ze.corkedRequestsFree;ge.entry=Ae;for(var ye=0,Me=!0;Ae;)Ce[ye]=Ae,Ae.isBuf||(Me=!1),Ae=Ae.next,ye+=1;Ce.allBuffers=Me,De(je,ze,!0,ze.length,Ce,"",ge.finish),ze.pendingcb++,ze.lastBufferedRequest=null,ge.next?(ze.corkedRequestsFree=ge.next,ge.next=null):ze.corkedRequestsFree=new $(ze),ze.bufferedRequestCount=0}else{for(;Ae;){var Ke=Ae.chunk,st=Ae.encoding,dt=Ae.callback,$t=ze.objectMode?1:Ke.length;if(De(je,ze,!1,$t,Ke,st,dt),Ae=Ae.next,ze.bufferedRequestCount--,ze.writing)break}Ae===null&&(ze.lastBufferedRequest=null)}ze.bufferedRequest=Ae,ze.bufferProcessing=!1}be.prototype._write=function(je,ze,Ae){Ae(new ne("_write()"))},be.prototype._writev=null,be.prototype.end=function(je,ze,Ae){var Re=this._writableState;return typeof je=="function"?(Ae=je,je=null,ze=null):typeof ze=="function"&&(Ae=ze,ze=null),je!=null&&this.write(je,ze),Re.corked&&(Re.corked=1,this.uncork()),Re.ending||tt(this,Re,Ae),this},Object.defineProperty(be.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function ut(je){return je.ending&&je.length===0&&je.bufferedRequest===null&&!je.finished&&!je.writing}function et(je,ze){je._final(function(Ae){ze.pendingcb--,Ae&&ue(je,Ae),ze.prefinished=!0,je.emit("prefinish"),We(je,ze)})}function Ue(je,ze){!ze.prefinished&&!ze.finalCalled&&(typeof je._final=="function"&&!ze.destroyed?(ze.pendingcb++,ze.finalCalled=!0,process.nextTick(et,je,ze)):(ze.prefinished=!0,je.emit("prefinish")))}function We(je,ze){var Ae=ut(ze);if(Ae&&(Ue(je,ze),ze.pendingcb===0&&(ze.finished=!0,je.emit("finish"),ze.autoDestroy))){var Re=je._readableState;(!Re||Re.autoDestroy&&Re.endEmitted)&&je.destroy()}return Ae}function tt(je,ze,Ae){ze.ending=!0,We(je,ze),Ae&&(ze.finished?process.nextTick(Ae):je.once("finish",Ae)),ze.ended=!0,je.writable=!1}function vt(je,ze,Ae){var Re=je.entry;for(je.entry=null;Re;){var Ce=Re.callback;ze.pendingcb--,Ce(Ae),Re=Re.next}ze.corkedRequestsFree.next=je}return Object.defineProperty(be.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(ze){this._writableState&&(this._writableState.destroyed=ze)}}),be.prototype.destroy=X.destroy,be.prototype._undestroy=X.undestroy,be.prototype._destroy=function(je,ze){ze(je)},_stream_writable}var _stream_duplex,hasRequired_stream_duplex;function require_stream_duplex(){if(hasRequired_stream_duplex)return _stream_duplex;hasRequired_stream_duplex=1;var $=Object.keys||function(Z){var Q=[];for(var ee in Z)Q.push(ee);return Q};_stream_duplex=Y;var I=require_stream_readable(),U=require_stream_writable();inherits_browserExports(Y,I);for(var q=$(U.prototype),G=0;G<q.length;G++){var K=q[G];Y.prototype[K]||(Y.prototype[K]=U.prototype[K])}function Y(Z){if(!(this instanceof Y))return new Y(Z);I.call(this,Z),U.call(this,Z),this.allowHalfOpen=!0,Z&&(Z.readable===!1&&(this.readable=!1),Z.writable===!1&&(this.writable=!1),Z.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",J)))}Object.defineProperty(Y.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(Y.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(Y.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function J(){this._writableState.ended||process.nextTick(X,this)}function X(Z){Z.end()}return Object.defineProperty(Y.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(Q){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=Q,this._writableState.destroyed=Q)}}),_stream_duplex}var string_decoder={},safeBuffer={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var hasRequiredSafeBuffer;function requireSafeBuffer(){return hasRequiredSafeBuffer||(hasRequiredSafeBuffer=1,function($,I){var U=buffer,q=U.Buffer;function G(Y,J){for(var X in Y)J[X]=Y[X]}q.from&&q.alloc&&q.allocUnsafe&&q.allocUnsafeSlow?$.exports=U:(G(U,I),I.Buffer=K);function K(Y,J,X){return q(Y,J,X)}K.prototype=Object.create(q.prototype),G(q,K),K.from=function(Y,J,X){if(typeof Y=="number")throw new TypeError("Argument must not be a number");return q(Y,J,X)},K.alloc=function(Y,J,X){if(typeof Y!="number")throw new TypeError("Argument must be a number");var Z=q(Y);return J!==void 0?typeof X=="string"?Z.fill(J,X):Z.fill(J):Z.fill(0),Z},K.allocUnsafe=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return q(Y)},K.allocUnsafeSlow=function(Y){if(typeof Y!="number")throw new TypeError("Argument must be a number");return U.SlowBuffer(Y)}}(safeBuffer,safeBuffer.exports)),safeBuffer.exports}var hasRequiredString_decoder;function requireString_decoder(){if(hasRequiredString_decoder)return string_decoder;hasRequiredString_decoder=1;var $=requireSafeBuffer().Buffer,I=$.isEncoding||function(fe){switch(fe=""+fe,fe&&fe.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function U(fe){if(!fe)return"utf8";for(var se;;)switch(fe){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return fe;default:if(se)return;fe=(""+fe).toLowerCase(),se=!0}}function q(fe){var se=U(fe);if(typeof se!="string"&&($.isEncoding===I||!I(fe)))throw new Error("Unknown encoding: "+fe);return se||fe}string_decoder.StringDecoder=G;function G(fe){this.encoding=q(fe);var se;switch(this.encoding){case"utf16le":this.text=ee,this.end=te,se=4;break;case"utf8":this.fillLast=X,se=4;break;case"base64":this.text=ne,this.end=ie,se=3;break;default:this.write=oe,this.end=ce;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=$.allocUnsafe(se)}G.prototype.write=function(fe){if(fe.length===0)return"";var se,de;if(this.lastNeed){if(se=this.fillLast(fe),se===void 0)return"";de=this.lastNeed,this.lastNeed=0}else de=0;return de<fe.length?se?se+this.text(fe,de):this.text(fe,de):se||""},G.prototype.end=Q,G.prototype.text=Z,G.prototype.fillLast=function(fe){if(this.lastNeed<=fe.length)return fe.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);fe.copy(this.lastChar,this.lastTotal-this.lastNeed,0,fe.length),this.lastNeed-=fe.length};function K(fe){return fe<=127?0:fe>>5===6?2:fe>>4===14?3:fe>>3===30?4:fe>>6===2?-1:-2}function Y(fe,se,de){var ue=se.length-1;if(ue<de)return 0;var pe=K(se[ue]);return pe>=0?(pe>0&&(fe.lastNeed=pe-1),pe):--ue<de||pe===-2?0:(pe=K(se[ue]),pe>=0?(pe>0&&(fe.lastNeed=pe-2),pe):--ue<de||pe===-2?0:(pe=K(se[ue]),pe>=0?(pe>0&&(pe===2?pe=0:fe.lastNeed=pe-3),pe):0))}function J(fe,se,de){if((se[0]&192)!==128)return fe.lastNeed=0,"�";if(fe.lastNeed>1&&se.length>1){if((se[1]&192)!==128)return fe.lastNeed=1,"�";if(fe.lastNeed>2&&se.length>2&&(se[2]&192)!==128)return fe.lastNeed=2,"�"}}function X(fe){var se=this.lastTotal-this.lastNeed,de=J(this,fe);if(de!==void 0)return de;if(this.lastNeed<=fe.length)return fe.copy(this.lastChar,se,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);fe.copy(this.lastChar,se,0,fe.length),this.lastNeed-=fe.length}function Z(fe,se){var de=Y(this,fe,se);if(!this.lastNeed)return fe.toString("utf8",se);this.lastTotal=de;var ue=fe.length-(de-this.lastNeed);return fe.copy(this.lastChar,0,ue),fe.toString("utf8",se,ue)}function Q(fe){var se=fe&&fe.length?this.write(fe):"";return this.lastNeed?se+"�":se}function ee(fe,se){if((fe.length-se)%2===0){var de=fe.toString("utf16le",se);if(de){var ue=de.charCodeAt(de.length-1);if(ue>=55296&&ue<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=fe[fe.length-2],this.lastChar[1]=fe[fe.length-1],de.slice(0,-1)}return de}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=fe[fe.length-1],fe.toString("utf16le",se,fe.length-1)}function te(fe){var se=fe&&fe.length?this.write(fe):"";if(this.lastNeed){var de=this.lastTotal-this.lastNeed;return se+this.lastChar.toString("utf16le",0,de)}return se}function ne(fe,se){var de=(fe.length-se)%3;return de===0?fe.toString("base64",se):(this.lastNeed=3-de,this.lastTotal=3,de===1?this.lastChar[0]=fe[fe.length-1]:(this.lastChar[0]=fe[fe.length-2],this.lastChar[1]=fe[fe.length-1]),fe.toString("base64",se,fe.length-de))}function ie(fe){var se=fe&&fe.length?this.write(fe):"";return this.lastNeed?se+this.lastChar.toString("base64",0,3-this.lastNeed):se}function oe(fe){return fe.toString(this.encoding)}function ce(fe){return fe&&fe.length?this.write(fe):""}return string_decoder}var ERR_STREAM_PREMATURE_CLOSE=errorsBrowser.codes.ERR_STREAM_PREMATURE_CLOSE;function once$1($){var I=!1;return function(){if(!I){I=!0;for(var U=arguments.length,q=new Array(U),G=0;G<U;G++)q[G]=arguments[G];$.apply(this,q)}}}function noop$2(){}function isRequest$1($){return $.setHeader&&typeof $.abort=="function"}function eos$1($,I,U){if(typeof I=="function")return eos$1($,null,I);I||(I={}),U=once$1(U||noop$2);var q=I.readable||I.readable!==!1&&$.readable,G=I.writable||I.writable!==!1&&$.writable,K=function(){$.writable||J()},Y=$._writableState&&$._writableState.finished,J=function(){G=!1,Y=!0,q||U.call($)},X=$._readableState&&$._readableState.endEmitted,Z=function(){q=!1,X=!0,G||U.call($)},Q=function(ie){U.call($,ie)},ee=function(){var ie;if(q&&!X)return(!$._readableState||!$._readableState.ended)&&(ie=new ERR_STREAM_PREMATURE_CLOSE),U.call($,ie);if(G&&!Y)return(!$._writableState||!$._writableState.ended)&&(ie=new ERR_STREAM_PREMATURE_CLOSE),U.call($,ie)},te=function(){$.req.on("finish",J)};return isRequest$1($)?($.on("complete",J),$.on("abort",ee),$.req?te():$.on("request",te)):G&&!$._writableState&&($.on("end",K),$.on("close",K)),$.on("end",Z),$.on("finish",J),I.error!==!1&&$.on("error",Q),$.on("close",ee),function(){$.removeListener("complete",J),$.removeListener("abort",ee),$.removeListener("request",te),$.req&&$.req.removeListener("finish",J),$.removeListener("end",K),$.removeListener("close",K),$.removeListener("finish",J),$.removeListener("end",Z),$.removeListener("error",Q),$.removeListener("close",ee)}}var endOfStream=eos$1,async_iterator,hasRequiredAsync_iterator;function requireAsync_iterator(){if(hasRequiredAsync_iterator)return async_iterator;hasRequiredAsync_iterator=1;var $;function I(fe,se,de){return se in fe?Object.defineProperty(fe,se,{value:de,enumerable:!0,configurable:!0,writable:!0}):fe[se]=de,fe}var U=endOfStream,q=Symbol("lastResolve"),G=Symbol("lastReject"),K=Symbol("error"),Y=Symbol("ended"),J=Symbol("lastPromise"),X=Symbol("handlePromise"),Z=Symbol("stream");function Q(fe,se){return{value:fe,done:se}}function ee(fe){var se=fe[q];if(se!==null){var de=fe[Z].read();de!==null&&(fe[J]=null,fe[q]=null,fe[G]=null,se(Q(de,!1)))}}function te(fe){process.nextTick(ee,fe)}function ne(fe,se){return function(de,ue){fe.then(function(){if(se[Y]){de(Q(void 0,!0));return}se[X](de,ue)},ue)}}var ie=Object.getPrototypeOf(function(){}),oe=Object.setPrototypeOf(($={get stream(){return this[Z]},next:function(){var se=this,de=this[K];if(de!==null)return Promise.reject(de);if(this[Y])return Promise.resolve(Q(void 0,!0));if(this[Z].destroyed)return new Promise(function(me,be){process.nextTick(function(){se[K]?be(se[K]):me(Q(void 0,!0))})});var ue=this[J],pe;if(ue)pe=new Promise(ne(ue,this));else{var ve=this[Z].read();if(ve!==null)return Promise.resolve(Q(ve,!1));pe=new Promise(this[X])}return this[J]=pe,pe}},I($,Symbol.asyncIterator,function(){return this}),I($,"return",function(){var se=this;return new Promise(function(de,ue){se[Z].destroy(null,function(pe){if(pe){ue(pe);return}de(Q(void 0,!0))})})}),$),ie),ce=function(se){var de,ue=Object.create(oe,(de={},I(de,Z,{value:se,writable:!0}),I(de,q,{value:null,writable:!0}),I(de,G,{value:null,writable:!0}),I(de,K,{value:null,writable:!0}),I(de,Y,{value:se._readableState.endEmitted,writable:!0}),I(de,X,{value:function(ve,me){var be=ue[Z].read();be?(ue[J]=null,ue[q]=null,ue[G]=null,ve(Q(be,!1))):(ue[q]=ve,ue[G]=me)},writable:!0}),de));return ue[J]=null,U(se,function(pe){if(pe&&pe.code!=="ERR_STREAM_PREMATURE_CLOSE"){var ve=ue[G];ve!==null&&(ue[J]=null,ue[q]=null,ue[G]=null,ve(pe)),ue[K]=pe;return}var me=ue[q];me!==null&&(ue[J]=null,ue[q]=null,ue[G]=null,me(Q(void 0,!0))),ue[Y]=!0}),se.on("readable",te.bind(null,ue)),ue};return async_iterator=ce,async_iterator}var fromBrowser,hasRequiredFromBrowser;function requireFromBrowser(){return hasRequiredFromBrowser||(hasRequiredFromBrowser=1,fromBrowser=function(){throw new Error("Readable.from is not available in the browser")}),fromBrowser}var _stream_readable,hasRequired_stream_readable;function require_stream_readable(){if(hasRequired_stream_readable)return _stream_readable;hasRequired_stream_readable=1,_stream_readable=_e;var $;_e.ReadableState=be,eventsExports.EventEmitter;var I=function(ye,Me){return ye.listeners(Me).length},U=streamBrowser,q=buffer.Buffer,G=commonjsGlobal.Uint8Array||function(){};function K(ge){return q.from(ge)}function Y(ge){return q.isBuffer(ge)||ge instanceof G}var J=require$$3,X;J&&J.debuglog?X=J.debuglog("stream"):X=function(){};var Z=requireBuffer_list(),Q=destroy_1,ee=state,te=ee.getHighWaterMark,ne=errorsBrowser.codes,ie=ne.ERR_INVALID_ARG_TYPE,oe=ne.ERR_STREAM_PUSH_AFTER_EOF,ce=ne.ERR_METHOD_NOT_IMPLEMENTED,fe=ne.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,se,de,ue;inherits_browserExports(_e,U);var pe=Q.errorOrDestroy,ve=["error","close","destroy","pause","resume"];function me(ge,ye,Me){if(typeof ge.prependListener=="function")return ge.prependListener(ye,Me);!ge._events||!ge._events[ye]?ge.on(ye,Me):Array.isArray(ge._events[ye])?ge._events[ye].unshift(Me):ge._events[ye]=[Me,ge._events[ye]]}function be(ge,ye,Me){$=$||require_stream_duplex(),ge=ge||{},typeof Me!="boolean"&&(Me=ye instanceof $),this.objectMode=!!ge.objectMode,Me&&(this.objectMode=this.objectMode||!!ge.readableObjectMode),this.highWaterMark=te(this,ge,"readableHighWaterMark",Me),this.buffer=new Z,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=ge.emitClose!==!1,this.autoDestroy=!!ge.autoDestroy,this.destroyed=!1,this.defaultEncoding=ge.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,ge.encoding&&(se||(se=requireString_decoder().StringDecoder),this.decoder=new se(ge.encoding),this.encoding=ge.encoding)}function _e(ge){if($=$||require_stream_duplex(),!(this instanceof _e))return new _e(ge);var ye=this instanceof $;this._readableState=new be(ge,this,ye),this.readable=!0,ge&&(typeof ge.read=="function"&&(this._read=ge.read),typeof ge.destroy=="function"&&(this._destroy=ge.destroy)),U.call(this)}Object.defineProperty(_e.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(ye){this._readableState&&(this._readableState.destroyed=ye)}}),_e.prototype.destroy=Q.destroy,_e.prototype._undestroy=Q.undestroy,_e.prototype._destroy=function(ge,ye){ye(ge)},_e.prototype.push=function(ge,ye){var Me=this._readableState,Ke;return Me.objectMode?Ke=!0:typeof ge=="string"&&(ye=ye||Me.defaultEncoding,ye!==Me.encoding&&(ge=q.from(ge,ye),ye=""),Ke=!0),Se(this,ge,ye,!1,Ke)},_e.prototype.unshift=function(ge){return Se(this,ge,null,!0,!1)};function Se(ge,ye,Me,Ke,st){X("readableAddChunk",ye);var dt=ge._readableState;if(ye===null)dt.reading=!1,nt(ge,dt);else{var $t;if(st||($t=ke(dt,ye)),$t)pe(ge,$t);else if(dt.objectMode||ye&&ye.length>0)if(typeof ye!="string"&&!dt.objectMode&&Object.getPrototypeOf(ye)!==q.prototype&&(ye=K(ye)),Ke)dt.endEmitted?pe(ge,new fe):xe(ge,dt,ye,!0);else if(dt.ended)pe(ge,new oe);else{if(dt.destroyed)return!1;dt.reading=!1,dt.decoder&&!Me?(ye=dt.decoder.write(ye),dt.objectMode||ye.length!==0?xe(ge,dt,ye,!1):it(ge,dt)):xe(ge,dt,ye,!1)}else Ke||(dt.reading=!1,it(ge,dt))}return!dt.ended&&(dt.length<dt.highWaterMark||dt.length===0)}function xe(ge,ye,Me,Ke){ye.flowing&&ye.length===0&&!ye.sync?(ye.awaitDrain=0,ge.emit("data",Me)):(ye.length+=ye.objectMode?1:Me.length,Ke?ye.buffer.unshift(Me):ye.buffer.push(Me),ye.needReadable&&ot(ge)),it(ge,ye)}function ke(ge,ye){var Me;return!Y(ye)&&typeof ye!="string"&&ye!==void 0&&!ge.objectMode&&(Me=new ie("chunk",["string","Buffer","Uint8Array"],ye)),Me}_e.prototype.isPaused=function(){return this._readableState.flowing===!1},_e.prototype.setEncoding=function(ge){se||(se=requireString_decoder().StringDecoder);var ye=new se(ge);this._readableState.decoder=ye,this._readableState.encoding=this._readableState.decoder.encoding;for(var Me=this._readableState.buffer.head,Ke="";Me!==null;)Ke+=ye.write(Me.data),Me=Me.next;return this._readableState.buffer.clear(),Ke!==""&&this._readableState.buffer.push(Ke),this._readableState.length=Ke.length,this};var De=1073741824;function Be(ge){return ge>=De?ge=De:(ge--,ge|=ge>>>1,ge|=ge>>>2,ge|=ge>>>4,ge|=ge>>>8,ge|=ge>>>16,ge++),ge}function Ve(ge,ye){return ge<=0||ye.length===0&&ye.ended?0:ye.objectMode?1:ge!==ge?ye.flowing&&ye.length?ye.buffer.head.data.length:ye.length:(ge>ye.highWaterMark&&(ye.highWaterMark=Be(ge)),ge<=ye.length?ge:ye.ended?ye.length:(ye.needReadable=!0,0))}_e.prototype.read=function(ge){X("read",ge),ge=parseInt(ge,10);var ye=this._readableState,Me=ge;if(ge!==0&&(ye.emittedReadable=!1),ge===0&&ye.needReadable&&((ye.highWaterMark!==0?ye.length>=ye.highWaterMark:ye.length>0)||ye.ended))return X("read: emitReadable",ye.length,ye.ended),ye.length===0&&ye.ended?Ae(this):ot(this),null;if(ge=Ve(ge,ye),ge===0&&ye.ended)return ye.length===0&&Ae(this),null;var Ke=ye.needReadable;X("need readable",Ke),(ye.length===0||ye.length-ge<ye.highWaterMark)&&(Ke=!0,X("length less than watermark",Ke)),ye.ended||ye.reading?(Ke=!1,X("reading or ended",Ke)):Ke&&(X("do read"),ye.reading=!0,ye.sync=!0,ye.length===0&&(ye.needReadable=!0),this._read(ye.highWaterMark),ye.sync=!1,ye.reading||(ge=Ve(Me,ye)));var st;return ge>0?st=ze(ge,ye):st=null,st===null?(ye.needReadable=ye.length<=ye.highWaterMark,ge=0):(ye.length-=ge,ye.awaitDrain=0),ye.length===0&&(ye.ended||(ye.needReadable=!0),Me!==ge&&ye.ended&&Ae(this)),st!==null&&this.emit("data",st),st};function nt(ge,ye){if(X("onEofChunk"),!ye.ended){if(ye.decoder){var Me=ye.decoder.end();Me&&Me.length&&(ye.buffer.push(Me),ye.length+=ye.objectMode?1:Me.length)}ye.ended=!0,ye.sync?ot(ge):(ye.needReadable=!1,ye.emittedReadable||(ye.emittedReadable=!0,ft(ge)))}}function ot(ge){var ye=ge._readableState;X("emitReadable",ye.needReadable,ye.emittedReadable),ye.needReadable=!1,ye.emittedReadable||(X("emitReadable",ye.flowing),ye.emittedReadable=!0,process.nextTick(ft,ge))}function ft(ge){var ye=ge._readableState;X("emitReadable_",ye.destroyed,ye.length,ye.ended),!ye.destroyed&&(ye.length||ye.ended)&&(ge.emit("readable"),ye.emittedReadable=!1),ye.needReadable=!ye.flowing&&!ye.ended&&ye.length<=ye.highWaterMark,je(ge)}function it(ge,ye){ye.readingMore||(ye.readingMore=!0,process.nextTick(ut,ge,ye))}function ut(ge,ye){for(;!ye.reading&&!ye.ended&&(ye.length<ye.highWaterMark||ye.flowing&&ye.length===0);){var Me=ye.length;if(X("maybeReadMore read 0"),ge.read(0),Me===ye.length)break}ye.readingMore=!1}_e.prototype._read=function(ge){pe(this,new ce("_read()"))},_e.prototype.pipe=function(ge,ye){var Me=this,Ke=this._readableState;switch(Ke.pipesCount){case 0:Ke.pipes=ge;break;case 1:Ke.pipes=[Ke.pipes,ge];break;default:Ke.pipes.push(ge);break}Ke.pipesCount+=1,X("pipe count=%d opts=%j",Ke.pipesCount,ye);var st=(!ye||ye.end!==!1)&&ge!==process.stdout&&ge!==process.stderr,dt=st?Et:Ut;Ke.endEmitted?process.nextTick(dt):Me.once("end",dt),ge.on("unpipe",$t);function $t(le,re){X("onunpipe"),le===Me&&re&&re.hasUnpiped===!1&&(re.hasUnpiped=!0,Gt())}function Et(){X("onend"),ge.end()}var rt=et(Me);ge.on("drain",rt);var jt=!1;function Gt(){X("cleanup"),ge.removeListener("close",nn),ge.removeListener("finish",St),ge.removeListener("drain",rt),ge.removeListener("error",zt),ge.removeListener("unpipe",$t),Me.removeListener("end",Et),Me.removeListener("end",Ut),Me.removeListener("data",At),jt=!0,Ke.awaitDrain&&(!ge._writableState||ge._writableState.needDrain)&&rt()}Me.on("data",At);function At(le){X("ondata");var re=ge.write(le);X("dest.write",re),re===!1&&((Ke.pipesCount===1&&Ke.pipes===ge||Ke.pipesCount>1&&Ce(Ke.pipes,ge)!==-1)&&!jt&&(X("false write response, pause",Ke.awaitDrain),Ke.awaitDrain++),Me.pause())}function zt(le){X("onerror",le),Ut(),ge.removeListener("error",zt),I(ge,"error")===0&&pe(ge,le)}me(ge,"error",zt);function nn(){ge.removeListener("finish",St),Ut()}ge.once("close",nn);function St(){X("onfinish"),ge.removeListener("close",nn),Ut()}ge.once("finish",St);function Ut(){X("unpipe"),Me.unpipe(ge)}return ge.emit("pipe",Me),Ke.flowing||(X("pipe resume"),Me.resume()),ge};function et(ge){return function(){var Me=ge._readableState;X("pipeOnDrain",Me.awaitDrain),Me.awaitDrain&&Me.awaitDrain--,Me.awaitDrain===0&&I(ge,"data")&&(Me.flowing=!0,je(ge))}}_e.prototype.unpipe=function(ge){var ye=this._readableState,Me={hasUnpiped:!1};if(ye.pipesCount===0)return this;if(ye.pipesCount===1)return ge&&ge!==ye.pipes?this:(ge||(ge=ye.pipes),ye.pipes=null,ye.pipesCount=0,ye.flowing=!1,ge&&ge.emit("unpipe",this,Me),this);if(!ge){var Ke=ye.pipes,st=ye.pipesCount;ye.pipes=null,ye.pipesCount=0,ye.flowing=!1;for(var dt=0;dt<st;dt++)Ke[dt].emit("unpipe",this,{hasUnpiped:!1});return this}var $t=Ce(ye.pipes,ge);return $t===-1?this:(ye.pipes.splice($t,1),ye.pipesCount-=1,ye.pipesCount===1&&(ye.pipes=ye.pipes[0]),ge.emit("unpipe",this,Me),this)},_e.prototype.on=function(ge,ye){var Me=U.prototype.on.call(this,ge,ye),Ke=this._readableState;return ge==="data"?(Ke.readableListening=this.listenerCount("readable")>0,Ke.flowing!==!1&&this.resume()):ge==="readable"&&!Ke.endEmitted&&!Ke.readableListening&&(Ke.readableListening=Ke.needReadable=!0,Ke.flowing=!1,Ke.emittedReadable=!1,X("on readable",Ke.length,Ke.reading),Ke.length?ot(this):Ke.reading||process.nextTick(We,this)),Me},_e.prototype.addListener=_e.prototype.on,_e.prototype.removeListener=function(ge,ye){var Me=U.prototype.removeListener.call(this,ge,ye);return ge==="readable"&&process.nextTick(Ue,this),Me},_e.prototype.removeAllListeners=function(ge){var ye=U.prototype.removeAllListeners.apply(this,arguments);return(ge==="readable"||ge===void 0)&&process.nextTick(Ue,this),ye};function Ue(ge){var ye=ge._readableState;ye.readableListening=ge.listenerCount("readable")>0,ye.resumeScheduled&&!ye.paused?ye.flowing=!0:ge.listenerCount("data")>0&&ge.resume()}function We(ge){X("readable nexttick read 0"),ge.read(0)}_e.prototype.resume=function(){var ge=this._readableState;return ge.flowing||(X("resume"),ge.flowing=!ge.readableListening,tt(this,ge)),ge.paused=!1,this};function tt(ge,ye){ye.resumeScheduled||(ye.resumeScheduled=!0,process.nextTick(vt,ge,ye))}function vt(ge,ye){X("resume",ye.reading),ye.reading||ge.read(0),ye.resumeScheduled=!1,ge.emit("resume"),je(ge),ye.flowing&&!ye.reading&&ge.read(0)}_e.prototype.pause=function(){return X("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(X("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function je(ge){var ye=ge._readableState;for(X("flow",ye.flowing);ye.flowing&&ge.read()!==null;);}_e.prototype.wrap=function(ge){var ye=this,Me=this._readableState,Ke=!1;ge.on("end",function(){if(X("wrapped end"),Me.decoder&&!Me.ended){var $t=Me.decoder.end();$t&&$t.length&&ye.push($t)}ye.push(null)}),ge.on("data",function($t){if(X("wrapped data"),Me.decoder&&($t=Me.decoder.write($t)),!(Me.objectMode&&$t==null)&&!(!Me.objectMode&&(!$t||!$t.length))){var Et=ye.push($t);Et||(Ke=!0,ge.pause())}});for(var st in ge)this[st]===void 0&&typeof ge[st]=="function"&&(this[st]=function(Et){return function(){return ge[Et].apply(ge,arguments)}}(st));for(var dt=0;dt<ve.length;dt++)ge.on(ve[dt],this.emit.bind(this,ve[dt]));return this._read=function($t){X("wrapped _read",$t),Ke&&(Ke=!1,ge.resume())},this},typeof Symbol=="function"&&(_e.prototype[Symbol.asyncIterator]=function(){return de===void 0&&(de=requireAsync_iterator()),de(this)}),Object.defineProperty(_e.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(_e.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(_e.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(ye){this._readableState&&(this._readableState.flowing=ye)}}),_e._fromList=ze,Object.defineProperty(_e.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function ze(ge,ye){if(ye.length===0)return null;var Me;return ye.objectMode?Me=ye.buffer.shift():!ge||ge>=ye.length?(ye.decoder?Me=ye.buffer.join(""):ye.buffer.length===1?Me=ye.buffer.first():Me=ye.buffer.concat(ye.length),ye.buffer.clear()):Me=ye.buffer.consume(ge,ye.decoder),Me}function Ae(ge){var ye=ge._readableState;X("endReadable",ye.endEmitted),ye.endEmitted||(ye.ended=!0,process.nextTick(Re,ye,ge))}function Re(ge,ye){if(X("endReadableNT",ge.endEmitted,ge.length),!ge.endEmitted&&ge.length===0&&(ge.endEmitted=!0,ye.readable=!1,ye.emit("end"),ge.autoDestroy)){var Me=ye._writableState;(!Me||Me.autoDestroy&&Me.finished)&&ye.destroy()}}typeof Symbol=="function"&&(_e.from=function(ge,ye){return ue===void 0&&(ue=requireFromBrowser()),ue(_e,ge,ye)});function Ce(ge,ye){for(var Me=0,Ke=ge.length;Me<Ke;Me++)if(ge[Me]===ye)return Me;return-1}return _stream_readable}var _stream_transform=Transform$1,_require$codes$1=errorsBrowser.codes,ERR_METHOD_NOT_IMPLEMENTED=_require$codes$1.ERR_METHOD_NOT_IMPLEMENTED,ERR_MULTIPLE_CALLBACK=_require$codes$1.ERR_MULTIPLE_CALLBACK,ERR_TRANSFORM_ALREADY_TRANSFORMING=_require$codes$1.ERR_TRANSFORM_ALREADY_TRANSFORMING,ERR_TRANSFORM_WITH_LENGTH_0=_require$codes$1.ERR_TRANSFORM_WITH_LENGTH_0,Duplex=require_stream_duplex();inherits_browserExports(Transform$1,Duplex);function afterTransform($,I){var U=this._transformState;U.transforming=!1;var q=U.writecb;if(q===null)return this.emit("error",new ERR_MULTIPLE_CALLBACK);U.writechunk=null,U.writecb=null,I!=null&&this.push(I),q($);var G=this._readableState;G.reading=!1,(G.needReadable||G.length<G.highWaterMark)&&this._read(G.highWaterMark)}function Transform$1($){if(!(this instanceof Transform$1))return new Transform$1($);Duplex.call(this,$),this._transformState={afterTransform:afterTransform.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,$&&(typeof $.transform=="function"&&(this._transform=$.transform),typeof $.flush=="function"&&(this._flush=$.flush)),this.on("prefinish",prefinish)}function prefinish(){var $=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(I,U){done$1($,I,U)}):done$1(this,null,null)}Transform$1.prototype.push=function($,I){return this._transformState.needTransform=!1,Duplex.prototype.push.call(this,$,I)},Transform$1.prototype._transform=function($,I,U){U(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"))},Transform$1.prototype._write=function($,I,U){var q=this._transformState;if(q.writecb=U,q.writechunk=$,q.writeencoding=I,!q.transforming){var G=this._readableState;(q.needTransform||G.needReadable||G.length<G.highWaterMark)&&this._read(G.highWaterMark)}},Transform$1.prototype._read=function($){var I=this._transformState;I.writechunk!==null&&!I.transforming?(I.transforming=!0,this._transform(I.writechunk,I.writeencoding,I.afterTransform)):I.needTransform=!0},Transform$1.prototype._destroy=function($,I){Duplex.prototype._destroy.call(this,$,function(U){I(U)})};function done$1($,I,U){if(I)return $.emit("error",I);if(U!=null&&$.push(U),$._writableState.length)throw new ERR_TRANSFORM_WITH_LENGTH_0;if($._transformState.transforming)throw new ERR_TRANSFORM_ALREADY_TRANSFORMING;return $.push(null)}var _stream_passthrough=PassThrough,Transform=_stream_transform;inherits_browserExports(PassThrough,Transform);function PassThrough($){if(!(this instanceof PassThrough))return new PassThrough($);Transform.call(this,$)}PassThrough.prototype._transform=function($,I,U){U(null,$)};var eos;function once($){var I=!1;return function(){I||(I=!0,$.apply(void 0,arguments))}}var _require$codes=errorsBrowser.codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop$1($){if($)throw $}function isRequest($){return $.setHeader&&typeof $.abort=="function"}function destroyer($,I,U,q){q=once(q);var G=!1;$.on("close",function(){G=!0}),eos===void 0&&(eos=endOfStream),eos($,{readable:I,writable:U},function(Y){if(Y)return q(Y);G=!0,q()});var K=!1;return function(Y){if(!G&&!K){if(K=!0,isRequest($))return $.abort();if(typeof $.destroy=="function")return $.destroy();q(Y||new ERR_STREAM_DESTROYED("pipe"))}}}function call($){$()}function pipe($,I){return $.pipe(I)}function popCallback($){return!$.length||typeof $[$.length-1]!="function"?noop$1:$.pop()}function pipeline(){for(var $=arguments.length,I=new Array($),U=0;U<$;U++)I[U]=arguments[U];var q=popCallback(I);if(Array.isArray(I[0])&&(I=I[0]),I.length<2)throw new ERR_MISSING_ARGS("streams");var G,K=I.map(function(Y,J){var X=J<I.length-1,Z=J>0;return destroyer(Y,X,Z,function(Q){G||(G=Q),Q&&K.forEach(call),!X&&(K.forEach(call),q(G))})});return I.reduce(pipe)}var pipeline_1=pipeline;(function($,I){I=$.exports=require_stream_readable(),I.Stream=I,I.Readable=I,I.Writable=require_stream_writable(),I.Duplex=require_stream_duplex(),I.Transform=_stream_transform,I.PassThrough=_stream_passthrough,I.finished=endOfStream,I.pipeline=pipeline_1})(readableBrowser,readableBrowser.exports);var readableBrowserExports=readableBrowser.exports,createPromiseFromCallback=$=>new Promise((I,U)=>{$((q,G)=>{q?U(q):I(G)})}),TimeoutError=class extends Error{constructor($,I){super($?`Timeout [${$.toLocaleString()}ms]${I===void 0?"":`: ${I}`}`:"Timeout")}},sleep=$=>new Promise(I=>{const U=Date.now()+$,q=()=>{const G=U-Date.now();G>0?setTimeout(q,G):I()};q()}),asyncTimeout=async($,I,U)=>{let q;const G=U===void 0||typeof U=="string"?new TimeoutError(I,U):U,K=new Promise((J,X)=>{q=setTimeout(()=>{X(G)},I),unrefTimeout(q)}),Y=typeof $=="function"?createPromiseFromCallback($):$;return await Promise.race([Y,K]).finally(()=>{clearTimeout(q)})},unrefTimeout=$=>{typeof $=="object"&&"unref"in $&&$.unref()},Event$1=class hr{constructor(){this._listeners=new Set,this._effects=new Set}static wrap(I,U){const q=new hr;return q.addEffect(()=>{const G=K=>q.emit(K);return I.on(U,G),()=>I.off(U,G)}),q}emit(I){for(const U of this._listeners)U.trigger(I),U.once&&this._listeners.delete(U)}on(I,U,q){const[G,K]=I instanceof Context?[I,U]:[new Context,I],Y=!!(q!=null&&q.weak),J=!!(q!=null&&q.once),X=new EventListener(this,K,G,J,Y);return this._addListener(X),()=>{this._removeListener(X)}}off(I){for(const U of this._listeners)U.derefCallback()===I&&this._removeListener(U)}once(I,U){const[q,G]=I instanceof Context?[I,U]:[new Context,I],K=new EventListener(this,G,q,!0,!1);return this._addListener(K),()=>{this._removeListener(K)}}async*[Symbol.asyncIterator](){for(;;)yield await new Promise(I=>{this.once(I)})}waitFor(I){return new Promise(U=>{const q=this.on(G=>{I(G)&&(q(),U(G))})})}waitForCount(I){let U=0;return this.waitFor(()=>++U===I)}async waitForCondition(I){I()||await this.waitFor(I)}listenerCount(){return this._listeners.size}addEffect(I){const U={effect:I,cleanup:void 0};return this.listenerCount()>0&&(U.cleanup=U.effect()),this._effects.add(U),()=>{var q;(q=U.cleanup)==null||q.call(U),this._effects.delete(U)}}debounce(I=0){let U,q;const G=new hr;return G.addEffect(()=>{const K=this.on(()=>{if(!U){const Y=!q||Date.now()-q>I?I/8:I;U=setTimeout(()=>{q=Date.now(),U=void 0,G.emit()},Y)}});return()=>{K(),clearTimeout(U)}}),G}discardParameter(){return this}toJSON(){return{listenerCount:this.listenerCount()}}_addListener(I){this._listeners.add(I),this.listenerCount()===1&&this._runEffects()}_removeListener(I){this._listeners.delete(I),I.remove(),this.listenerCount()===0&&this._cleanupEffects()}_runEffects(){for(const I of this._effects)I.cleanup=I.effect()}_cleanupEffects(){var I;for(const U of this._effects)(I=U.cleanup)==null||I.call(U),U.cleanup=void 0}},EventListener=class{constructor($,I,U,q,G){this.ctx=U,this.once=q,this.weak=G,this._clearDispose=void 0,this._clearDispose=U.onDispose(()=>{$._removeListener(this)}),G?(this.callback=new WeakRef(I),weakListeners().registry.register(I,{event:new WeakRef($),listener:this},this)):this.callback=I}derefCallback(){return this.weak?this.callback.deref():this.callback}async trigger($){try{const I=this.derefCallback();await(I==null?void 0:I($))}catch(I){this.ctx.raise(I)}}remove(){var $;($=this._clearDispose)==null||$.call(this),weakListeners().registry.unregister(this)}},weakListenersState=null,weakListeners=()=>(weakListenersState??(weakListenersState=new FinalizationRegistry(({event:$,listener:I})=>{var U;(U=$.deref())==null||U._removeListener(I)})),{registry:weakListenersState}),Trigger=class{constructor($={autoReset:!1}){this._options=$,this.reset()}async wait({timeout:$}={}){return $?asyncTimeout(this._promise,$,new TimeoutError($)):this._promise}wake($){return this._wake($),this._options.autoReset?this.reset():this}reset(){return this._promise=new Promise($=>{this._wake=$}),this}throw($){return this._wake(Promise.reject($)),this._options.autoReset?this.reset():this}},MulticastObservable=class Jn extends Observable{constructor(I,U){super(q=>this._subscribe(q)),this._value=U,this._observers=new Set,this._completed=new Trigger,this._handlers={next:q=>{this._value=q,this._observers.forEach(G=>{var K;return(K=G.next)==null?void 0:K.call(G,q)})},error:q=>{this._observers.forEach(G=>{var K;return(K=G.error)==null?void 0:K.call(G,q)})},complete:()=>{this._completed.wake(),this._observers.forEach(q=>{var G;return(G=q.complete)==null?void 0:G.call(q)})}},this._observable=typeof I=="function"?new Observable(I):I,this._observable.subscribe(this._handlers)}static from(I,U){if("emit"in I)return new Jn(G=>{I.on(K=>{G.next(K)})},U);const q=Observable.from(I);return new Jn(q,U)}static of(...I){return new Jn(Observable.of(...I.slice(1)),I[0])}static empty(){return EMPTY_OBSERVABLE}get(){if(this._value===void 0)throw new Error("MulticastObservable is not initialized.");return this._value}async wait({timeout:I}={}){return await this._completed.wait({timeout:I}),this.get()}forEach(I){return this._observable.forEach(I)}map(I){return new Jn(this._observable.map(I),this._value&&I(this._value))}filter(I){return new Jn(this._observable.filter(I),this._value&&I(this._value)?this._value:void 0)}reduce(I,U){return new Jn(U?this._observable.reduce(I,U):this._observable.reduce(I),U??this._value)}flatMap(I){return new Jn(this._observable.flatMap(I),this._value&&I(this._value).get())}concat(...I){return new Jn(this._observable.concat(...I),this._value)}losslessConcat(I,...U){const q=U.filter(K=>K instanceof Jn),G=I(this._value,q.map(K=>K.get()));return new Jn(this._observable.concat(...U),G)}_subscribe(I){var U;return this._observers.has(I)||this._observers.add(I),this._value!==void 0&&((U=I.next)==null||U.call(I,this._value)),()=>{this._observers.delete(I)}}},EMPTY_OBSERVABLE=MulticastObservable.of(null),Mutex=class{constructor(){this._queue=Promise.resolve(),this._tag=null}get tag(){return this._tag}async acquire($){const I=this._queue;let U;return this._queue=new Promise(q=>{U=new MutexGuard(()=>{this._tag=null,q()})}),await I,$!==void 0&&(this._tag=$),U}async executeSynchronized($){const I=await this.acquire();try{return await $()}finally{I.release()}}},MutexGuard=class{constructor($){this._release=$}release(){this._release()}[Symbol.dispose](){this.release()}},classMutexSymbol=Symbol("class-mutex"),enableWarning=globalThis.mochaExecutor,synchronized=($,I,U)=>{const q=U.value;U.value=async function(...K){const Y=this[classMutexSymbol]??(this[classMutexSymbol]=new Mutex),J=`${$.constructor.name}.${I}`;let X;enableWarning?X=await warnAfterTimeout(1e4,`lock on ${J} (taken by ${Y.tag})`,()=>Y.acquire(J)):X=await Y.acquire(J);try{return await q.apply(this,K)}finally{X.release()}},Object.defineProperty(U.value,"name",{value:I+"$synchronized"})},__dxlog_file2$6="/home/runner/work/dxos/dxos/packages/common/async/src/track-leaks.ts",enabled=typeof process<"u"&&!!process.env.DX_TRACK_LEAKS,openResources=new Set,trackResource=$=>{if(!enabled)return()=>{};const I=$();return openResources.add(I),()=>{openResources.delete(I)}},dumpLeaks=()=>{if(enabled){log$2.info(`Leaked resources ${openResources.size}:`,void 0,{F:__dxlog_file2$6,L:82,S:void 0,C:($,I)=>$(...I)});for(const $ of openResources)log$2.info(`- ${$.name} at`,void 0,{F:__dxlog_file2$6,L:84,S:void 0,C:(I,U)=>I(...U)}),log$2.info($.openStack.getStack(1),void 0,{F:__dxlog_file2$6,L:85,S:void 0,C:(I,U)=>I(...U)}),log$2.info(`
|
|
852
|
+
`,void 0,{F:__dxlog_file2$6,L:86,S:void 0,C:(I,U)=>I(...U)})}};enabled&&(global.dxDumpLeaks=dumpLeaks);var DeferredTask=class{constructor($,I){this._ctx=$,this._callback=I,this._scheduled=!1,this._promise=null}schedule(){this._scheduled||(scheduleTask(this._ctx,async()=>{await this._promise,this._scheduled=!1,this._promise=runInContextAsync(this._ctx,()=>this._callback())}),this._scheduled=!0)}},runInContextAsync=async($,I)=>{try{await I()}catch(U){$.raise(U)}},scheduleTask=($,I,U)=>{const q=trackResource(()=>({name:`task (${I.name||"anonymous"})`,openStack:new StackTrace})),G=setTimeout(async()=>{K(),await runInContextAsync($,I),q()},U),K=$.onDispose(()=>{q(),clearTimeout(G)})},scheduleTaskInterval=($,I,U)=>{const q=trackResource(()=>({name:`repeating task (${I.name||"anonymous"})`,openStack:new StackTrace}));let G;const K=async()=>{await runInContextAsync($,I),!$.disposed&&(G=setTimeout(K,U))};G=setTimeout(K,U),$.onDispose(()=>{q(),clearTimeout(G)})},__dxlog_file$7="/home/runner/work/dxos/dxos/packages/sdk/react-client/src/invitations/useInvitationStatus.ts",useInvitationStatus=$=>{const[I,U]=React.useReducer((Y,J)=>(log$2("useInvitationStatus",{action:J},{F:__dxlog_file$7,L:81,S:void 0,C:(X,Z)=>X(...Z)}),{...Y,status:J.status,result:J.status===Invitation.State.SUCCESS?J.result:Y.result,...J.status===Invitation.State.ERROR&&{error:J.error},...(J.status===Invitation.State.ERROR||J.status===Invitation.State.CANCELLED||J.status===Invitation.State.TIMEOUT)&&{haltedAt:typeof Y.haltedAt>"u"?J.haltedAt:Y.haltedAt},observable:J.status===Invitation.State.CONNECTING?J.observable??Y.observable:Y.observable}),null,Y=>({status:Invitation.State.INIT,result:{spaceKey:null,identityKey:null,swarmKey:null,target:null},observable:$}));React.useEffect(()=>{var Z,Q;const Y=ee=>{switch(ee.state){case Invitation.State.CONNECTED:case Invitation.State.READY_FOR_AUTHENTICATION:case Invitation.State.AUTHENTICATING:{U({status:ee.state});break}case Invitation.State.SUCCESS:{U({status:ee.state,result:{spaceKey:ee.spaceKey||null,identityKey:ee.identityKey||null,swarmKey:ee.swarmKey||null,target:ee.target||null}});break}case Invitation.State.CANCELLED:case Invitation.State.TIMEOUT:{U({status:ee.state,haltedAt:I.status});break}}},J=(Z=I.observable)==null?void 0:Z.subscribe(Y,ee=>{U({status:Invitation.State.ERROR,error:ee,haltedAt:I.status})}),X=(Q=I.observable)==null?void 0:Q.get();return X&&Y(X),()=>J==null?void 0:J.unsubscribe()},[I.observable,I.status]);const q=React.useCallback(Y=>{U({status:Invitation.State.CONNECTING,observable:Y})},[]),G=React.useCallback(Y=>(log$2("authenticating...",{authCode:Y},{F:__dxlog_file$7,L:165,S:void 0,C:(J,X)=>J(...X)}),I.observable.authenticate(Y)),[I.observable]),K=React.useCallback(async()=>{var Y;return(Y=I.observable)==null?void 0:Y.cancel()},[I.observable]);return React.useMemo(()=>{var X;const Y=(X=I.observable)==null?void 0:X.get();return{status:I.status,haltedAt:I.haltedAt,result:I.result,error:I.error,cancel:K,connect:q,authenticate:G,id:Y==null?void 0:Y.invitationId,multiUse:Y==null?void 0:Y.multiUse,invitationCode:Y?clientProtocol.InvitationEncoder.encode(Y):void 0,authCode:Y==null?void 0:Y.authCode,authMethod:Y==null?void 0:Y.authMethod,type:Y==null?void 0:Y.type}},[I,K,q,G])};const AuthCode=$=>{const{code:I,large:U,classNames:q}=$,G=(I==null?void 0:I.length)??0,K=I==null?void 0:I.slice(0,G/2),Y=I==null?void 0:I.slice(G/2),J=()=>{navigator.clipboard.writeText(I??"")};return React.createElement("span",{className:mx(U?"text-6xl":"text-2xl","font-mono pli-2.5 flex gap-1.5 rounded cursor-pointer",q),onClick:J},React.createElement("span",null,K),React.createElement("span",null,Y))},InvitationListItem=$=>{const{invitation:I}=$,U=useInvitationStatus(I);return React.createElement(InvitationListItemImpl,{...$,invitationStatus:U})},avatarProps={size:10,variant:"circle"},AvatarStackEffect=({animation:$,status:I,reverseEffects:U})=>{const{tx:q}=useThemeContext();return React.createElement(React.Fragment,null,React.createElement("span",{role:"none",className:mx("absolute inline-end-auto opacity-20",U?"inline-start-3":"inline-start-1",getSize(avatarProps.size))},React.createElement("span",{role:"none",className:q("avatar.ring","avatar__ring",{...avatarProps,status:I,animation:$}),style:{animationDelay:"400ms"}})),React.createElement("span",{role:"none",className:mx("absolute inline-end-auto opacity-50","inline-start-2",getSize(avatarProps.size))},React.createElement("span",{role:"none",className:q("avatar.ring","avatar__ring",{...avatarProps,status:I,animation:$}),style:{animationDelay:"200ms"}})))},InvitationListItemImpl=({invitation:$,invitationStatus:I,send:U,onClickRemove:q,createInvitationUrl:G,reverseEffects:K,...Y})=>{const{t:J}=useTranslation("os"),{cancel:X,status:Z,invitationCode:Q,authCode:ee,multiUse:te}=I,ne=!([Invitation.State.ERROR,Invitation.State.TIMEOUT,Invitation.State.CANCELLED].indexOf(Z)>=0),ie=te||[Invitation.State.INIT,Invitation.State.CONNECTING,Invitation.State.CONNECTED].indexOf(Z)>=0,oe=Z===Invitation.State.READY_FOR_AUTHENTICATION,ce=React.useCallback(()=>q==null?void 0:q($),[$,q]),fe=Q&&G(Q),se=$==null?void 0:$.get().invitationId,de=$==null?void 0:$.get().lifetime,ue=$!=null&&$.expiry?formatDistanceToNow($==null?void 0:$.expiry,{addSuffix:!0}):void 0,pe=[Invitation.State.INIT,Invitation.State.CONNECTING,Invitation.State.CONNECTED,Invitation.State.READY_FOR_AUTHENTICATION,Invitation.State.AUTHENTICATING].includes(Z)?"pulse":"none",ve=[Invitation.State.ERROR,Invitation.State.TIMEOUT,Invitation.State.CANCELLED].includes(Z),me=[Invitation.State.CONNECTED,Invitation.State.READY_FOR_AUTHENTICATION,Invitation.State.AUTHENTICATING,Invitation.State.SUCCESS].includes(Z),be=ve?"error":me?"active":"inactive";return React.createElement(ListItem.Root,{id:Q,...Y,classNames:["flex gap-2 pis-3 pie-1 items-center relative",Y.classNames]},React.createElement(ListItem.Heading,{classNames:"sr-only"},J(te?"invite many list item label":"invite one list item label")),te&&React.createElement(AvatarStackEffect,{status:be,animation:pe,reverseEffects:K}),React.createElement(Tooltip.Root,null,React.createElement(Avatar.Root,{...avatarProps,animation:pe,status:be},React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Avatar.Frame,{tabIndex:0,classNames:[focusRing,"relative rounded-full place-self-center"]},React.createElement(Avatar.Fallback,{text:hexToEmoji(se)})))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"left",classNames:"z-[70]"},J(te?"invite many qr label":"invite one qr label"),React.createElement(Tooltip.Arrow,null)))),ie&&fe?React.createElement(Tooltip.Root,null,React.createElement(React.Fragment,null,React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Button,{variant:"ghost",classNames:"grow justify-start font-medium",onClick:()=>U({type:"selectInvitation",invitation:$}),"data-testid":"show-qrcode"},React.createElement("span",null,J("open share panel label")))),React.createElement(CopyButtonIconOnly,{variant:"ghost",value:fe})),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"left",classNames:"z-[70]"},de&&React.createElement("span",null,"Expires ",ue)))):oe?React.createElement(AuthCode,{code:ee,classNames:"grow"}):Z===Invitation.State.CONNECTING?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Connecting..."):Z===Invitation.State.AUTHENTICATING?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Authenticating..."):Z===Invitation.State.ERROR||Z===Invitation.State.TIMEOUT?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Failed"):Z===Invitation.State.CANCELLED?React.createElement("span",{className:"pli-2 grow text-neutral-500"},"Cancelled"):Z===Invitation.State.SUCCESS?React.createElement("span",{className:"pli-2 grow truncate"},"User joined"):React.createElement("span",{className:"grow"}," "),ne?React.createElement(Button,{variant:"ghost",classNames:"flex gap-1 pli-0",onClick:X,"data-testid":"cancel-invitation"},React.createElement("span",{className:"sr-only"},J("cancel invitation label")),React.createElement(react.X,{className:getSize(4)})):React.createElement(Button,{variant:"ghost",classNames:"flex gap-1 pli-0",onClick:ce,"data-testid":"remove-invitation"},React.createElement("span",{className:"sr-only"},J("remove invitation label")),React.createElement(react.X,{className:getSize(4)})))},InvitationList=({invitations:$,send:I,...U})=>{const{className:q,InvitationListItem:G=InvitationListItem}=U;return React.createElement(List,{classNames:mx("flex flex-col gap-2",q)},$.map(K=>{const Y=K.get().invitationId;return React.createElement(G,{key:Y,send:I,invitation:K,...U})}))},defaultActions={noopAction:{label:"No-op",description:"",icon:react.Placeholder,onClick:()=>{}}},BifurcatedAction=React.forwardRef(($,I)=>{const{classNames:U,variant:q,isFull:G=!0,actions:K=defaultActions,activeAction:Y,onChangeActiveAction:J,defaultActiveAction:X,...Z}=$,[Q=Object.keys(K)[0],ee]=$71cd76cc60e0454e$export$6f32135080cb4c3({prop:Y,onChange:J,defaultProp:X}),te=K[Q]??{},{t:ne}=useTranslation("os");return React.createElement("div",{role:"none",className:mx("mbs-2 flex gap-px items-center",G&&"is-full")},React.createElement(Button,{...Z,classNames:["bs-11 flex-1 min-is-0 flex gap-2 rounded-ie-none",U],ref:I,variant:q,onClick:te.onClick},te.icon&&React.createElement(te.icon,{className:getSize(5)}),React.createElement("span",null,te.label)),React.createElement(DropdownMenu2.Root,null,React.createElement(DropdownMenu2.Trigger,{asChild:!0},React.createElement(Button,{classNames:["bs-11 flex-none rounded-is-none",U]},React.createElement("span",{className:"sr-only"},ne("invite options label")),React.createElement(react.CaretDown,{className:getSize(4)}))),React.createElement(DropdownMenu2.Content,null,React.createElement(DropdownMenu2.Viewport,null,Object.entries(K).map(([ie,oe])=>React.createElement(DropdownMenu2.CheckboxItem,{key:ie,"aria-labelledby":`${ie}__label`,"aria-describedby":`${ie}__description`,checked:Q===ie,onCheckedChange:ce=>ce&&ee(ie),classNames:"gap-2"},oe.icon&&React.createElement(oe.icon,{className:getSize(5)}),React.createElement("div",{role:"none",className:"flex-1 min-is-0 space-b-1"},React.createElement("p",{id:`${ie}__label`},oe.label),oe.description&&React.createElement("p",{id:`${ie}__description`,className:descriptionText},oe.description)),React.createElement(DropdownMenu2.ItemIndicator,{asChild:!0},React.createElement(react.Check,{weight:"bold",className:getSize(4)}))))),React.createElement(DropdownMenu2.Arrow,null))))}),Action=React.forwardRef(($,I)=>{const{children:U,classNames:q,variant:G,isFull:K=!0,...Y}=$;return React.createElement(Button,{...Y,classNames:[K&&"is-full","bs-11 flex gap-2 mbs-2",q],ref:I,variant:G},U)}),Actions=React.forwardRef(({classNames:$,children:I,...U},q)=>React.createElement("div",{...U,className:mx("flex flex-col gap-2 mbs-2",Array.isArray(I)&&I.length>1?"justify-between":"justify-center",$),ref:q},I)),CloseButton=({onDone:$,...I})=>{const{t:U}=useTranslation("os");return React.createElement(Button,{variant:"ghost",classNames:mx("plb-0 pli-2 absolute block-start-0 inline-end-0 z-[1]"),onClick:()=>$==null?void 0:$(),...I},React.createElement(react.X,{weight:"bold",className:getSize(4)}),React.createElement("span",{className:"sr-only"},U("exit label")))},Emoji=({text:$,className:I})=>React.createElement("div",{role:"none",className:mx(getSize(14),"rounded relative pointer-events-none",I)},React.createElement("svg",{viewBox:`0 0 ${14*4} ${14*4}`,width:14*4,height:14*4},React.createElement("text",{x:"50%",y:"50%",textAnchor:"middle",dominantBaseline:"middle",baselineShift:"-0.25rem",fontSize:"2.25rem"},$))),Centered=$=>{const{children:I}=$;return React.createElement("div",{role:"none",className:"absolute inset-0 flex items-center justify-center"},I)},Heading=React.forwardRef(({titleId:$,title:I,titleSrOnly:U,children:q,corner:G},K)=>React.createElement("div",{role:"none",className:"pbe-2 relative",ref:K},G,React.createElement("h1",{...!U&&{id:$},className:mx(descriptionText,"text-center mlb-2",U&&"invisible")},I),U&&React.createElement("span",{id:$},I),q)),Label=$=>{const{children:I}=$;return React.createElement("span",{className:mx(descriptionText,"text-center mli-6 whitespace-normal")},I)},Input=({validationMessage:$,label:I,...U})=>React.createElement(Input$1.Root,null,React.createElement(Input$1.Label,null,I),React.createElement(Input$1.TextInput,{...U,classNames:"plb-3 mbs-2 text-center"}),React.createElement(Input$1.DescriptionAndValidation,null,$&&React.createElement(Input$1.Validation,null,$))),StepHeading=React.forwardRef(({children:$,className:I,...U},q)=>React.createElement("h2",{...U,className:mx("font-normal text-sm mbe-4 mli-1 text-center",I),ref:q},$));/*!
|
|
853
853
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
854
854
|
* Licensed under the MIT License.
|
|
855
855
|
*/const TabsterAttributeName="data-tabster",TabsterDummyInputAttributeName="data-tabster-dummy",FocusInEventName="tabster:focusin",FocusOutEventName="tabster:focusout",MoveFocusEventName="tabster:movefocus",FocusableSelector=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","*[tabindex]","*[contenteditable]"].join(", "),SysDummyInputsPositions={Auto:0,Inside:1,Outside:2};/*!
|
|
@@ -904,12 +904,12 @@ button {
|
|
|
904
904
|
`;)pe++;return pe}function oe(){if(J.length>0)return J.shift();if(X)return Q();var ue,pe,ve,me,be,_e=U===0;do{if(U===q)return null;for(ue=!1;whitespaceRe.test(ve=ee(U));)if(ve===`
|
|
905
905
|
`&&(_e=!0,++G),++U===q)return null;if(ee(U)==="/"){if(++U===q)throw Z("comment");if(ee(U)==="/")if(I){if(me=U,be=!1,ne(U)){be=!0;do if(U=ie(U),U===q||(U++,!_e))break;while(ne(U))}else U=Math.min(q,ie(U)+1);be&&(te(me,U,_e),_e=!0),G++,ue=!0}else{for(be=ee(me=U+1)==="/";ee(++U)!==`
|
|
906
906
|
`;)if(U===q)return null;++U,be&&(te(me,U-1,_e),_e=!0),++G,ue=!0}else if((ve=ee(U))==="*"){me=U+1,be=I||ee(me)==="*";do{if(ve===`
|
|
907
|
-
`&&++G,++U===q)throw Z("comment");pe=ve,ve=ee(U)}while(pe!=="*"||ve!=="/");++U,be&&(te(me,U-2,_e),_e=!0),ue=!0}else return"/"}}while(ue);var Se=U;delimRe.lastIndex=0;var xe=delimRe.test(ee(Se++));if(!xe)for(;Se<q&&!delimRe.test(ee(Se));)++Se;var ke=$.substring(U,U=Se);return(ke==='"'||ke==="'")&&(X=ke),ke}function ce(ue){J.push(ue)}function fe(){if(!J.length){var ue=oe();if(ue===null)return null;ce(ue)}return J[0]}function se(ue,pe){var ve=fe(),me=ve===ue;if(me)return oe(),!0;if(!pe)throw Z("token '"+ve+"', '"+ue+"' expected");return!1}function de(ue){var pe=null,ve;return ue===void 0?(ve=Y[G-1],delete Y[G-1],ve&&(I||ve.type==="*"||ve.lineEmpty)&&(pe=ve.leading?ve.text:null)):(K<ue&&fe(),ve=Y[ue],delete Y[ue],ve&&!ve.lineEmpty&&(I||ve.type==="/")&&(pe=ve.leading?null:ve.text)),pe}return Object.defineProperty({next:oe,peek:fe,push:ce,skip:se,cmnt:de},"line",{get:function(){return G}})}var parse_1=parse;parse.filename=null,parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,fqTypeRefRe=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function parse($,I,U){I instanceof Root||(U=I,I=new Root),U||(U=parse.defaults);var q=U.preferTrailingComment||!1,G=tokenize($,U.alternateCommentMode||!1),K=G.next,Y=G.push,J=G.peek,X=G.skip,Z=G.cmnt,Q=!0,ee,te,ne,ie,oe=!1,ce=I,fe=U.keepCase?function(Re){return Re}:util.camelCase;function se(Re,Ce,ge){var ye=parse.filename;return ge||(parse.filename=null),Error("illegal "+(Ce||"token")+" '"+Re+"' ("+(ye?ye+", ":"")+"line "+G.line+")")}function de(){var Re=[],Ce;do{if((Ce=K())!=='"'&&Ce!=="'")throw se(Ce);Re.push(K()),X(Ce),Ce=J()}while(Ce==='"'||Ce==="'");return Re.join("")}function ue(Re){var Ce=K();switch(Ce){case"'":case'"':return Y(Ce),de();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return ve(Ce,!0)}catch{if(Re&&typeRefRe.test(Ce))return Ce;throw se(Ce,"value")}}function pe(Re,Ce){var ge,ye;do Ce&&((ge=J())==='"'||ge==="'")?Re.push(de()):Re.push([ye=me(K()),X("to",!0)?me(K()):ye]);while(X(",",!0));X(";")}function ve(Re,Ce){var ge=1;switch(Re.charAt(0)==="-"&&(ge=-1,Re=Re.substring(1)),Re){case"inf":case"INF":case"Inf":return ge*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(Re))return ge*parseInt(Re,10);if(base16Re.test(Re))return ge*parseInt(Re,16);if(base8Re.test(Re))return ge*parseInt(Re,8);if(numberRe.test(Re))return ge*parseFloat(Re);throw se(Re,"number",Ce)}function me(Re,Ce){switch(Re){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!Ce&&Re.charAt(0)==="-")throw se(Re,"id");if(base10NegRe.test(Re))return parseInt(Re,10);if(base16NegRe.test(Re))return parseInt(Re,16);if(base8NegRe.test(Re))return parseInt(Re,8);throw se(Re,"id")}function be(){if(ee!==void 0)throw se("package");if(ee=K(),!typeRefRe.test(ee))throw se(ee,"name");ce=ce.define(ee),X(";")}function _e(){var Re=J(),Ce;switch(Re){case"weak":Ce=ne||(ne=[]),K();break;case"public":K();default:Ce=te||(te=[]);break}Re=de(),X(";"),Ce.push(Re)}function Se(){if(X("="),ie=de(),oe=ie==="proto3",!oe&&ie!=="proto2")throw se(ie,"syntax");X(";")}function xe(Re,Ce){switch(Ce){case"option":return ut(Re,Ce),X(";"),!0;case"message":return De(Re,Ce),!0;case"enum":return ft(Re,Ce),!0;case"service":return vt(Re,Ce),!0;case"extend":return ze(Re,Ce),!0}return!1}function ke(Re,Ce,ge){var ye=G.line;if(Re&&(typeof Re.comment!="string"&&(Re.comment=Z()),Re.filename=parse.filename),X("{",!0)){for(var Me;(Me=K())!=="}";)Ce(Me);X(";",!0)}else ge&&ge(),X(";"),Re&&(typeof Re.comment!="string"||q)&&(Re.comment=Z(ye)||Re.comment)}function De(Re,Ce){if(!nameRe.test(Ce=K()))throw se(Ce,"type name");var ge=new Type(Ce);ke(ge,function(Me){if(!xe(ge,Me))switch(Me){case"map":nt(ge);break;case"required":case"repeated":Be(ge,Me);break;case"optional":oe?Be(ge,"proto3_optional"):Be(ge,"optional");break;case"oneof":ot(ge,Me);break;case"extensions":pe(ge.extensions||(ge.extensions=[]));break;case"reserved":pe(ge.reserved||(ge.reserved=[]),!0);break;default:if(!oe||!typeRefRe.test(Me))throw se(Me);Y(Me),Be(ge,"optional");break}}),Re.add(ge)}function Be(Re,Ce,ge){var ye=K();if(ye==="group"){Ve(Re,Ce);return}if(!typeRefRe.test(ye))throw se(ye,"type");var Me=K();if(!nameRe.test(Me))throw se(Me,"name");Me=fe(Me),X("=");var Ke=new Field(Me,me(K()),ye,Ce,ge);if(ke(Ke,function($t){if($t==="option")ut(Ke,$t),X(";");else throw se($t)},function(){tt(Ke)}),Ce==="proto3_optional"){var st=new OneOf("_"+Me);Ke.setOption("proto3_optional",!0),st.add(Ke),Re.add(st)}else Re.add(Ke);!oe&&Ke.repeated&&(types.packed[ye]!==void 0||types.basic[ye]===void 0)&&Ke.setOption("packed",!1,!0)}function Ve(Re,Ce){var ge=K();if(!nameRe.test(ge))throw se(ge,"name");var ye=util.lcFirst(ge);ge===ye&&(ge=util.ucFirst(ge)),X("=");var Me=me(K()),Ke=new Type(ge);Ke.group=!0;var st=new Field(ye,Me,ge,Ce);st.filename=parse.filename,ke(Ke,function($t){switch($t){case"option":ut(Ke,$t),X(";");break;case"required":case"repeated":Be(Ke,$t);break;case"optional":oe?Be(Ke,"proto3_optional"):Be(Ke,"optional");break;case"message":De(Ke,$t);break;case"enum":ft(Ke,$t);break;default:throw se($t)}}),Re.add(Ke).add(st)}function nt(Re){X("<");var Ce=K();if(types.mapKey[Ce]===void 0)throw se(Ce,"type");X(",");var ge=K();if(!typeRefRe.test(ge))throw se(ge,"type");X(">");var ye=K();if(!nameRe.test(ye))throw se(ye,"name");X("=");var Me=new MapField(fe(ye),me(K()),Ce,ge);ke(Me,function(st){if(st==="option")ut(Me,st),X(";");else throw se(st)},function(){tt(Me)}),Re.add(Me)}function ot(Re,Ce){if(!nameRe.test(Ce=K()))throw se(Ce,"name");var ge=new OneOf(fe(Ce));ke(ge,function(Me){Me==="option"?(ut(ge,Me),X(";")):(Y(Me),Be(ge,"optional"))}),Re.add(ge)}function ft(Re,Ce){if(!nameRe.test(Ce=K()))throw se(Ce,"name");var ge=new Enum(Ce);ke(ge,function(Me){switch(Me){case"option":ut(ge,Me),X(";");break;case"reserved":pe(ge.reserved||(ge.reserved=[]),!0);break;default:it(ge,Me)}}),Re.add(ge)}function it(Re,Ce){if(!nameRe.test(Ce))throw se(Ce,"name");X("=");var ge=me(K(),!0),ye={options:void 0};ye.setOption=function(Me,Ke){this.options===void 0&&(this.options={}),this.options[Me]=Ke},ke(ye,function(Ke){if(Ke==="option")ut(ye,Ke),X(";");else throw se(Ke)},function(){tt(ye)}),Re.add(Ce,ge,ye.comment,ye.options)}function ut(Re,Ce){var ge=X("(",!0);if(!typeRefRe.test(Ce=K()))throw se(Ce,"name");var ye=Ce,Me=ye,Ke;ge&&(X(")"),ye="("+ye+")",Me=ye,Ce=J(),fqTypeRefRe.test(Ce)&&(Ke=Ce.slice(1),ye+=Ce,K())),X("=");var st=et(Re,ye);We(Re,Me,st,Ke)}function et(Re,Ce){if(X("{",!0)){for(var ge={};!X("}",!0);){if(!nameRe.test(Ae=K()))throw se(Ae,"name");var ye,Me=Ae;if(X(":",!0),J()==="{")ye=et(Re,Ce+"."+Ae);else if(J()==="["){ye=[];var Ke;if(X("[",!0)){do Ke=ue(!0),ye.push(Ke);while(X(",",!0));X("]"),typeof Ke<"u"&&Ue(Re,Ce+"."+Ae,Ke)}}else ye=ue(!0),Ue(Re,Ce+"."+Ae,ye);var st=ge[Me];st&&(ye=[].concat(st).concat(ye)),ge[Me]=ye,X(",",!0),X(";",!0)}return ge}var dt=ue(!0);return Ue(Re,Ce,dt),dt}function Ue(Re,Ce,ge){Re.setOption&&Re.setOption(Ce,ge)}function We(Re,Ce,ge,ye){Re.setParsedOption&&Re.setParsedOption(Ce,ge,ye)}function tt(Re){if(X("[",!0)){do ut(Re,"option");while(X(",",!0));X("]")}return Re}function vt(Re,Ce){if(!nameRe.test(Ce=K()))throw se(Ce,"service name");var ge=new Service(Ce);ke(ge,function(Me){if(!xe(ge,Me))if(Me==="rpc")je(ge,Me);else throw se(Me)}),Re.add(ge)}function je(Re,Ce){var ge=Z(),ye=Ce;if(!nameRe.test(Ce=K()))throw se(Ce,"name");var Me=Ce,Ke,st,dt,$t;if(X("("),X("stream",!0)&&(st=!0),!typeRefRe.test(Ce=K())||(Ke=Ce,X(")"),X("returns"),X("("),X("stream",!0)&&($t=!0),!typeRefRe.test(Ce=K())))throw se(Ce);dt=Ce,X(")");var Et=new Method(Me,ye,Ke,dt,st,$t);Et.comment=ge,ke(Et,function(jt){if(jt==="option")ut(Et,jt),X(";");else throw se(jt)}),Re.add(Et)}function ze(Re,Ce){if(!typeRefRe.test(Ce=K()))throw se(Ce,"reference");var ge=Ce;ke(null,function(Me){switch(Me){case"required":case"repeated":Be(Re,Me,ge);break;case"optional":oe?Be(Re,"proto3_optional",ge):Be(Re,"optional",ge);break;default:if(!oe||!typeRefRe.test(Me))throw se(Me);Y(Me),Be(Re,"optional",ge);break}})}for(var Ae;(Ae=K())!==null;)switch(Ae){case"package":if(!Q)throw se(Ae);be();break;case"import":if(!Q)throw se(Ae);_e();break;case"syntax":if(!Q)throw se(Ae);Se();break;case"option":ut(ce,Ae),X(";");break;default:if(xe(ce,Ae)){Q=!1;continue}throw se(Ae)}return parse.filename=null,{package:ee,imports:te,weakImports:ne,syntax:ie,root:I}}var common_1=common$1,commonRe=/\/|\./;function common$1($,I){commonRe.test($)||($="google/protobuf/"+$+".proto",I={nested:{google:{nested:{protobuf:{nested:I}}}}}),common$1[$]=I}common$1("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common$1("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),common$1("timestamp",{Timestamp:timeType}),common$1("empty",{Empty:{fields:{}}}),common$1("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),common$1("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),common$1("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),common$1.get=function $(I){return common$1[I]||null};var protobuf=indexLightExports;protobuf.build="full",protobuf.tokenize=tokenize_1,protobuf.parse=parse_1,protobuf.common=common_1,protobuf.Root._configure(protobuf.Type,protobuf.parse,protobuf.common);var dist$1={},core={},debug$1={};Object.defineProperty(debug$1,"__esModule",{value:!0});function getType($){return Object.prototype.toString.call($)}debug$1.getType=getType;function throwUnknownDataType($){throw new TypeError("unsupported data type: "+getType($))}debug$1.throwUnknownDataType=throwUnknownDataType;var encode$1={},number={};Object.defineProperty(number,"__esModule",{value:!0});let i_to_s="";for(let $=0;$<10;$++){const I=String.fromCharCode(48+$);i_to_s+=I}for(let $=0;$<26;$++){const I=String.fromCharCode(65+$);i_to_s+=I}for(let $=0;$<26;$++){const I=String.fromCharCode(97+$);i_to_s+=I}const N=i_to_s.length,s_to_i={};for(let $=0;$<N;$++){const I=i_to_s[$];s_to_i[I]=$}function s_to_int($){let I=0,U=1;for(let q=$.length-1;q>=0;q--){const G=$[q];let K=s_to_i[G];K*=U,I+=K,U*=N}return I}number.s_to_int=s_to_int;function s_to_big_int($){let I=BigInt(0),U=BigInt(1);const q=BigInt(N);for(let G=$.length-1;G>=0;G--){const K=$[G];let Y=BigInt(s_to_i[K]);Y*=U,I+=Y,U*=q}return I}number.s_to_big_int=s_to_big_int;function int_to_s($){if($===0)return i_to_s[0];const I=[];for(;$!==0;){const U=$%N,q=i_to_s[U];I.push(q),$-=U,$/=N}return I.reverse().join("")}number.int_to_s=int_to_s;function big_int_to_s($){const I=BigInt(0),U=BigInt(N);if($===I)return i_to_s[0];const q=[];for(;$!==I;){const G=$%U,K=i_to_s[Number(G)];q.push(K),$-=G,$/=U}return q.reverse().join("")}number.big_int_to_s=big_int_to_s;function reverse($){return $.split("").reverse().join("")}function num_to_s($){if($<0)return"-"+num_to_s(-$);let[I,U]=$.toString().split(".");if(!U)return int_to_s($);let q;U&&([U,q]=U.split("e")),I=int_str_to_s(I),U=reverse(U),U=int_str_to_s(U);let G=I+"."+U;if(q){switch(G+=".",q[0]){case"+":q=q.slice(1);break;case"-":G+="-",q=q.slice(1);break}q=reverse(q),q=int_str_to_s(q),G+=q}return G}number.num_to_s=num_to_s;function int_str_to_s($){const I=+$;return I.toString()===$?int_to_s(I):":"+big_int_to_s(BigInt($))}number.int_str_to_s=int_str_to_s;function s_to_int_str($){return $[0]===":"?s_to_big_int($.substring(1)).toString():s_to_int($).toString()}function s_to_num($){if($[0]==="-")return-s_to_num($.substr(1));let[I,U,q]=$.split(".");if(!U)return s_to_int(I);I=s_to_int_str(I),U=s_to_int_str(U),U=reverse(U);let G=I+"."+U;if(q){G+="e";let K=!1;q[0]==="-"&&(K=!0,q=q.slice(1)),q=s_to_int_str(q),q=reverse(q),G+=K?-q:+q}return+G}number.s_to_num=s_to_num,Object.defineProperty(encode$1,"__esModule",{value:!0});const number_1$1=number;function encodeNum($){return"n|"+number_1$1.num_to_s($)}encode$1.encodeNum=encodeNum;function decodeNum($){return $=$.replace("n|",""),number_1$1.s_to_num($)}encode$1.decodeNum=decodeNum;function decodeKey($){return typeof $=="number"?$:number_1$1.s_to_int($)}encode$1.decodeKey=decodeKey;function encodeBool($){return $?"b|T":"b|F"}encode$1.encodeBool=encodeBool;function decodeBool($){switch($){case"b|T":return!0;case"b|F":return!1}return!!$}encode$1.decodeBool=decodeBool;function encodeStr($){switch($[0]+$[1]){case"b|":case"o|":case"n|":case"a|":case"s|":$="s|"+$}return $}encode$1.encodeStr=encodeStr;function decodeStr($){return $[0]+$[1]==="s|"?$.substr(2):$}encode$1.decodeStr=decodeStr;var memory={},config={};Object.defineProperty(config,"__esModule",{value:!0}),config.config={sort_key:!1},Object.defineProperty(memory,"__esModule",{value:!0});const config_1=config,debug_1$1=debug$1,encode_1$2=encode$1,number_1=number;function memToValues($){return $.store.toArray()}memory.memToValues=memToValues;function makeInMemoryStore(){const $=[];return{forEach(I){for(let U=0;U<$.length;U++)if(I($[U])==="break")return},add(I){$.push(I)},toArray(){return $}}}memory.makeInMemoryStore=makeInMemoryStore;function makeInMemoryCache(){const $=Object.create(null),I=Object.create(null);return{getValue(U){return $[U]},getSchema(U){return I[U]},forEachValue(U){for(const[q,G]of Object.entries($))if(U(q,G)==="break")return},forEachSchema(U){for(const[q,G]of Object.entries(I))if(U(q,G)==="break")return},setValue(U,q){$[U]=q},setSchema(U,q){I[U]=q},hasValue(U){return U in $},hasSchema(U){return U in I}}}memory.makeInMemoryCache=makeInMemoryCache;function makeInMemoryMemory(){return{store:makeInMemoryStore(),cache:makeInMemoryCache(),keyCount:0}}memory.makeInMemoryMemory=makeInMemoryMemory;function getValueKey($,I){if($.cache.hasValue(I))return $.cache.getValue(I);const U=$.keyCount++,q=number_1.num_to_s(U);return $.store.add(I),$.cache.setValue(I,q),q}function getSchema($,I){config_1.config.sort_key&&I.sort();const U=I.join(",");if($.cache.hasSchema(U))return $.cache.getSchema(U);const q=addValue($,I,void 0);return $.cache.setSchema(U,q),q}function addValue($,I,U){if(I===null)return"";switch(typeof I){case"undefined":if(Array.isArray(U))return addValue($,null,U);break;case"object":if(I===null)return getValueKey($,null);if(Array.isArray(I)){let q="a";for(let G=0;G<I.length;G++){const K=I[G],Y=K===null?"_":addValue($,K,I);q+="|"+Y}return q==="a"&&(q="a|"),getValueKey($,q)}else{const q=Object.keys(I);if(q.length===0)return getValueKey($,"o|");let G="o";const K=getSchema($,q);G+="|"+K;for(const Y of q){const J=I[Y],X=addValue($,J,I);G+="|"+X}return getValueKey($,G)}case"boolean":return getValueKey($,encode_1$2.encodeBool(I));case"number":return getValueKey($,encode_1$2.encodeNum(I));case"string":return getValueKey($,encode_1$2.encodeStr(I))}return debug_1$1.throwUnknownDataType(I)}memory.addValue=addValue,Object.defineProperty(core,"__esModule",{value:!0});const debug_1=debug$1,encode_1$1=encode$1,memory_1$1=memory;function compress($){const I=memory_1$1.makeInMemoryMemory(),U=memory_1$1.addValue(I,$,void 0);return[memory_1$1.memToValues(I),U]}core.compress=compress;function decodeObject($,I){if(I==="o|")return{};const U={},q=I.split("|"),G=q[1];let K=decode$1($,G);const Y=q.length;Y-2===1&&!Array.isArray(K)&&(K=[K]);for(let J=2;J<Y;J++){const X=K[J-2];let Z=q[J];Z=decode$1($,Z),U[X]=Z}return U}function decodeArray($,I){if(I==="a|")return[];const U=I.split("|"),q=U.length-1,G=new Array(q);for(let K=0;K<q;K++){let Y=U[K+1];Y=decode$1($,Y),G[K]=Y}return G}function decode$1($,I){if(I===""||I==="_")return null;const U=encode_1$1.decodeKey(I),q=$[U];if(q===null)return q;switch(typeof q){case"undefined":return q;case"number":return q;case"string":switch(q[0]+q[1]){case"b|":return encode_1$1.decodeBool(q);case"o|":return decodeObject($,q);case"n|":return encode_1$1.decodeNum(q);case"a|":return decodeArray($,q);default:return encode_1$1.decodeStr(q)}}return debug_1.throwUnknownDataType(q)}core.decode=decode$1;function decompress($){const[I,U]=$;return decode$1(I,U)}core.decompress=decompress;var helpers={};Object.defineProperty(helpers,"__esModule",{value:!0});function trimUndefined($){for(const I in $)$[I]===void 0&&delete $[I]}helpers.trimUndefined=trimUndefined;function trimUndefinedRecursively($){trimUndefinedRecursivelyLoop($,new Set)}helpers.trimUndefinedRecursively=trimUndefinedRecursively;function trimUndefinedRecursivelyLoop($,I){I.add($);for(const U in $)if($[U]===void 0)delete $[U];else{const q=$[U];q&&typeof q=="object"&&!I.has(q)&&trimUndefinedRecursivelyLoop(q,I)}}Object.defineProperty(dist$1,"__esModule",{value:!0});var core_1=core;dist$1.compress=core_1.compress,dist$1.decompress=core_1.decompress;var core_2=core;dist$1.decode=core_2.decode;var memory_1=memory;dist$1.addValue=memory_1.addValue;var helpers_1=helpers;dist$1.trimUndefined=helpers_1.trimUndefined,dist$1.trimUndefinedRecursively=helpers_1.trimUndefinedRecursively;var __dxlog_file3$4="/home/runner/work/dxos/dxos/packages/common/codec-protobuf/src/stream.ts",Stream$1=class lr{constructor(I){this._messageHandler=void 0,this._closeHandler=void 0,this._readyHandler=void 0,this._isClosed=!1,this._closeError=void 0,this._producerCleanup=void 0,this._isReady=!1,this._buffer=[],this._readyPromise=new Promise(U=>{this._resolveReadyPromise=U}),this._ctx=new Context({onError:U=>{var q,G;this._isClosed||(this._isClosed=!0,this._closeError=U,(q=this._producerCleanup)==null||q.call(this,U),(G=this._closeHandler)==null||G.call(this,U),this._ctx.dispose())}}),this._ctx.onDispose(()=>this.close());try{const U=I({ctx:this._ctx,ready:()=>{this._markAsReady()},next:q=>{if(this._isClosed){log$2("Stream is closed, dropping message.",void 0,{F:__dxlog_file3$4,L:207,S:this,C:(G,K)=>G(...K)});return}if(this._markAsReady(),this._messageHandler)try{this._messageHandler(q)}catch(G){throwUnhandledRejection(G)}else invariant(this._buffer,void 0,{F:__dxlog_file3$4,L:221,S:this,A:["this._buffer",""]}),this._buffer.push(q)},close:q=>{var G,K;if(!this._isClosed){this._isClosed=!0,this._closeError=q,(G=this._producerCleanup)==null||G.call(this,q);try{(K=this._closeHandler)==null||K.call(this,q)}catch(Y){throwUnhandledRejection(Y)}this._ctx.dispose()}}});U&&(this._producerCleanup=U)}catch(U){this._ctx.raise(U)}}static consume(I){return new Promise(U=>{const q=[];I.onReady(()=>{q.push({ready:!0})}),I.subscribe(G=>{q.push({data:G})},G=>{G?q.push({closed:!0,error:G}):q.push({closed:!0}),U(q)})})}static async consumeData(I){const U=await lr.consume(I),q=[];for(const G of U)if("data"in G)q.push(G.data);else if("closed"in G&&G.closed===!0){if(G.error)throw G.error;break}return q}static async first(I){return new Promise((U,q)=>{I.subscribe(G=>{U(G),I.close()},G=>{G?q(G):U(void 0)})})}static map(I,U){return new lr(({ready:q,next:G,close:K})=>(I.onReady(q),I.subscribe(Y=>G(U(Y)),K),()=>I.close()))}static unwrapPromise(I){return I instanceof lr?I:new lr(({ready:U,next:q,close:G})=>(I.then(K=>{K.onReady(U),K.subscribe(q,G)},K=>{G(K)}),()=>{I.then(K=>K.close(),K=>{})}))}_markAsReady(){var I;this._isReady||(this._isReady=!0,(I=this._readyHandler)==null||I.call(this),this._resolveReadyPromise())}subscribe(I,U){invariant(!this._messageHandler,"Stream is already subscribed to.",{F:__dxlog_file3$4,L:262,S:this,A:["!this._messageHandler","'Stream is already subscribed to.'"]}),invariant(!this._closeHandler,"Stream is already subscribed to.",{F:__dxlog_file3$4,L:263,S:this,A:["!this._closeHandler","'Stream is already subscribed to.'"]}),invariant(this._buffer,void 0,{F:__dxlog_file3$4,L:264,S:this,A:["this._buffer",""]});for(const q of this._buffer)try{I(q)}catch(G){throwUnhandledRejection(G)}if(this._buffer=null,this._isClosed){U==null||U(this._closeError);return}this._messageHandler=I,this._closeHandler=U}waitUntilReady(){return this._readyPromise}onReady(I){invariant(!this._readyHandler,"Stream already has a handler for the ready event.",{F:__dxlog_file3$4,L:299,S:this,A:["!this._readyHandler","'Stream already has a handler for the ready event.'"]}),this._readyHandler=I,this._isReady&&I()}async close(){var I,U;this._isClosed||(this._isClosed=!0,(I=this._producerCleanup)==null||I.call(this),(U=this._closeHandler)==null||U.call(this,void 0),await this._ctx.dispose(),this._messageHandler=void 0,this._closeHandler=void 0,this._producerCleanup=void 0)}},throwUnhandledRejection=$=>{setTimeout(()=>{throw $})},symbolTracingContext=Symbol("dxos.tracing.context"),getTracingContext=$=>$[symbolTracingContext]??($[symbolTracingContext]={infoProperties:{},metricsProperties:{}}),TRACE_SPAN_ATTRIBUTE="dxos.trace-span",TraceSender=class{constructor($){this._traceProcessor=$}streamTrace($){return new Stream$1(({ctx:I,next:U})=>{const q=(Y,J,X)=>{const Z={resourceAdded:[],resourceRemoved:[],spanAdded:[],logAdded:[]};if(Y)for(const Q of Y){const ee=this._traceProcessor.resources.get(Q);ee?Z.resourceAdded.push({resource:ee.data}):Z.resourceRemoved.push({id:Q})}else for(const Q of this._traceProcessor.resources.values())Z.resourceAdded.push({resource:Q.data});if(J)for(const Q of J){const ee=this._traceProcessor.spans.get(Q);ee&&Z.spanAdded.push({span:ee})}else for(const Q of this._traceProcessor.spans.values())Z.spanAdded.push({span:Q});if(X)for(const Q of X)Z.logAdded.push({log:Q});else for(const Q of this._traceProcessor.logs)Z.logAdded.push({log:Q});(Z.resourceAdded.length>0||Z.resourceRemoved.length>0||Z.spanAdded.length>0)&&U(Z)},K={flush:()=>{q(K.dirtyResources,K.dirtySpans,K.newLogs),K.dirtyResources.clear(),K.dirtySpans.clear(),K.newLogs.length=0},dirtyResources:new Set,dirtySpans:new Set,newLogs:[]};this._traceProcessor.subscriptions.add(K),I.onDispose(()=>{this._traceProcessor.subscriptions.delete(K)}),q(null,null,null)})}},__dxlog_file$6="/home/runner/work/dxos/dxos/packages/common/tracing/src/trace-processor.ts",ResourceEntry=class{constructor($,I,U){this.data=$,this.instance=I,this.annotation=U,this.sanitizedClassName=sanitizeClassName($.className)}getMetric($){var I;return(I=this.data.metrics)==null?void 0:I.find(U=>U.name===$)}},MAX_RESOURCE_RECORDS=2e3,MAX_SPAN_RECORDS=1e3,MAX_LOG_RECORDS=1e3,REFRESH_INTERVAL=1e3,MAX_INFO_OBJECT_DEPTH=8,TraceProcessor=class{constructor(){this.resources=new Map,this.resourceInstanceIndex=new WeakMap,this.resourceIdList=[],this.spans=new Map,this.spanIdList=[],this.logs=[],this.subscriptions=new Set,this._logProcessor=(I,U)=>{var q,G,K;switch(U.level){case LogLevel$1.ERROR:case LogLevel$1.WARN:case LogLevel$1.TRACE:{const Y=(q=U.meta)==null?void 0:q.S,J=this.resourceInstanceIndex.get(Y);if(!J)return;const X=getContextFromEntry(U)??{};for(const Q of Object.keys(X))X[Q]=sanitizeValue(X[Q],0,this);const Z={level:U.level,message:U.message,context:X,timestamp:new Date,meta:{file:((G=U.meta)==null?void 0:G.F)??"",line:((K=U.meta)==null?void 0:K.L)??0,resourceId:J.data.id}};this._pushLog(Z);break}}},log$2.addProcessor(this._logProcessor.bind(this),void 0,{F:__dxlog_file$6,L:81,S:this,C:(I,U)=>I(...U)});const $=setInterval(this.refresh.bind(this),REFRESH_INTERVAL);unrefTimeout($)}traceResourceConstructor($){const I=this.resources.size,U=getTracingContext(Object.getPrototypeOf($.instance));for(const G of Object.keys(U.metricsProperties))$.instance[G]._assign($.instance,G);const q=new ResourceEntry({id:I,className:$.constructor.name,instanceId:getPrototypeSpecificInstanceId($.instance),info:this.getResourceInfo($.instance),links:[],metrics:this.getResourceMetrics($.instance)},new WeakRef($.instance),$.annotation);this.resources.set(I,q),this.resourceInstanceIndex.set($.instance,q),this.resourceIdList.push(I),this.resourceIdList.length>MAX_RESOURCE_RECORDS&&this._clearResources(),this._markResourceDirty(I)}getResourceInfo($){const I={},U=getTracingContext(Object.getPrototypeOf($));for(const[q,{options:G}]of Object.entries(U.infoProperties))try{const K=typeof $[q]=="function"?$[q]():$[q];G.enum?I[q]=G.enum[K]:I[q]=sanitizeValue(K,G.depth===void 0?1:G.depth??MAX_INFO_OBJECT_DEPTH,this)}catch(K){I[q]=K.message}return I}getResourceMetrics($){const I=[],U=getTracingContext(Object.getPrototypeOf($));for(const[q,G]of Object.entries(U.metricsProperties))I.push($[q].getData());return I}traceSpan($){const I=new TracingSpan(this,$);return this._flushSpan(I),I}addLink($,I,U){}getResourceId($){const I=this.resourceInstanceIndex.get($);return I?I.data.id:null}createTraceSender(){return new TraceSender(this)}refresh(){var $,I;for(const U of this.resources.values()){const q=U.instance.deref();if(!q)continue;const G=getTracingContext(Object.getPrototypeOf(q)),K=performance.now();for(const Z of Object.keys(G.metricsProperties))(I=($=q[Z])._tick)==null||I.call($,K);let Y=!1;const J=U.data.info;U.data.info=this.getResourceInfo(q),Y||(Y=!areEqualShallow(J,U.data.info));const X=U.data.metrics;U.data.metrics=this.getResourceMetrics(q),Y||(Y=!areEqualShallow(X,U.data.metrics)),this._markResourceDirty(U.data.id)}for(const U of this.subscriptions)U.flush()}findResourcesByClassName($){return[...this.resources.values()].filter(I=>I.data.className===$||I.sanitizedClassName===$)}findByAnnotation($){return[...this.resources.values()].filter(I=>I.annotation===$)}getDiagnostics(){return this.refresh(),{resources:Object.fromEntries(Array.from(this.resources.entries()).map(([$,I])=>[`${I.sanitizedClassName}#${I.data.instanceId}`,I.data])),spans:Array.from(this.spans.values()),logs:this.logs.filter($=>$.level>=LogLevel$1.INFO)}}_flushSpan($){const I=$.serialize();this.spans.set(I.id,I),this.spanIdList.push(I.id),this.spanIdList.length>MAX_SPAN_RECORDS&&this._clearSpans(),this._markSpanDirty(I.id)}_markResourceDirty($){for(const I of this.subscriptions)I.dirtyResources.add($)}_markSpanDirty($){for(const I of this.subscriptions)I.dirtySpans.add($)}_clearResources(){for(;this.resourceIdList.length>MAX_RESOURCE_RECORDS;){const $=this.resourceIdList.shift();this.resources.delete($)}}_clearSpans(){for(;this.spanIdList.length>MAX_SPAN_RECORDS;){const $=this.spanIdList.shift();this.spans.delete($)}}_pushLog($){this.logs.push($),this.logs.length>MAX_LOG_RECORDS&&this.logs.shift();for(const I of this.subscriptions)I.newLogs.push($)}},TracingSpan=(Xn=class{constructor(I,U){if(this._traceProcessor=I,this.parentId=null,this.resourceId=null,this.endTs=null,this.error=null,this._ctx=null,this.id=Xn.nextId++,this.methodName=U.methodName,this.resourceId=I.getResourceId(U.instance),this.startTs=performance.now(),this._showInBrowserTimeline=U.showInBrowserTimeline,U.parentCtx){this._ctx=U.parentCtx.derive({attributes:{[TRACE_SPAN_ATTRIBUTE]:this.id}});const q=U.parentCtx.getAttribute(TRACE_SPAN_ATTRIBUTE);typeof q=="number"&&(this.parentId=q)}}get ctx(){return this._ctx}markSuccess(){this.endTs=performance.now(),this._traceProcessor._flushSpan(this),this._showInBrowserTimeline&&this._markInBrowserTimeline()}markError(I){this.endTs=performance.now(),this.error=serializeError(I),this._traceProcessor._flushSpan(this),this._showInBrowserTimeline&&this._markInBrowserTimeline()}serialize(){var I;return{id:this.id,resourceId:this.resourceId??void 0,methodName:this.methodName,parentId:this.parentId??void 0,startTs:this.startTs.toFixed(3),endTs:((I=this.endTs)==null?void 0:I.toFixed(3))??void 0,error:this.error??void 0}}_markInBrowserTimeline(){const I=this._traceProcessor.resources.get(this.resourceId),U=I?`${I.sanitizedClassName}#${I.data.instanceId}.${this.methodName}`:this.methodName;performance.measure(U,{start:this.startTs,end:this.endTs})}},Xn.nextId=0,Xn),serializeError=$=>$ instanceof Error?{name:$.name,message:$.message}:{message:String($)},TRACE_PROCESSOR=globalThis.TRACE_PROCESSOR??(globalThis.TRACE_PROCESSOR=new TraceProcessor),sanitizeValue=($,I,U)=>{switch(typeof $){case"string":case"number":case"boolean":case"undefined":return $;case"object":case"function":if($===null)return $;{const q=U.resourceInstanceIndex.get($);if(q)return`${q.sanitizedClassName}#${q.data.instanceId}`}if(typeof $.toJSON=="function")return sanitizeValue($.toJSON(),I,U);if(I>0){if(isSetLike($))return Object.fromEntries(Array.from($.entries()).map(q=>sanitizeValue(q,I-1,U)));if(isMapLike($))return Object.fromEntries(Array.from($.entries()).map(([q,G])=>[q,sanitizeValue(G,I-1,U)]));if(Array.isArray($))return $.map(q=>sanitizeValue(q,I-1,U));if(typeof $=="object"){const q={};for(const G of Object.keys($))q[G]=sanitizeValue($[G],I-1,U);return q}}return typeof $.truncate=="function"?$.truncate():$.toString()}},areEqualShallow=($,I)=>{for(const U in $)if(!(U in I)||$[U]!==I[U])return!1;for(const U in I)if(!(U in $)||$[U]!==I[U])return!1;return!0},sanitizeClassName=$=>{const I=/[^_](\d+)$/,U=$.match(I);return U?$.slice(0,-U[1].length):$},isSetLike=$=>$ instanceof Set||typeof $=="object"&&$!==null&&Object.getPrototypeOf($).constructor.name==="ComplexSet",isMapLike=$=>$ instanceof Map||typeof $=="object"&&$!==null&&Object.getPrototypeOf($).constructor.name==="ComplexMap",resource=$=>I=>{const U=class extends I{constructor(...q){super(...q),TRACE_PROCESSOR.traceResourceConstructor({constructor:I,annotation:$==null?void 0:$.annotation,instance:this})}};return Object.defineProperty(U,"name",{value:I.name}),U},info=($={})=>(I,U,q)=>{getTracingContext(I).infoProperties[U]={options:$}},mark=$=>{performance.mark($)},span=({showInBrowserTimeline:$=!1}={})=>(I,U,q)=>{const G=q.value;q.value=async function(...K){const Y=K[0]instanceof Context?K[0]:null,J=TRACE_PROCESSOR.traceSpan({parentCtx:Y,methodName:U,instance:this,showInBrowserTimeline:$}),X=J.ctx?[J.ctx,...K.slice(1)]:K;try{return await G.apply(this,X)}catch(Z){throw J.markError(Z),Z}finally{J.markSuccess()}}},metricsCounter=()=>($,I,U)=>{getTracingContext($).metricsProperties[I]={}},addLink=($,I,U={})=>{TRACE_PROCESSOR.addLink($,I,U)},trace={resource,info,mark,span,metricsCounter,addLink},Runtime;(function($){(function(I){(function(U){(function(q){q[q.RAM=0]="RAM",q[q.IDB=1]="IDB",q[q.CHROME=2]="CHROME",q[q.FIREFOX=3]="FIREFOX",q[q.NODE=4]="NODE",q[q.WEBFS=5]="WEBFS",q[q.LEVELJS=11]="LEVELJS",q[q.JSONDOWN=12]="JSONDOWN"})(U.StorageDriver||(U.StorageDriver={}))})(I.Storage||(I.Storage={}))})($.Client||($.Client={}))})(Runtime||(Runtime={}));var lib={},boolean$1={};Object.defineProperty(boolean$1,"__esModule",{value:!0}),boolean$1.boolean=void 0;const boolean=function($){switch(Object.prototype.toString.call($)){case"[object String]":return["true","t","yes","y","on","1"].includes($.trim().toLowerCase());case"[object Number]":return $.valueOf()===1;case"[object Boolean]":return $.valueOf();default:return!1}};boolean$1.boolean=boolean;var isBooleanable$1={};Object.defineProperty(isBooleanable$1,"__esModule",{value:!0}),isBooleanable$1.isBooleanable=void 0;const isBooleanable=function($){switch(Object.prototype.toString.call($)){case"[object String]":return["true","t","yes","y","on","1","false","f","no","n","off","0"].includes($.trim().toLowerCase());case"[object Number]":return[0,1].includes($.valueOf());case"[object Boolean]":return!0;default:return!1}};isBooleanable$1.isBooleanable=isBooleanable,function($){Object.defineProperty($,"__esModule",{value:!0}),$.isBooleanable=$.boolean=void 0;const I=boolean$1;Object.defineProperty($,"boolean",{enumerable:!0,get:function(){return I.boolean}});const U=isBooleanable$1;Object.defineProperty($,"isBooleanable",{enumerable:!0,get:function(){return U.isBooleanable}})}(lib);var lodash_ismatch={exports:{}};lodash_ismatch.exports,function($,I){var U=200,q="__lodash_hash_undefined__",G=1,K=2,Y=9007199254740991,J="[object Arguments]",X="[object Array]",Z="[object Boolean]",Q="[object Date]",ee="[object Error]",te="[object Function]",ne="[object GeneratorFunction]",ie="[object Map]",oe="[object Number]",ce="[object Object]",fe="[object Promise]",se="[object RegExp]",de="[object Set]",ue="[object String]",pe="[object Symbol]",ve="[object WeakMap]",me="[object ArrayBuffer]",be="[object DataView]",_e="[object Float32Array]",Se="[object Float64Array]",xe="[object Int8Array]",ke="[object Int16Array]",De="[object Int32Array]",Be="[object Uint8Array]",Ve="[object Uint8ClampedArray]",nt="[object Uint16Array]",ot="[object Uint32Array]",ft=/[\\^$.*+?()[\]{}|]/g,it=/^\[object .+?Constructor\]$/,ut=/^(?:0|[1-9]\d*)$/,et={};et[_e]=et[Se]=et[xe]=et[ke]=et[De]=et[Be]=et[Ve]=et[nt]=et[ot]=!0,et[J]=et[X]=et[me]=et[Z]=et[be]=et[Q]=et[ee]=et[te]=et[ie]=et[oe]=et[ce]=et[se]=et[de]=et[ue]=et[ve]=!1;var Ue=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,We=typeof self=="object"&&self&&self.Object===Object&&self,tt=Ue||We||Function("return this")(),vt=I&&!I.nodeType&&I,je=vt&&!0&&$&&!$.nodeType&&$,ze=je&&je.exports===vt,Ae=ze&&Ue.process,Re=function(){try{return Ae&&Ae.binding("util")}catch{}}(),Ce=Re&&Re.isTypedArray;function ge(Ne,Qe){for(var yt=-1,Pt=Ne?Ne.length:0;++yt<Pt;)if(Qe(Ne[yt],yt,Ne))return!0;return!1}function ye(Ne,Qe){for(var yt=-1,Pt=Array(Ne);++yt<Ne;)Pt[yt]=Qe(yt);return Pt}function Me(Ne){return function(Qe){return Ne(Qe)}}function Ke(Ne,Qe){return Ne==null?void 0:Ne[Qe]}function st(Ne){var Qe=!1;if(Ne!=null&&typeof Ne.toString!="function")try{Qe=!!(Ne+"")}catch{}return Qe}function dt(Ne){var Qe=-1,yt=Array(Ne.size);return Ne.forEach(function(Pt,tn){yt[++Qe]=[tn,Pt]}),yt}function $t(Ne,Qe){return function(yt){return Ne(Qe(yt))}}function Et(Ne){var Qe=-1,yt=Array(Ne.size);return Ne.forEach(function(Pt){yt[++Qe]=Pt}),yt}var rt=Array.prototype,jt=Function.prototype,Gt=Object.prototype,At=tt["__core-js_shared__"],zt=function(){var Ne=/[^.]+$/.exec(At&&At.keys&&At.keys.IE_PROTO||"");return Ne?"Symbol(src)_1."+Ne:""}(),nn=jt.toString,St=Gt.hasOwnProperty,Ut=Gt.toString,le=RegExp("^"+nn.call(St).replace(ft,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),re=tt.Symbol,ae=tt.Uint8Array,he=Gt.propertyIsEnumerable,we=rt.splice,Ee=$t(Object.keys,Object),Le=Ge(tt,"DataView"),bt=Ge(tt,"Map"),Lt=Ge(tt,"Promise"),Ct=Ge(tt,"Set"),It=Ge(tt,"WeakMap"),Tt=Ge(Object,"create"),Sn=Ht(Le),gn=Ht(bt),pn=Ht(Lt),vn=Ht(Ct),Tn=Ht(It),dn=re?re.prototype:void 0,Pn=dn?dn.valueOf:void 0;function $n(Ne){var Qe=-1,yt=Ne?Ne.length:0;for(this.clear();++Qe<yt;){var Pt=Ne[Qe];this.set(Pt[0],Pt[1])}}function Vn(){this.__data__=Tt?Tt(null):{}}function Nn(Ne){return this.has(Ne)&&delete this.__data__[Ne]}function Fn(Ne){var Qe=this.__data__;if(Tt){var yt=Qe[Ne];return yt===q?void 0:yt}return St.call(Qe,Ne)?Qe[Ne]:void 0}function fn(Ne){var Qe=this.__data__;return Tt?Qe[Ne]!==void 0:St.call(Qe,Ne)}function Gn(Ne,Qe){var yt=this.__data__;return yt[Ne]=Tt&&Qe===void 0?q:Qe,this}$n.prototype.clear=Vn,$n.prototype.delete=Nn,$n.prototype.get=Fn,$n.prototype.has=fn,$n.prototype.set=Gn;function bn(Ne){var Qe=-1,yt=Ne?Ne.length:0;for(this.clear();++Qe<yt;){var Pt=Ne[Qe];this.set(Pt[0],Pt[1])}}function Kn(){this.__data__=[]}function He(Ne){var Qe=this.__data__,yt=An(Qe,Ne);if(yt<0)return!1;var Pt=Qe.length-1;return yt==Pt?Qe.pop():we.call(Qe,yt,1),!0}function pt(Ne){var Qe=this.__data__,yt=An(Qe,Ne);return yt<0?void 0:Qe[yt][1]}function kt(Ne){return An(this.__data__,Ne)>-1}function Pe(Ne,Qe){var yt=this.__data__,Pt=An(yt,Ne);return Pt<0?yt.push([Ne,Qe]):yt[Pt][1]=Qe,this}bn.prototype.clear=Kn,bn.prototype.delete=He,bn.prototype.get=pt,bn.prototype.has=kt,bn.prototype.set=Pe;function at(Ne){var Qe=-1,yt=Ne?Ne.length:0;for(this.clear();++Qe<yt;){var Pt=Ne[Qe];this.set(Pt[0],Pt[1])}}function lt(){this.__data__={hash:new $n,map:new(bt||bn),string:new $n}}function xt(Ne){return Ye(this,Ne).delete(Ne)}function Rt(Ne){return Ye(this,Ne).get(Ne)}function Dt(Ne){return Ye(this,Ne).has(Ne)}function Mt(Ne,Qe){return Ye(this,Ne).set(Ne,Qe),this}at.prototype.clear=lt,at.prototype.delete=xt,at.prototype.get=Rt,at.prototype.has=Dt,at.prototype.set=Mt;function Ot(Ne){var Qe=-1,yt=Ne?Ne.length:0;for(this.__data__=new at;++Qe<yt;)this.add(Ne[Qe])}function Xt(Ne){return this.__data__.set(Ne,q),this}function Zt(Ne){return this.__data__.has(Ne)}Ot.prototype.add=Ot.prototype.push=Xt,Ot.prototype.has=Zt;function Kt(Ne){this.__data__=new bn(Ne)}function an(){this.__data__=new bn}function xn(Ne){return this.__data__.delete(Ne)}function Yn(Ne){return this.__data__.get(Ne)}function ln(Ne){return this.__data__.has(Ne)}function Bn(Ne,Qe){var yt=this.__data__;if(yt instanceof bn){var Pt=yt.__data__;if(!bt||Pt.length<U-1)return Pt.push([Ne,Qe]),this;yt=this.__data__=new at(Pt)}return yt.set(Ne,Qe),this}Kt.prototype.clear=an,Kt.prototype.delete=xn,Kt.prototype.get=Yn,Kt.prototype.has=ln,Kt.prototype.set=Bn;function jn(Ne,Qe){var yt=cn(Ne)||en(Ne)?ye(Ne.length,String):[],Pt=yt.length,tn=!!Pt;for(var Wt in Ne)(Qe||St.call(Ne,Wt))&&!(tn&&(Wt=="length"||ht(Wt,Pt)))&&yt.push(Wt);return yt}function An(Ne,Qe){for(var yt=Ne.length;yt--;)if(Yt(Ne[yt][0],Qe))return yt;return-1}function Un(Ne){return Ut.call(Ne)}function Qn(Ne,Qe,yt,Pt,tn){return Ne===Qe?!0:Ne==null||Qe==null||!Wn(Ne)&&!Mn(Qe)?Ne!==Ne&&Qe!==Qe:ir(Ne,Qe,Qn,yt,Pt,tn)}function ir(Ne,Qe,yt,Pt,tn,Wt){var hn=cn(Ne),rn=cn(Qe),Qt=X,un=X;hn||(Qt=ct(Ne),Qt=Qt==J?ce:Qt),rn||(un=ct(Qe),un=un==J?ce:un);var yn=Qt==ce&&!st(Ne),kn=un==ce&&!st(Qe),mn=Qt==un;if(mn&&!yn)return Wt||(Wt=new Kt),hn||sr(Ne)?Te(Ne,Qe,yt,Pt,tn,Wt):qe(Ne,Qe,Qt,yt,Pt,tn,Wt);if(!(tn&K)){var On=yn&&St.call(Ne,"__wrapped__"),Rn=kn&&St.call(Qe,"__wrapped__");if(On||Rn){var Ln=On?Ne.value():Ne,Dn=Rn?Qe.value():Qe;return Wt||(Wt=new Kt),yt(Ln,Dn,Pt,tn,Wt)}}return mn?(Wt||(Wt=new Kt),Oe(Ne,Qe,yt,Pt,tn,Wt)):!1}function ar(Ne,Qe,yt,Pt){var tn=yt.length,Wt=tn,hn=!Pt;if(Ne==null)return!Wt;for(Ne=Object(Ne);tn--;){var rn=yt[tn];if(hn&&rn[2]?rn[1]!==Ne[rn[0]]:!(rn[0]in Ne))return!1}for(;++tn<Wt;){rn=yt[tn];var Qt=rn[0],un=Ne[Qt],yn=rn[1];if(hn&&rn[2]){if(un===void 0&&!(Qt in Ne))return!1}else{var kn=new Kt;if(Pt)var mn=Pt(un,yn,Qt,Ne,Qe,kn);if(!(mn===void 0?Qn(yn,un,Pt,G|K,kn):mn))return!1}}return!0}function zn(Ne){if(!Wn(Ne)||gt(Ne))return!1;var Qe=Hn(Ne)||st(Ne)?le:it;return Qe.test(Ht(Ne))}function or(Ne){return Mn(Ne)&&er(Ne.length)&&!!et[Ut.call(Ne)]}function nr(Ne){if(!wt(Ne))return Ee(Ne);var Qe=[];for(var yt in Object(Ne))St.call(Ne,yt)&&yt!="constructor"&&Qe.push(yt);return Qe}function Te(Ne,Qe,yt,Pt,tn,Wt){var hn=tn&K,rn=Ne.length,Qt=Qe.length;if(rn!=Qt&&!(hn&&Qt>rn))return!1;var un=Wt.get(Ne);if(un&&Wt.get(Qe))return un==Qe;var yn=-1,kn=!0,mn=tn&G?new Ot:void 0;for(Wt.set(Ne,Qe),Wt.set(Qe,Ne);++yn<rn;){var On=Ne[yn],Rn=Qe[yn];if(Pt)var Ln=hn?Pt(Rn,On,yn,Qe,Ne,Wt):Pt(On,Rn,yn,Ne,Qe,Wt);if(Ln!==void 0){if(Ln)continue;kn=!1;break}if(mn){if(!ge(Qe,function(Dn,Ie){if(!mn.has(Ie)&&(On===Dn||yt(On,Dn,Pt,tn,Wt)))return mn.add(Ie)})){kn=!1;break}}else if(!(On===Rn||yt(On,Rn,Pt,tn,Wt))){kn=!1;break}}return Wt.delete(Ne),Wt.delete(Qe),kn}function qe(Ne,Qe,yt,Pt,tn,Wt,hn){switch(yt){case be:if(Ne.byteLength!=Qe.byteLength||Ne.byteOffset!=Qe.byteOffset)return!1;Ne=Ne.buffer,Qe=Qe.buffer;case me:return!(Ne.byteLength!=Qe.byteLength||!Pt(new ae(Ne),new ae(Qe)));case Z:case Q:case oe:return Yt(+Ne,+Qe);case ee:return Ne.name==Qe.name&&Ne.message==Qe.message;case se:case ue:return Ne==Qe+"";case ie:var rn=dt;case de:var Qt=Wt&K;if(rn||(rn=Et),Ne.size!=Qe.size&&!Qt)return!1;var un=hn.get(Ne);if(un)return un==Qe;Wt|=G,hn.set(Ne,Qe);var yn=Te(rn(Ne),rn(Qe),Pt,tn,Wt,hn);return hn.delete(Ne),yn;case pe:if(Pn)return Pn.call(Ne)==Pn.call(Qe)}return!1}function Oe(Ne,Qe,yt,Pt,tn,Wt){var hn=tn&K,rn=qn(Ne),Qt=rn.length,un=qn(Qe),yn=un.length;if(Qt!=yn&&!hn)return!1;for(var kn=Qt;kn--;){var mn=rn[kn];if(!(hn?mn in Qe:St.call(Qe,mn)))return!1}var On=Wt.get(Ne);if(On&&Wt.get(Qe))return On==Qe;var Rn=!0;Wt.set(Ne,Qe),Wt.set(Qe,Ne);for(var Ln=hn;++kn<Qt;){mn=rn[kn];var Dn=Ne[mn],Ie=Qe[mn];if(Pt)var Je=hn?Pt(Ie,Dn,mn,Qe,Ne,Wt):Pt(Dn,Ie,mn,Ne,Qe,Wt);if(!(Je===void 0?Dn===Ie||yt(Dn,Ie,Pt,tn,Wt):Je)){Rn=!1;break}Ln||(Ln=mn=="constructor")}if(Rn&&!Ln){var $e=Ne.constructor,Fe=Qe.constructor;$e!=Fe&&"constructor"in Ne&&"constructor"in Qe&&!(typeof $e=="function"&&$e instanceof $e&&typeof Fe=="function"&&Fe instanceof Fe)&&(Rn=!1)}return Wt.delete(Ne),Wt.delete(Qe),Rn}function Ye(Ne,Qe){var yt=Ne.__data__;return mt(Qe)?yt[typeof Qe=="string"?"string":"hash"]:yt.map}function Ze(Ne){for(var Qe=qn(Ne),yt=Qe.length;yt--;){var Pt=Qe[yt],tn=Ne[Pt];Qe[yt]=[Pt,tn,Ft(tn)]}return Qe}function Ge(Ne,Qe){var yt=Ke(Ne,Qe);return zn(yt)?yt:void 0}var ct=Un;(Le&&ct(new Le(new ArrayBuffer(1)))!=be||bt&&ct(new bt)!=ie||Lt&&ct(Lt.resolve())!=fe||Ct&&ct(new Ct)!=de||It&&ct(new It)!=ve)&&(ct=function(Ne){var Qe=Ut.call(Ne),yt=Qe==ce?Ne.constructor:void 0,Pt=yt?Ht(yt):void 0;if(Pt)switch(Pt){case Sn:return be;case gn:return ie;case pn:return fe;case vn:return de;case Tn:return ve}return Qe});function ht(Ne,Qe){return Qe=Qe??Y,!!Qe&&(typeof Ne=="number"||ut.test(Ne))&&Ne>-1&&Ne%1==0&&Ne<Qe}function mt(Ne){var Qe=typeof Ne;return Qe=="string"||Qe=="number"||Qe=="symbol"||Qe=="boolean"?Ne!=="__proto__":Ne===null}function gt(Ne){return!!zt&&zt in Ne}function wt(Ne){var Qe=Ne&&Ne.constructor,yt=typeof Qe=="function"&&Qe.prototype||Gt;return Ne===yt}function Ft(Ne){return Ne===Ne&&!Wn(Ne)}function Ht(Ne){if(Ne!=null){try{return nn.call(Ne)}catch{}try{return Ne+""}catch{}}return""}function Yt(Ne,Qe){return Ne===Qe||Ne!==Ne&&Qe!==Qe}function en(Ne){return wn(Ne)&&St.call(Ne,"callee")&&(!he.call(Ne,"callee")||Ut.call(Ne)==J)}var cn=Array.isArray;function sn(Ne){return Ne!=null&&er(Ne.length)&&!Hn(Ne)}function wn(Ne){return Mn(Ne)&&sn(Ne)}function Hn(Ne){var Qe=Wn(Ne)?Ut.call(Ne):"";return Qe==te||Qe==ne}function er(Ne){return typeof Ne=="number"&&Ne>-1&&Ne%1==0&&Ne<=Y}function Wn(Ne){var Qe=typeof Ne;return!!Ne&&(Qe=="object"||Qe=="function")}function Mn(Ne){return!!Ne&&typeof Ne=="object"}function cr(Ne,Qe){return Ne===Qe||ar(Ne,Qe,Ze(Qe))}var sr=Ce?Me(Ce):or;function qn(Ne){return sn(Ne)?jn(Ne):nr(Ne)}$.exports=cr}(lodash_ismatch,lodash_ismatch.exports);var lodash_ismatchExports=lodash_ismatch.exports;const isMatch=getDefaultExportFromCjs(lodash_ismatchExports);var FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",INFINITY=1/0,funcTag="[object Function]",genTag="[object GeneratorFunction]",symbolTag="[object Symbol]",reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reEscapeChar=/\\(\\)?/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,freeSelf=typeof self=="object"&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")();function getValue$1($,I){return $==null?void 0:$[I]}function isHostObject($){var I=!1;if($!=null&&typeof $.toString!="function")try{I=!!($+"")}catch{}return I}var arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var $=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol$1=root.Symbol,splice=arrayProto.splice,Map$1=getNative(root,"Map"),nativeCreate=getNative(Object,"create"),symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0;function Hash($){var I=-1,U=$?$.length:0;for(this.clear();++I<U;){var q=$[I];this.set(q[0],q[1])}}function hashClear(){this.__data__=nativeCreate?nativeCreate(null):{}}function hashDelete($){return this.has($)&&delete this.__data__[$]}function hashGet($){var I=this.__data__;if(nativeCreate){var U=I[$];return U===HASH_UNDEFINED?void 0:U}return hasOwnProperty.call(I,$)?I[$]:void 0}function hashHas($){var I=this.__data__;return nativeCreate?I[$]!==void 0:hasOwnProperty.call(I,$)}function hashSet($,I){var U=this.__data__;return U[$]=nativeCreate&&I===void 0?HASH_UNDEFINED:I,this}Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet;function ListCache($){var I=-1,U=$?$.length:0;for(this.clear();++I<U;){var q=$[I];this.set(q[0],q[1])}}function listCacheClear(){this.__data__=[]}function listCacheDelete($){var I=this.__data__,U=assocIndexOf(I,$);if(U<0)return!1;var q=I.length-1;return U==q?I.pop():splice.call(I,U,1),!0}function listCacheGet($){var I=this.__data__,U=assocIndexOf(I,$);return U<0?void 0:I[U][1]}function listCacheHas($){return assocIndexOf(this.__data__,$)>-1}function listCacheSet($,I){var U=this.__data__,q=assocIndexOf(U,$);return q<0?U.push([$,I]):U[q][1]=I,this}ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet;function MapCache($){var I=-1,U=$?$.length:0;for(this.clear();++I<U;){var q=$[I];this.set(q[0],q[1])}}function mapCacheClear(){this.__data__={hash:new Hash,map:new(Map$1||ListCache),string:new Hash}}function mapCacheDelete($){return getMapData(this,$).delete($)}function mapCacheGet($){return getMapData(this,$).get($)}function mapCacheHas($){return getMapData(this,$).has($)}function mapCacheSet($,I){return getMapData(this,$).set($,I),this}MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet;function assocIndexOf($,I){for(var U=$.length;U--;)if(eq($[U][0],I))return U;return-1}function baseIsNative($){if(!isObject($)||isMasked($))return!1;var I=isFunction$1($)||isHostObject($)?reIsNative:reIsHostCtor;return I.test(toSource($))}function baseToString($){if(typeof $=="string")return $;if(isSymbol($))return symbolToString?symbolToString.call($):"";var I=$+"";return I=="0"&&1/$==-INFINITY?"-0":I}function getMapData($,I){var U=$.__data__;return isKeyable(I)?U[typeof I=="string"?"string":"hash"]:U.map}function getNative($,I){var U=getValue$1($,I);return baseIsNative(U)?U:void 0}function isKeyable($){var I=typeof $;return I=="string"||I=="number"||I=="symbol"||I=="boolean"?$!=="__proto__":$===null}function isMasked($){return!!maskSrcKey&&maskSrcKey in $}memoize(function($){$=toString($);var I=[];return reLeadingDot.test($)&&I.push(""),$.replace(rePropName,function(U,q,G,K){I.push(G?K.replace(reEscapeChar,"$1"):q||U)}),I});function toSource($){if($!=null){try{return funcToString.call($)}catch{}try{return $+""}catch{}}return""}function memoize($,I){if(typeof $!="function"||I&&typeof I!="function")throw new TypeError(FUNC_ERROR_TEXT);var U=function(){var q=arguments,G=I?I.apply(this,q):q[0],K=U.cache;if(K.has(G))return K.get(G);var Y=$.apply(this,q);return U.cache=K.set(G,Y),Y};return U.cache=new(memoize.Cache||MapCache),U}memoize.Cache=MapCache;function eq($,I){return $===I||$!==$&&I!==I}function isFunction$1($){var I=isObject($)?objectToString.call($):"";return I==funcTag||I==genTag}function isObject($){var I=typeof $;return!!$&&(I=="object"||I=="function")}function isObjectLike($){return!!$&&typeof $=="object"}function isSymbol($){return typeof $=="symbol"||isObjectLike($)&&objectToString.call($)==symbolTag}function toString($){return $==null?"":baseToString($)}function commonjsRequire($){throw new Error('Could not dynamically require "'+$+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var localforage={exports:{}};/*!
|
|
907
|
+
`&&++G,++U===q)throw Z("comment");pe=ve,ve=ee(U)}while(pe!=="*"||ve!=="/");++U,be&&(te(me,U-2,_e),_e=!0),ue=!0}else return"/"}}while(ue);var Se=U;delimRe.lastIndex=0;var xe=delimRe.test(ee(Se++));if(!xe)for(;Se<q&&!delimRe.test(ee(Se));)++Se;var ke=$.substring(U,U=Se);return(ke==='"'||ke==="'")&&(X=ke),ke}function ce(ue){J.push(ue)}function fe(){if(!J.length){var ue=oe();if(ue===null)return null;ce(ue)}return J[0]}function se(ue,pe){var ve=fe(),me=ve===ue;if(me)return oe(),!0;if(!pe)throw Z("token '"+ve+"', '"+ue+"' expected");return!1}function de(ue){var pe=null,ve;return ue===void 0?(ve=Y[G-1],delete Y[G-1],ve&&(I||ve.type==="*"||ve.lineEmpty)&&(pe=ve.leading?ve.text:null)):(K<ue&&fe(),ve=Y[ue],delete Y[ue],ve&&!ve.lineEmpty&&(I||ve.type==="/")&&(pe=ve.leading?null:ve.text)),pe}return Object.defineProperty({next:oe,peek:fe,push:ce,skip:se,cmnt:de},"line",{get:function(){return G}})}var parse_1=parse;parse.filename=null,parse.defaults={keepCase:!1};var tokenize=tokenize_1,Root=requireRoot(),Type=requireType(),Field=requireField(),MapField=requireMapfield(),OneOf=requireOneof(),Enum=require_enum(),Service=requireService(),Method=requireMethod(),types=requireTypes(),util=requireUtil(),base10Re=/^[1-9][0-9]*$/,base10NegRe=/^-?[1-9][0-9]*$/,base16Re=/^0[x][0-9a-fA-F]+$/,base16NegRe=/^-?0[x][0-9a-fA-F]+$/,base8Re=/^0[0-7]+$/,base8NegRe=/^-?0[0-7]+$/,numberRe=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,nameRe=/^[a-zA-Z_][a-zA-Z_0-9]*$/,typeRefRe=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,fqTypeRefRe=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function parse($,I,U){I instanceof Root||(U=I,I=new Root),U||(U=parse.defaults);var q=U.preferTrailingComment||!1,G=tokenize($,U.alternateCommentMode||!1),K=G.next,Y=G.push,J=G.peek,X=G.skip,Z=G.cmnt,Q=!0,ee,te,ne,ie,oe=!1,ce=I,fe=U.keepCase?function(Re){return Re}:util.camelCase;function se(Re,Ce,ge){var ye=parse.filename;return ge||(parse.filename=null),Error("illegal "+(Ce||"token")+" '"+Re+"' ("+(ye?ye+", ":"")+"line "+G.line+")")}function de(){var Re=[],Ce;do{if((Ce=K())!=='"'&&Ce!=="'")throw se(Ce);Re.push(K()),X(Ce),Ce=J()}while(Ce==='"'||Ce==="'");return Re.join("")}function ue(Re){var Ce=K();switch(Ce){case"'":case'"':return Y(Ce),de();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return ve(Ce,!0)}catch{if(Re&&typeRefRe.test(Ce))return Ce;throw se(Ce,"value")}}function pe(Re,Ce){var ge,ye;do Ce&&((ge=J())==='"'||ge==="'")?Re.push(de()):Re.push([ye=me(K()),X("to",!0)?me(K()):ye]);while(X(",",!0));X(";")}function ve(Re,Ce){var ge=1;switch(Re.charAt(0)==="-"&&(ge=-1,Re=Re.substring(1)),Re){case"inf":case"INF":case"Inf":return ge*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(base10Re.test(Re))return ge*parseInt(Re,10);if(base16Re.test(Re))return ge*parseInt(Re,16);if(base8Re.test(Re))return ge*parseInt(Re,8);if(numberRe.test(Re))return ge*parseFloat(Re);throw se(Re,"number",Ce)}function me(Re,Ce){switch(Re){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!Ce&&Re.charAt(0)==="-")throw se(Re,"id");if(base10NegRe.test(Re))return parseInt(Re,10);if(base16NegRe.test(Re))return parseInt(Re,16);if(base8NegRe.test(Re))return parseInt(Re,8);throw se(Re,"id")}function be(){if(ee!==void 0)throw se("package");if(ee=K(),!typeRefRe.test(ee))throw se(ee,"name");ce=ce.define(ee),X(";")}function _e(){var Re=J(),Ce;switch(Re){case"weak":Ce=ne||(ne=[]),K();break;case"public":K();default:Ce=te||(te=[]);break}Re=de(),X(";"),Ce.push(Re)}function Se(){if(X("="),ie=de(),oe=ie==="proto3",!oe&&ie!=="proto2")throw se(ie,"syntax");X(";")}function xe(Re,Ce){switch(Ce){case"option":return ut(Re,Ce),X(";"),!0;case"message":return De(Re,Ce),!0;case"enum":return ft(Re,Ce),!0;case"service":return vt(Re,Ce),!0;case"extend":return ze(Re,Ce),!0}return!1}function ke(Re,Ce,ge){var ye=G.line;if(Re&&(typeof Re.comment!="string"&&(Re.comment=Z()),Re.filename=parse.filename),X("{",!0)){for(var Me;(Me=K())!=="}";)Ce(Me);X(";",!0)}else ge&&ge(),X(";"),Re&&(typeof Re.comment!="string"||q)&&(Re.comment=Z(ye)||Re.comment)}function De(Re,Ce){if(!nameRe.test(Ce=K()))throw se(Ce,"type name");var ge=new Type(Ce);ke(ge,function(Me){if(!xe(ge,Me))switch(Me){case"map":nt(ge);break;case"required":case"repeated":Be(ge,Me);break;case"optional":oe?Be(ge,"proto3_optional"):Be(ge,"optional");break;case"oneof":ot(ge,Me);break;case"extensions":pe(ge.extensions||(ge.extensions=[]));break;case"reserved":pe(ge.reserved||(ge.reserved=[]),!0);break;default:if(!oe||!typeRefRe.test(Me))throw se(Me);Y(Me),Be(ge,"optional");break}}),Re.add(ge)}function Be(Re,Ce,ge){var ye=K();if(ye==="group"){Ve(Re,Ce);return}if(!typeRefRe.test(ye))throw se(ye,"type");var Me=K();if(!nameRe.test(Me))throw se(Me,"name");Me=fe(Me),X("=");var Ke=new Field(Me,me(K()),ye,Ce,ge);if(ke(Ke,function($t){if($t==="option")ut(Ke,$t),X(";");else throw se($t)},function(){tt(Ke)}),Ce==="proto3_optional"){var st=new OneOf("_"+Me);Ke.setOption("proto3_optional",!0),st.add(Ke),Re.add(st)}else Re.add(Ke);!oe&&Ke.repeated&&(types.packed[ye]!==void 0||types.basic[ye]===void 0)&&Ke.setOption("packed",!1,!0)}function Ve(Re,Ce){var ge=K();if(!nameRe.test(ge))throw se(ge,"name");var ye=util.lcFirst(ge);ge===ye&&(ge=util.ucFirst(ge)),X("=");var Me=me(K()),Ke=new Type(ge);Ke.group=!0;var st=new Field(ye,Me,ge,Ce);st.filename=parse.filename,ke(Ke,function($t){switch($t){case"option":ut(Ke,$t),X(";");break;case"required":case"repeated":Be(Ke,$t);break;case"optional":oe?Be(Ke,"proto3_optional"):Be(Ke,"optional");break;case"message":De(Ke,$t);break;case"enum":ft(Ke,$t);break;default:throw se($t)}}),Re.add(Ke).add(st)}function nt(Re){X("<");var Ce=K();if(types.mapKey[Ce]===void 0)throw se(Ce,"type");X(",");var ge=K();if(!typeRefRe.test(ge))throw se(ge,"type");X(">");var ye=K();if(!nameRe.test(ye))throw se(ye,"name");X("=");var Me=new MapField(fe(ye),me(K()),Ce,ge);ke(Me,function(st){if(st==="option")ut(Me,st),X(";");else throw se(st)},function(){tt(Me)}),Re.add(Me)}function ot(Re,Ce){if(!nameRe.test(Ce=K()))throw se(Ce,"name");var ge=new OneOf(fe(Ce));ke(ge,function(Me){Me==="option"?(ut(ge,Me),X(";")):(Y(Me),Be(ge,"optional"))}),Re.add(ge)}function ft(Re,Ce){if(!nameRe.test(Ce=K()))throw se(Ce,"name");var ge=new Enum(Ce);ke(ge,function(Me){switch(Me){case"option":ut(ge,Me),X(";");break;case"reserved":pe(ge.reserved||(ge.reserved=[]),!0);break;default:it(ge,Me)}}),Re.add(ge)}function it(Re,Ce){if(!nameRe.test(Ce))throw se(Ce,"name");X("=");var ge=me(K(),!0),ye={options:void 0};ye.setOption=function(Me,Ke){this.options===void 0&&(this.options={}),this.options[Me]=Ke},ke(ye,function(Ke){if(Ke==="option")ut(ye,Ke),X(";");else throw se(Ke)},function(){tt(ye)}),Re.add(Ce,ge,ye.comment,ye.options)}function ut(Re,Ce){var ge=X("(",!0);if(!typeRefRe.test(Ce=K()))throw se(Ce,"name");var ye=Ce,Me=ye,Ke;ge&&(X(")"),ye="("+ye+")",Me=ye,Ce=J(),fqTypeRefRe.test(Ce)&&(Ke=Ce.slice(1),ye+=Ce,K())),X("=");var st=et(Re,ye);We(Re,Me,st,Ke)}function et(Re,Ce){if(X("{",!0)){for(var ge={};!X("}",!0);){if(!nameRe.test(Ae=K()))throw se(Ae,"name");var ye,Me=Ae;if(X(":",!0),J()==="{")ye=et(Re,Ce+"."+Ae);else if(J()==="["){ye=[];var Ke;if(X("[",!0)){do Ke=ue(!0),ye.push(Ke);while(X(",",!0));X("]"),typeof Ke<"u"&&Ue(Re,Ce+"."+Ae,Ke)}}else ye=ue(!0),Ue(Re,Ce+"."+Ae,ye);var st=ge[Me];st&&(ye=[].concat(st).concat(ye)),ge[Me]=ye,X(",",!0),X(";",!0)}return ge}var dt=ue(!0);return Ue(Re,Ce,dt),dt}function Ue(Re,Ce,ge){Re.setOption&&Re.setOption(Ce,ge)}function We(Re,Ce,ge,ye){Re.setParsedOption&&Re.setParsedOption(Ce,ge,ye)}function tt(Re){if(X("[",!0)){do ut(Re,"option");while(X(",",!0));X("]")}return Re}function vt(Re,Ce){if(!nameRe.test(Ce=K()))throw se(Ce,"service name");var ge=new Service(Ce);ke(ge,function(Me){if(!xe(ge,Me))if(Me==="rpc")je(ge,Me);else throw se(Me)}),Re.add(ge)}function je(Re,Ce){var ge=Z(),ye=Ce;if(!nameRe.test(Ce=K()))throw se(Ce,"name");var Me=Ce,Ke,st,dt,$t;if(X("("),X("stream",!0)&&(st=!0),!typeRefRe.test(Ce=K())||(Ke=Ce,X(")"),X("returns"),X("("),X("stream",!0)&&($t=!0),!typeRefRe.test(Ce=K())))throw se(Ce);dt=Ce,X(")");var Et=new Method(Me,ye,Ke,dt,st,$t);Et.comment=ge,ke(Et,function(jt){if(jt==="option")ut(Et,jt),X(";");else throw se(jt)}),Re.add(Et)}function ze(Re,Ce){if(!typeRefRe.test(Ce=K()))throw se(Ce,"reference");var ge=Ce;ke(null,function(Me){switch(Me){case"required":case"repeated":Be(Re,Me,ge);break;case"optional":oe?Be(Re,"proto3_optional",ge):Be(Re,"optional",ge);break;default:if(!oe||!typeRefRe.test(Me))throw se(Me);Y(Me),Be(Re,"optional",ge);break}})}for(var Ae;(Ae=K())!==null;)switch(Ae){case"package":if(!Q)throw se(Ae);be();break;case"import":if(!Q)throw se(Ae);_e();break;case"syntax":if(!Q)throw se(Ae);Se();break;case"option":ut(ce,Ae),X(";");break;default:if(xe(ce,Ae)){Q=!1;continue}throw se(Ae)}return parse.filename=null,{package:ee,imports:te,weakImports:ne,syntax:ie,root:I}}var common_1=common$1,commonRe=/\/|\./;function common$1($,I){commonRe.test($)||($="google/protobuf/"+$+".proto",I={nested:{google:{nested:{protobuf:{nested:I}}}}}),common$1[$]=I}common$1("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}});var timeType;common$1("duration",{Duration:timeType={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),common$1("timestamp",{Timestamp:timeType}),common$1("empty",{Empty:{fields:{}}}),common$1("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),common$1("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),common$1("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),common$1.get=function $(I){return common$1[I]||null};var protobuf=indexLightExports;protobuf.build="full",protobuf.tokenize=tokenize_1,protobuf.parse=parse_1,protobuf.common=common_1,protobuf.Root._configure(protobuf.Type,protobuf.parse,protobuf.common);var dist$1={},core={},debug$1={};Object.defineProperty(debug$1,"__esModule",{value:!0});function getType($){return Object.prototype.toString.call($)}debug$1.getType=getType;function throwUnknownDataType($){throw new TypeError("unsupported data type: "+getType($))}debug$1.throwUnknownDataType=throwUnknownDataType;var encode$1={},number={};Object.defineProperty(number,"__esModule",{value:!0});let i_to_s="";for(let $=0;$<10;$++){const I=String.fromCharCode(48+$);i_to_s+=I}for(let $=0;$<26;$++){const I=String.fromCharCode(65+$);i_to_s+=I}for(let $=0;$<26;$++){const I=String.fromCharCode(97+$);i_to_s+=I}const N=i_to_s.length,s_to_i={};for(let $=0;$<N;$++){const I=i_to_s[$];s_to_i[I]=$}function s_to_int($){let I=0,U=1;for(let q=$.length-1;q>=0;q--){const G=$[q];let K=s_to_i[G];K*=U,I+=K,U*=N}return I}number.s_to_int=s_to_int;function s_to_big_int($){let I=BigInt(0),U=BigInt(1);const q=BigInt(N);for(let G=$.length-1;G>=0;G--){const K=$[G];let Y=BigInt(s_to_i[K]);Y*=U,I+=Y,U*=q}return I}number.s_to_big_int=s_to_big_int;function int_to_s($){if($===0)return i_to_s[0];const I=[];for(;$!==0;){const U=$%N,q=i_to_s[U];I.push(q),$-=U,$/=N}return I.reverse().join("")}number.int_to_s=int_to_s;function big_int_to_s($){const I=BigInt(0),U=BigInt(N);if($===I)return i_to_s[0];const q=[];for(;$!==I;){const G=$%U,K=i_to_s[Number(G)];q.push(K),$-=G,$/=U}return q.reverse().join("")}number.big_int_to_s=big_int_to_s;function reverse($){return $.split("").reverse().join("")}function num_to_s($){if($<0)return"-"+num_to_s(-$);let[I,U]=$.toString().split(".");if(!U)return int_to_s($);let q;U&&([U,q]=U.split("e")),I=int_str_to_s(I),U=reverse(U),U=int_str_to_s(U);let G=I+"."+U;if(q){switch(G+=".",q[0]){case"+":q=q.slice(1);break;case"-":G+="-",q=q.slice(1);break}q=reverse(q),q=int_str_to_s(q),G+=q}return G}number.num_to_s=num_to_s;function int_str_to_s($){const I=+$;return I.toString()===$?int_to_s(I):":"+big_int_to_s(BigInt($))}number.int_str_to_s=int_str_to_s;function s_to_int_str($){return $[0]===":"?s_to_big_int($.substring(1)).toString():s_to_int($).toString()}function s_to_num($){if($[0]==="-")return-s_to_num($.substr(1));let[I,U,q]=$.split(".");if(!U)return s_to_int(I);I=s_to_int_str(I),U=s_to_int_str(U),U=reverse(U);let G=I+"."+U;if(q){G+="e";let K=!1;q[0]==="-"&&(K=!0,q=q.slice(1)),q=s_to_int_str(q),q=reverse(q),G+=K?-q:+q}return+G}number.s_to_num=s_to_num,Object.defineProperty(encode$1,"__esModule",{value:!0});const number_1$1=number;function encodeNum($){return"n|"+number_1$1.num_to_s($)}encode$1.encodeNum=encodeNum;function decodeNum($){return $=$.replace("n|",""),number_1$1.s_to_num($)}encode$1.decodeNum=decodeNum;function decodeKey($){return typeof $=="number"?$:number_1$1.s_to_int($)}encode$1.decodeKey=decodeKey;function encodeBool($){return $?"b|T":"b|F"}encode$1.encodeBool=encodeBool;function decodeBool($){switch($){case"b|T":return!0;case"b|F":return!1}return!!$}encode$1.decodeBool=decodeBool;function encodeStr($){switch($[0]+$[1]){case"b|":case"o|":case"n|":case"a|":case"s|":$="s|"+$}return $}encode$1.encodeStr=encodeStr;function decodeStr($){return $[0]+$[1]==="s|"?$.substr(2):$}encode$1.decodeStr=decodeStr;var memory={},config={};Object.defineProperty(config,"__esModule",{value:!0}),config.config={sort_key:!1},Object.defineProperty(memory,"__esModule",{value:!0});const config_1=config,debug_1$1=debug$1,encode_1$2=encode$1,number_1=number;function memToValues($){return $.store.toArray()}memory.memToValues=memToValues;function makeInMemoryStore(){const $=[];return{forEach(I){for(let U=0;U<$.length;U++)if(I($[U])==="break")return},add(I){$.push(I)},toArray(){return $}}}memory.makeInMemoryStore=makeInMemoryStore;function makeInMemoryCache(){const $=Object.create(null),I=Object.create(null);return{getValue(U){return $[U]},getSchema(U){return I[U]},forEachValue(U){for(const[q,G]of Object.entries($))if(U(q,G)==="break")return},forEachSchema(U){for(const[q,G]of Object.entries(I))if(U(q,G)==="break")return},setValue(U,q){$[U]=q},setSchema(U,q){I[U]=q},hasValue(U){return U in $},hasSchema(U){return U in I}}}memory.makeInMemoryCache=makeInMemoryCache;function makeInMemoryMemory(){return{store:makeInMemoryStore(),cache:makeInMemoryCache(),keyCount:0}}memory.makeInMemoryMemory=makeInMemoryMemory;function getValueKey($,I){if($.cache.hasValue(I))return $.cache.getValue(I);const U=$.keyCount++,q=number_1.num_to_s(U);return $.store.add(I),$.cache.setValue(I,q),q}function getSchema($,I){config_1.config.sort_key&&I.sort();const U=I.join(",");if($.cache.hasSchema(U))return $.cache.getSchema(U);const q=addValue($,I,void 0);return $.cache.setSchema(U,q),q}function addValue($,I,U){if(I===null)return"";switch(typeof I){case"undefined":if(Array.isArray(U))return addValue($,null,U);break;case"object":if(I===null)return getValueKey($,null);if(Array.isArray(I)){let q="a";for(let G=0;G<I.length;G++){const K=I[G],Y=K===null?"_":addValue($,K,I);q+="|"+Y}return q==="a"&&(q="a|"),getValueKey($,q)}else{const q=Object.keys(I);if(q.length===0)return getValueKey($,"o|");let G="o";const K=getSchema($,q);G+="|"+K;for(const Y of q){const J=I[Y],X=addValue($,J,I);G+="|"+X}return getValueKey($,G)}case"boolean":return getValueKey($,encode_1$2.encodeBool(I));case"number":return getValueKey($,encode_1$2.encodeNum(I));case"string":return getValueKey($,encode_1$2.encodeStr(I))}return debug_1$1.throwUnknownDataType(I)}memory.addValue=addValue,Object.defineProperty(core,"__esModule",{value:!0});const debug_1=debug$1,encode_1$1=encode$1,memory_1$1=memory;function compress($){const I=memory_1$1.makeInMemoryMemory(),U=memory_1$1.addValue(I,$,void 0);return[memory_1$1.memToValues(I),U]}core.compress=compress;function decodeObject($,I){if(I==="o|")return{};const U={},q=I.split("|"),G=q[1];let K=decode$1($,G);const Y=q.length;Y-2===1&&!Array.isArray(K)&&(K=[K]);for(let J=2;J<Y;J++){const X=K[J-2];let Z=q[J];Z=decode$1($,Z),U[X]=Z}return U}function decodeArray($,I){if(I==="a|")return[];const U=I.split("|"),q=U.length-1,G=new Array(q);for(let K=0;K<q;K++){let Y=U[K+1];Y=decode$1($,Y),G[K]=Y}return G}function decode$1($,I){if(I===""||I==="_")return null;const U=encode_1$1.decodeKey(I),q=$[U];if(q===null)return q;switch(typeof q){case"undefined":return q;case"number":return q;case"string":switch(q[0]+q[1]){case"b|":return encode_1$1.decodeBool(q);case"o|":return decodeObject($,q);case"n|":return encode_1$1.decodeNum(q);case"a|":return decodeArray($,q);default:return encode_1$1.decodeStr(q)}}return debug_1.throwUnknownDataType(q)}core.decode=decode$1;function decompress($){const[I,U]=$;return decode$1(I,U)}core.decompress=decompress;var helpers={};Object.defineProperty(helpers,"__esModule",{value:!0});function trimUndefined($){for(const I in $)$[I]===void 0&&delete $[I]}helpers.trimUndefined=trimUndefined;function trimUndefinedRecursively($){trimUndefinedRecursivelyLoop($,new Set)}helpers.trimUndefinedRecursively=trimUndefinedRecursively;function trimUndefinedRecursivelyLoop($,I){I.add($);for(const U in $)if($[U]===void 0)delete $[U];else{const q=$[U];q&&typeof q=="object"&&!I.has(q)&&trimUndefinedRecursivelyLoop(q,I)}}Object.defineProperty(dist$1,"__esModule",{value:!0});var core_1=core;dist$1.compress=core_1.compress,dist$1.decompress=core_1.decompress;var core_2=core;dist$1.decode=core_2.decode;var memory_1=memory;dist$1.addValue=memory_1.addValue;var helpers_1=helpers;dist$1.trimUndefined=helpers_1.trimUndefined,dist$1.trimUndefinedRecursively=helpers_1.trimUndefinedRecursively;var __dxlog_file3$3="/home/runner/work/dxos/dxos/packages/common/codec-protobuf/src/stream.ts",Stream$1=class lr{constructor(I){this._messageHandler=void 0,this._closeHandler=void 0,this._readyHandler=void 0,this._isClosed=!1,this._closeError=void 0,this._producerCleanup=void 0,this._isReady=!1,this._buffer=[],this._readyPromise=new Promise(U=>{this._resolveReadyPromise=U}),this._ctx=new Context({onError:U=>{var q,G;this._isClosed||(this._isClosed=!0,this._closeError=U,(q=this._producerCleanup)==null||q.call(this,U),(G=this._closeHandler)==null||G.call(this,U),this._ctx.dispose())}}),this._ctx.onDispose(()=>this.close());try{const U=I({ctx:this._ctx,ready:()=>{this._markAsReady()},next:q=>{if(this._isClosed){log$2("Stream is closed, dropping message.",void 0,{F:__dxlog_file3$3,L:207,S:this,C:(G,K)=>G(...K)});return}if(this._markAsReady(),this._messageHandler)try{this._messageHandler(q)}catch(G){throwUnhandledRejection(G)}else invariant(this._buffer,void 0,{F:__dxlog_file3$3,L:221,S:this,A:["this._buffer",""]}),this._buffer.push(q)},close:q=>{var G,K;if(!this._isClosed){this._isClosed=!0,this._closeError=q,(G=this._producerCleanup)==null||G.call(this,q);try{(K=this._closeHandler)==null||K.call(this,q)}catch(Y){throwUnhandledRejection(Y)}this._ctx.dispose()}}});U&&(this._producerCleanup=U)}catch(U){this._ctx.raise(U)}}static consume(I){return new Promise(U=>{const q=[];I.onReady(()=>{q.push({ready:!0})}),I.subscribe(G=>{q.push({data:G})},G=>{G?q.push({closed:!0,error:G}):q.push({closed:!0}),U(q)})})}static async consumeData(I){const U=await lr.consume(I),q=[];for(const G of U)if("data"in G)q.push(G.data);else if("closed"in G&&G.closed===!0){if(G.error)throw G.error;break}return q}static async first(I){return new Promise((U,q)=>{I.subscribe(G=>{U(G),I.close()},G=>{G?q(G):U(void 0)})})}static map(I,U){return new lr(({ready:q,next:G,close:K})=>(I.onReady(q),I.subscribe(Y=>G(U(Y)),K),()=>I.close()))}static unwrapPromise(I){return I instanceof lr?I:new lr(({ready:U,next:q,close:G})=>(I.then(K=>{K.onReady(U),K.subscribe(q,G)},K=>{G(K)}),()=>{I.then(K=>K.close(),K=>{})}))}_markAsReady(){var I;this._isReady||(this._isReady=!0,(I=this._readyHandler)==null||I.call(this),this._resolveReadyPromise())}subscribe(I,U){invariant(!this._messageHandler,"Stream is already subscribed to.",{F:__dxlog_file3$3,L:262,S:this,A:["!this._messageHandler","'Stream is already subscribed to.'"]}),invariant(!this._closeHandler,"Stream is already subscribed to.",{F:__dxlog_file3$3,L:263,S:this,A:["!this._closeHandler","'Stream is already subscribed to.'"]}),invariant(this._buffer,void 0,{F:__dxlog_file3$3,L:264,S:this,A:["this._buffer",""]});for(const q of this._buffer)try{I(q)}catch(G){throwUnhandledRejection(G)}if(this._buffer=null,this._isClosed){U==null||U(this._closeError);return}this._messageHandler=I,this._closeHandler=U}waitUntilReady(){return this._readyPromise}onReady(I){invariant(!this._readyHandler,"Stream already has a handler for the ready event.",{F:__dxlog_file3$3,L:299,S:this,A:["!this._readyHandler","'Stream already has a handler for the ready event.'"]}),this._readyHandler=I,this._isReady&&I()}async close(){var I,U;this._isClosed||(this._isClosed=!0,(I=this._producerCleanup)==null||I.call(this),(U=this._closeHandler)==null||U.call(this,void 0),await this._ctx.dispose(),this._messageHandler=void 0,this._closeHandler=void 0,this._producerCleanup=void 0)}},throwUnhandledRejection=$=>{setTimeout(()=>{throw $})},symbolTracingContext=Symbol("dxos.tracing.context"),getTracingContext=$=>$[symbolTracingContext]??($[symbolTracingContext]={infoProperties:{},metricsProperties:{}}),TRACE_SPAN_ATTRIBUTE="dxos.trace-span",TraceSender=class{constructor($){this._traceProcessor=$}streamTrace($){return new Stream$1(({ctx:I,next:U})=>{const q=(Y,J,X)=>{const Z={resourceAdded:[],resourceRemoved:[],spanAdded:[],logAdded:[]};if(Y)for(const Q of Y){const ee=this._traceProcessor.resources.get(Q);ee?Z.resourceAdded.push({resource:ee.data}):Z.resourceRemoved.push({id:Q})}else for(const Q of this._traceProcessor.resources.values())Z.resourceAdded.push({resource:Q.data});if(J)for(const Q of J){const ee=this._traceProcessor.spans.get(Q);ee&&Z.spanAdded.push({span:ee})}else for(const Q of this._traceProcessor.spans.values())Z.spanAdded.push({span:Q});if(X)for(const Q of X)Z.logAdded.push({log:Q});else for(const Q of this._traceProcessor.logs)Z.logAdded.push({log:Q});(Z.resourceAdded.length>0||Z.resourceRemoved.length>0||Z.spanAdded.length>0)&&U(Z)},K={flush:()=>{q(K.dirtyResources,K.dirtySpans,K.newLogs),K.dirtyResources.clear(),K.dirtySpans.clear(),K.newLogs.length=0},dirtyResources:new Set,dirtySpans:new Set,newLogs:[]};this._traceProcessor.subscriptions.add(K),I.onDispose(()=>{this._traceProcessor.subscriptions.delete(K)}),q(null,null,null)})}},__dxlog_file$6="/home/runner/work/dxos/dxos/packages/common/tracing/src/trace-processor.ts",ResourceEntry=class{constructor($,I,U){this.data=$,this.instance=I,this.annotation=U,this.sanitizedClassName=sanitizeClassName($.className)}getMetric($){var I;return(I=this.data.metrics)==null?void 0:I.find(U=>U.name===$)}},MAX_RESOURCE_RECORDS=2e3,MAX_SPAN_RECORDS=1e3,MAX_LOG_RECORDS=1e3,REFRESH_INTERVAL=1e3,MAX_INFO_OBJECT_DEPTH=8,TraceProcessor=class{constructor(){this.resources=new Map,this.resourceInstanceIndex=new WeakMap,this.resourceIdList=[],this.spans=new Map,this.spanIdList=[],this.logs=[],this.subscriptions=new Set,this._logProcessor=(I,U)=>{var q,G,K;switch(U.level){case LogLevel$1.ERROR:case LogLevel$1.WARN:case LogLevel$1.TRACE:{const Y=(q=U.meta)==null?void 0:q.S,J=this.resourceInstanceIndex.get(Y);if(!J)return;const X=getContextFromEntry(U)??{};for(const Q of Object.keys(X))X[Q]=sanitizeValue(X[Q],0,this);const Z={level:U.level,message:U.message,context:X,timestamp:new Date,meta:{file:((G=U.meta)==null?void 0:G.F)??"",line:((K=U.meta)==null?void 0:K.L)??0,resourceId:J.data.id}};this._pushLog(Z);break}}},log$2.addProcessor(this._logProcessor.bind(this),void 0,{F:__dxlog_file$6,L:81,S:this,C:(I,U)=>I(...U)});const $=setInterval(this.refresh.bind(this),REFRESH_INTERVAL);unrefTimeout($)}traceResourceConstructor($){const I=this.resources.size,U=getTracingContext(Object.getPrototypeOf($.instance));for(const G of Object.keys(U.metricsProperties))$.instance[G]._assign($.instance,G);const q=new ResourceEntry({id:I,className:$.constructor.name,instanceId:getPrototypeSpecificInstanceId($.instance),info:this.getResourceInfo($.instance),links:[],metrics:this.getResourceMetrics($.instance)},new WeakRef($.instance),$.annotation);this.resources.set(I,q),this.resourceInstanceIndex.set($.instance,q),this.resourceIdList.push(I),this.resourceIdList.length>MAX_RESOURCE_RECORDS&&this._clearResources(),this._markResourceDirty(I)}getResourceInfo($){const I={},U=getTracingContext(Object.getPrototypeOf($));for(const[q,{options:G}]of Object.entries(U.infoProperties))try{const K=typeof $[q]=="function"?$[q]():$[q];G.enum?I[q]=G.enum[K]:I[q]=sanitizeValue(K,G.depth===void 0?1:G.depth??MAX_INFO_OBJECT_DEPTH,this)}catch(K){I[q]=K.message}return I}getResourceMetrics($){const I=[],U=getTracingContext(Object.getPrototypeOf($));for(const[q,G]of Object.entries(U.metricsProperties))I.push($[q].getData());return I}traceSpan($){const I=new TracingSpan(this,$);return this._flushSpan(I),I}addLink($,I,U){}getResourceId($){const I=this.resourceInstanceIndex.get($);return I?I.data.id:null}createTraceSender(){return new TraceSender(this)}refresh(){var $,I;for(const U of this.resources.values()){const q=U.instance.deref();if(!q)continue;const G=getTracingContext(Object.getPrototypeOf(q)),K=performance.now();for(const Z of Object.keys(G.metricsProperties))(I=($=q[Z])._tick)==null||I.call($,K);let Y=!1;const J=U.data.info;U.data.info=this.getResourceInfo(q),Y||(Y=!areEqualShallow(J,U.data.info));const X=U.data.metrics;U.data.metrics=this.getResourceMetrics(q),Y||(Y=!areEqualShallow(X,U.data.metrics)),this._markResourceDirty(U.data.id)}for(const U of this.subscriptions)U.flush()}findResourcesByClassName($){return[...this.resources.values()].filter(I=>I.data.className===$||I.sanitizedClassName===$)}findByAnnotation($){return[...this.resources.values()].filter(I=>I.annotation===$)}getDiagnostics(){return this.refresh(),{resources:Object.fromEntries(Array.from(this.resources.entries()).map(([$,I])=>[`${I.sanitizedClassName}#${I.data.instanceId}`,I.data])),spans:Array.from(this.spans.values()),logs:this.logs.filter($=>$.level>=LogLevel$1.INFO)}}_flushSpan($){const I=$.serialize();this.spans.set(I.id,I),this.spanIdList.push(I.id),this.spanIdList.length>MAX_SPAN_RECORDS&&this._clearSpans(),this._markSpanDirty(I.id)}_markResourceDirty($){for(const I of this.subscriptions)I.dirtyResources.add($)}_markSpanDirty($){for(const I of this.subscriptions)I.dirtySpans.add($)}_clearResources(){for(;this.resourceIdList.length>MAX_RESOURCE_RECORDS;){const $=this.resourceIdList.shift();this.resources.delete($)}}_clearSpans(){for(;this.spanIdList.length>MAX_SPAN_RECORDS;){const $=this.spanIdList.shift();this.spans.delete($)}}_pushLog($){this.logs.push($),this.logs.length>MAX_LOG_RECORDS&&this.logs.shift();for(const I of this.subscriptions)I.newLogs.push($)}},TracingSpan=(Xn=class{constructor(I,U){if(this._traceProcessor=I,this.parentId=null,this.resourceId=null,this.endTs=null,this.error=null,this._ctx=null,this.id=Xn.nextId++,this.methodName=U.methodName,this.resourceId=I.getResourceId(U.instance),this.startTs=performance.now(),this._showInBrowserTimeline=U.showInBrowserTimeline,U.parentCtx){this._ctx=U.parentCtx.derive({attributes:{[TRACE_SPAN_ATTRIBUTE]:this.id}});const q=U.parentCtx.getAttribute(TRACE_SPAN_ATTRIBUTE);typeof q=="number"&&(this.parentId=q)}}get ctx(){return this._ctx}markSuccess(){this.endTs=performance.now(),this._traceProcessor._flushSpan(this),this._showInBrowserTimeline&&this._markInBrowserTimeline()}markError(I){this.endTs=performance.now(),this.error=serializeError(I),this._traceProcessor._flushSpan(this),this._showInBrowserTimeline&&this._markInBrowserTimeline()}serialize(){var I;return{id:this.id,resourceId:this.resourceId??void 0,methodName:this.methodName,parentId:this.parentId??void 0,startTs:this.startTs.toFixed(3),endTs:((I=this.endTs)==null?void 0:I.toFixed(3))??void 0,error:this.error??void 0}}_markInBrowserTimeline(){const I=this._traceProcessor.resources.get(this.resourceId),U=I?`${I.sanitizedClassName}#${I.data.instanceId}.${this.methodName}`:this.methodName;performance.measure(U,{start:this.startTs,end:this.endTs})}},Xn.nextId=0,Xn),serializeError=$=>$ instanceof Error?{name:$.name,message:$.message}:{message:String($)},TRACE_PROCESSOR=globalThis.TRACE_PROCESSOR??(globalThis.TRACE_PROCESSOR=new TraceProcessor),sanitizeValue=($,I,U)=>{switch(typeof $){case"string":case"number":case"boolean":case"undefined":return $;case"object":case"function":if($===null)return $;{const q=U.resourceInstanceIndex.get($);if(q)return`${q.sanitizedClassName}#${q.data.instanceId}`}if(typeof $.toJSON=="function")return sanitizeValue($.toJSON(),I,U);if(I>0){if(isSetLike($))return Object.fromEntries(Array.from($.entries()).map(q=>sanitizeValue(q,I-1,U)));if(isMapLike($))return Object.fromEntries(Array.from($.entries()).map(([q,G])=>[q,sanitizeValue(G,I-1,U)]));if(Array.isArray($))return $.map(q=>sanitizeValue(q,I-1,U));if(typeof $=="object"){const q={};for(const G of Object.keys($))q[G]=sanitizeValue($[G],I-1,U);return q}}return typeof $.truncate=="function"?$.truncate():$.toString()}},areEqualShallow=($,I)=>{for(const U in $)if(!(U in I)||$[U]!==I[U])return!1;for(const U in I)if(!(U in $)||$[U]!==I[U])return!1;return!0},sanitizeClassName=$=>{const I=/[^_](\d+)$/,U=$.match(I);return U?$.slice(0,-U[1].length):$},isSetLike=$=>$ instanceof Set||typeof $=="object"&&$!==null&&Object.getPrototypeOf($).constructor.name==="ComplexSet",isMapLike=$=>$ instanceof Map||typeof $=="object"&&$!==null&&Object.getPrototypeOf($).constructor.name==="ComplexMap",resource=$=>I=>{const U=class extends I{constructor(...q){super(...q),TRACE_PROCESSOR.traceResourceConstructor({constructor:I,annotation:$==null?void 0:$.annotation,instance:this})}};return Object.defineProperty(U,"name",{value:I.name}),U},info=($={})=>(I,U,q)=>{getTracingContext(I).infoProperties[U]={options:$}},mark=$=>{performance.mark($)},span=({showInBrowserTimeline:$=!1}={})=>(I,U,q)=>{const G=q.value;q.value=async function(...K){const Y=K[0]instanceof Context?K[0]:null,J=TRACE_PROCESSOR.traceSpan({parentCtx:Y,methodName:U,instance:this,showInBrowserTimeline:$}),X=J.ctx?[J.ctx,...K.slice(1)]:K;try{return await G.apply(this,X)}catch(Z){throw J.markError(Z),Z}finally{J.markSuccess()}}},metricsCounter=()=>($,I,U)=>{getTracingContext($).metricsProperties[I]={}},addLink=($,I,U={})=>{TRACE_PROCESSOR.addLink($,I,U)},trace={resource,info,mark,span,metricsCounter,addLink},Runtime;(function($){(function(I){(function(U){(function(q){q[q.RAM=0]="RAM",q[q.IDB=1]="IDB",q[q.CHROME=2]="CHROME",q[q.FIREFOX=3]="FIREFOX",q[q.NODE=4]="NODE",q[q.WEBFS=5]="WEBFS",q[q.LEVELJS=11]="LEVELJS",q[q.JSONDOWN=12]="JSONDOWN"})(U.StorageDriver||(U.StorageDriver={}))})(I.Storage||(I.Storage={}))})($.Client||($.Client={}))})(Runtime||(Runtime={}));var lib={},boolean$1={};Object.defineProperty(boolean$1,"__esModule",{value:!0}),boolean$1.boolean=void 0;const boolean=function($){switch(Object.prototype.toString.call($)){case"[object String]":return["true","t","yes","y","on","1"].includes($.trim().toLowerCase());case"[object Number]":return $.valueOf()===1;case"[object Boolean]":return $.valueOf();default:return!1}};boolean$1.boolean=boolean;var isBooleanable$1={};Object.defineProperty(isBooleanable$1,"__esModule",{value:!0}),isBooleanable$1.isBooleanable=void 0;const isBooleanable=function($){switch(Object.prototype.toString.call($)){case"[object String]":return["true","t","yes","y","on","1","false","f","no","n","off","0"].includes($.trim().toLowerCase());case"[object Number]":return[0,1].includes($.valueOf());case"[object Boolean]":return!0;default:return!1}};isBooleanable$1.isBooleanable=isBooleanable,function($){Object.defineProperty($,"__esModule",{value:!0}),$.isBooleanable=$.boolean=void 0;const I=boolean$1;Object.defineProperty($,"boolean",{enumerable:!0,get:function(){return I.boolean}});const U=isBooleanable$1;Object.defineProperty($,"isBooleanable",{enumerable:!0,get:function(){return U.isBooleanable}})}(lib);var lodash_ismatch={exports:{}};lodash_ismatch.exports,function($,I){var U=200,q="__lodash_hash_undefined__",G=1,K=2,Y=9007199254740991,J="[object Arguments]",X="[object Array]",Z="[object Boolean]",Q="[object Date]",ee="[object Error]",te="[object Function]",ne="[object GeneratorFunction]",ie="[object Map]",oe="[object Number]",ce="[object Object]",fe="[object Promise]",se="[object RegExp]",de="[object Set]",ue="[object String]",pe="[object Symbol]",ve="[object WeakMap]",me="[object ArrayBuffer]",be="[object DataView]",_e="[object Float32Array]",Se="[object Float64Array]",xe="[object Int8Array]",ke="[object Int16Array]",De="[object Int32Array]",Be="[object Uint8Array]",Ve="[object Uint8ClampedArray]",nt="[object Uint16Array]",ot="[object Uint32Array]",ft=/[\\^$.*+?()[\]{}|]/g,it=/^\[object .+?Constructor\]$/,ut=/^(?:0|[1-9]\d*)$/,et={};et[_e]=et[Se]=et[xe]=et[ke]=et[De]=et[Be]=et[Ve]=et[nt]=et[ot]=!0,et[J]=et[X]=et[me]=et[Z]=et[be]=et[Q]=et[ee]=et[te]=et[ie]=et[oe]=et[ce]=et[se]=et[de]=et[ue]=et[ve]=!1;var Ue=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,We=typeof self=="object"&&self&&self.Object===Object&&self,tt=Ue||We||Function("return this")(),vt=I&&!I.nodeType&&I,je=vt&&!0&&$&&!$.nodeType&&$,ze=je&&je.exports===vt,Ae=ze&&Ue.process,Re=function(){try{return Ae&&Ae.binding("util")}catch{}}(),Ce=Re&&Re.isTypedArray;function ge(Ne,Qe){for(var yt=-1,Pt=Ne?Ne.length:0;++yt<Pt;)if(Qe(Ne[yt],yt,Ne))return!0;return!1}function ye(Ne,Qe){for(var yt=-1,Pt=Array(Ne);++yt<Ne;)Pt[yt]=Qe(yt);return Pt}function Me(Ne){return function(Qe){return Ne(Qe)}}function Ke(Ne,Qe){return Ne==null?void 0:Ne[Qe]}function st(Ne){var Qe=!1;if(Ne!=null&&typeof Ne.toString!="function")try{Qe=!!(Ne+"")}catch{}return Qe}function dt(Ne){var Qe=-1,yt=Array(Ne.size);return Ne.forEach(function(Pt,tn){yt[++Qe]=[tn,Pt]}),yt}function $t(Ne,Qe){return function(yt){return Ne(Qe(yt))}}function Et(Ne){var Qe=-1,yt=Array(Ne.size);return Ne.forEach(function(Pt){yt[++Qe]=Pt}),yt}var rt=Array.prototype,jt=Function.prototype,Gt=Object.prototype,At=tt["__core-js_shared__"],zt=function(){var Ne=/[^.]+$/.exec(At&&At.keys&&At.keys.IE_PROTO||"");return Ne?"Symbol(src)_1."+Ne:""}(),nn=jt.toString,St=Gt.hasOwnProperty,Ut=Gt.toString,le=RegExp("^"+nn.call(St).replace(ft,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),re=tt.Symbol,ae=tt.Uint8Array,he=Gt.propertyIsEnumerable,we=rt.splice,Ee=$t(Object.keys,Object),Le=Ge(tt,"DataView"),bt=Ge(tt,"Map"),Lt=Ge(tt,"Promise"),Ct=Ge(tt,"Set"),It=Ge(tt,"WeakMap"),Tt=Ge(Object,"create"),Sn=Ht(Le),gn=Ht(bt),pn=Ht(Lt),vn=Ht(Ct),Tn=Ht(It),dn=re?re.prototype:void 0,Pn=dn?dn.valueOf:void 0;function $n(Ne){var Qe=-1,yt=Ne?Ne.length:0;for(this.clear();++Qe<yt;){var Pt=Ne[Qe];this.set(Pt[0],Pt[1])}}function Vn(){this.__data__=Tt?Tt(null):{}}function Nn(Ne){return this.has(Ne)&&delete this.__data__[Ne]}function Fn(Ne){var Qe=this.__data__;if(Tt){var yt=Qe[Ne];return yt===q?void 0:yt}return St.call(Qe,Ne)?Qe[Ne]:void 0}function fn(Ne){var Qe=this.__data__;return Tt?Qe[Ne]!==void 0:St.call(Qe,Ne)}function Gn(Ne,Qe){var yt=this.__data__;return yt[Ne]=Tt&&Qe===void 0?q:Qe,this}$n.prototype.clear=Vn,$n.prototype.delete=Nn,$n.prototype.get=Fn,$n.prototype.has=fn,$n.prototype.set=Gn;function bn(Ne){var Qe=-1,yt=Ne?Ne.length:0;for(this.clear();++Qe<yt;){var Pt=Ne[Qe];this.set(Pt[0],Pt[1])}}function Kn(){this.__data__=[]}function He(Ne){var Qe=this.__data__,yt=An(Qe,Ne);if(yt<0)return!1;var Pt=Qe.length-1;return yt==Pt?Qe.pop():we.call(Qe,yt,1),!0}function pt(Ne){var Qe=this.__data__,yt=An(Qe,Ne);return yt<0?void 0:Qe[yt][1]}function kt(Ne){return An(this.__data__,Ne)>-1}function Pe(Ne,Qe){var yt=this.__data__,Pt=An(yt,Ne);return Pt<0?yt.push([Ne,Qe]):yt[Pt][1]=Qe,this}bn.prototype.clear=Kn,bn.prototype.delete=He,bn.prototype.get=pt,bn.prototype.has=kt,bn.prototype.set=Pe;function at(Ne){var Qe=-1,yt=Ne?Ne.length:0;for(this.clear();++Qe<yt;){var Pt=Ne[Qe];this.set(Pt[0],Pt[1])}}function lt(){this.__data__={hash:new $n,map:new(bt||bn),string:new $n}}function xt(Ne){return Ye(this,Ne).delete(Ne)}function Rt(Ne){return Ye(this,Ne).get(Ne)}function Dt(Ne){return Ye(this,Ne).has(Ne)}function Mt(Ne,Qe){return Ye(this,Ne).set(Ne,Qe),this}at.prototype.clear=lt,at.prototype.delete=xt,at.prototype.get=Rt,at.prototype.has=Dt,at.prototype.set=Mt;function Ot(Ne){var Qe=-1,yt=Ne?Ne.length:0;for(this.__data__=new at;++Qe<yt;)this.add(Ne[Qe])}function Xt(Ne){return this.__data__.set(Ne,q),this}function Zt(Ne){return this.__data__.has(Ne)}Ot.prototype.add=Ot.prototype.push=Xt,Ot.prototype.has=Zt;function Kt(Ne){this.__data__=new bn(Ne)}function an(){this.__data__=new bn}function xn(Ne){return this.__data__.delete(Ne)}function Yn(Ne){return this.__data__.get(Ne)}function ln(Ne){return this.__data__.has(Ne)}function Bn(Ne,Qe){var yt=this.__data__;if(yt instanceof bn){var Pt=yt.__data__;if(!bt||Pt.length<U-1)return Pt.push([Ne,Qe]),this;yt=this.__data__=new at(Pt)}return yt.set(Ne,Qe),this}Kt.prototype.clear=an,Kt.prototype.delete=xn,Kt.prototype.get=Yn,Kt.prototype.has=ln,Kt.prototype.set=Bn;function jn(Ne,Qe){var yt=cn(Ne)||en(Ne)?ye(Ne.length,String):[],Pt=yt.length,tn=!!Pt;for(var Wt in Ne)(Qe||St.call(Ne,Wt))&&!(tn&&(Wt=="length"||ht(Wt,Pt)))&&yt.push(Wt);return yt}function An(Ne,Qe){for(var yt=Ne.length;yt--;)if(Yt(Ne[yt][0],Qe))return yt;return-1}function Un(Ne){return Ut.call(Ne)}function Qn(Ne,Qe,yt,Pt,tn){return Ne===Qe?!0:Ne==null||Qe==null||!Wn(Ne)&&!Mn(Qe)?Ne!==Ne&&Qe!==Qe:ir(Ne,Qe,Qn,yt,Pt,tn)}function ir(Ne,Qe,yt,Pt,tn,Wt){var hn=cn(Ne),rn=cn(Qe),Qt=X,un=X;hn||(Qt=ct(Ne),Qt=Qt==J?ce:Qt),rn||(un=ct(Qe),un=un==J?ce:un);var yn=Qt==ce&&!st(Ne),kn=un==ce&&!st(Qe),mn=Qt==un;if(mn&&!yn)return Wt||(Wt=new Kt),hn||sr(Ne)?Te(Ne,Qe,yt,Pt,tn,Wt):qe(Ne,Qe,Qt,yt,Pt,tn,Wt);if(!(tn&K)){var On=yn&&St.call(Ne,"__wrapped__"),Rn=kn&&St.call(Qe,"__wrapped__");if(On||Rn){var Ln=On?Ne.value():Ne,Dn=Rn?Qe.value():Qe;return Wt||(Wt=new Kt),yt(Ln,Dn,Pt,tn,Wt)}}return mn?(Wt||(Wt=new Kt),Oe(Ne,Qe,yt,Pt,tn,Wt)):!1}function ar(Ne,Qe,yt,Pt){var tn=yt.length,Wt=tn,hn=!Pt;if(Ne==null)return!Wt;for(Ne=Object(Ne);tn--;){var rn=yt[tn];if(hn&&rn[2]?rn[1]!==Ne[rn[0]]:!(rn[0]in Ne))return!1}for(;++tn<Wt;){rn=yt[tn];var Qt=rn[0],un=Ne[Qt],yn=rn[1];if(hn&&rn[2]){if(un===void 0&&!(Qt in Ne))return!1}else{var kn=new Kt;if(Pt)var mn=Pt(un,yn,Qt,Ne,Qe,kn);if(!(mn===void 0?Qn(yn,un,Pt,G|K,kn):mn))return!1}}return!0}function zn(Ne){if(!Wn(Ne)||gt(Ne))return!1;var Qe=Hn(Ne)||st(Ne)?le:it;return Qe.test(Ht(Ne))}function or(Ne){return Mn(Ne)&&er(Ne.length)&&!!et[Ut.call(Ne)]}function nr(Ne){if(!wt(Ne))return Ee(Ne);var Qe=[];for(var yt in Object(Ne))St.call(Ne,yt)&&yt!="constructor"&&Qe.push(yt);return Qe}function Te(Ne,Qe,yt,Pt,tn,Wt){var hn=tn&K,rn=Ne.length,Qt=Qe.length;if(rn!=Qt&&!(hn&&Qt>rn))return!1;var un=Wt.get(Ne);if(un&&Wt.get(Qe))return un==Qe;var yn=-1,kn=!0,mn=tn&G?new Ot:void 0;for(Wt.set(Ne,Qe),Wt.set(Qe,Ne);++yn<rn;){var On=Ne[yn],Rn=Qe[yn];if(Pt)var Ln=hn?Pt(Rn,On,yn,Qe,Ne,Wt):Pt(On,Rn,yn,Ne,Qe,Wt);if(Ln!==void 0){if(Ln)continue;kn=!1;break}if(mn){if(!ge(Qe,function(Dn,Ie){if(!mn.has(Ie)&&(On===Dn||yt(On,Dn,Pt,tn,Wt)))return mn.add(Ie)})){kn=!1;break}}else if(!(On===Rn||yt(On,Rn,Pt,tn,Wt))){kn=!1;break}}return Wt.delete(Ne),Wt.delete(Qe),kn}function qe(Ne,Qe,yt,Pt,tn,Wt,hn){switch(yt){case be:if(Ne.byteLength!=Qe.byteLength||Ne.byteOffset!=Qe.byteOffset)return!1;Ne=Ne.buffer,Qe=Qe.buffer;case me:return!(Ne.byteLength!=Qe.byteLength||!Pt(new ae(Ne),new ae(Qe)));case Z:case Q:case oe:return Yt(+Ne,+Qe);case ee:return Ne.name==Qe.name&&Ne.message==Qe.message;case se:case ue:return Ne==Qe+"";case ie:var rn=dt;case de:var Qt=Wt&K;if(rn||(rn=Et),Ne.size!=Qe.size&&!Qt)return!1;var un=hn.get(Ne);if(un)return un==Qe;Wt|=G,hn.set(Ne,Qe);var yn=Te(rn(Ne),rn(Qe),Pt,tn,Wt,hn);return hn.delete(Ne),yn;case pe:if(Pn)return Pn.call(Ne)==Pn.call(Qe)}return!1}function Oe(Ne,Qe,yt,Pt,tn,Wt){var hn=tn&K,rn=qn(Ne),Qt=rn.length,un=qn(Qe),yn=un.length;if(Qt!=yn&&!hn)return!1;for(var kn=Qt;kn--;){var mn=rn[kn];if(!(hn?mn in Qe:St.call(Qe,mn)))return!1}var On=Wt.get(Ne);if(On&&Wt.get(Qe))return On==Qe;var Rn=!0;Wt.set(Ne,Qe),Wt.set(Qe,Ne);for(var Ln=hn;++kn<Qt;){mn=rn[kn];var Dn=Ne[mn],Ie=Qe[mn];if(Pt)var Je=hn?Pt(Ie,Dn,mn,Qe,Ne,Wt):Pt(Dn,Ie,mn,Ne,Qe,Wt);if(!(Je===void 0?Dn===Ie||yt(Dn,Ie,Pt,tn,Wt):Je)){Rn=!1;break}Ln||(Ln=mn=="constructor")}if(Rn&&!Ln){var $e=Ne.constructor,Fe=Qe.constructor;$e!=Fe&&"constructor"in Ne&&"constructor"in Qe&&!(typeof $e=="function"&&$e instanceof $e&&typeof Fe=="function"&&Fe instanceof Fe)&&(Rn=!1)}return Wt.delete(Ne),Wt.delete(Qe),Rn}function Ye(Ne,Qe){var yt=Ne.__data__;return mt(Qe)?yt[typeof Qe=="string"?"string":"hash"]:yt.map}function Ze(Ne){for(var Qe=qn(Ne),yt=Qe.length;yt--;){var Pt=Qe[yt],tn=Ne[Pt];Qe[yt]=[Pt,tn,Ft(tn)]}return Qe}function Ge(Ne,Qe){var yt=Ke(Ne,Qe);return zn(yt)?yt:void 0}var ct=Un;(Le&&ct(new Le(new ArrayBuffer(1)))!=be||bt&&ct(new bt)!=ie||Lt&&ct(Lt.resolve())!=fe||Ct&&ct(new Ct)!=de||It&&ct(new It)!=ve)&&(ct=function(Ne){var Qe=Ut.call(Ne),yt=Qe==ce?Ne.constructor:void 0,Pt=yt?Ht(yt):void 0;if(Pt)switch(Pt){case Sn:return be;case gn:return ie;case pn:return fe;case vn:return de;case Tn:return ve}return Qe});function ht(Ne,Qe){return Qe=Qe??Y,!!Qe&&(typeof Ne=="number"||ut.test(Ne))&&Ne>-1&&Ne%1==0&&Ne<Qe}function mt(Ne){var Qe=typeof Ne;return Qe=="string"||Qe=="number"||Qe=="symbol"||Qe=="boolean"?Ne!=="__proto__":Ne===null}function gt(Ne){return!!zt&&zt in Ne}function wt(Ne){var Qe=Ne&&Ne.constructor,yt=typeof Qe=="function"&&Qe.prototype||Gt;return Ne===yt}function Ft(Ne){return Ne===Ne&&!Wn(Ne)}function Ht(Ne){if(Ne!=null){try{return nn.call(Ne)}catch{}try{return Ne+""}catch{}}return""}function Yt(Ne,Qe){return Ne===Qe||Ne!==Ne&&Qe!==Qe}function en(Ne){return wn(Ne)&&St.call(Ne,"callee")&&(!he.call(Ne,"callee")||Ut.call(Ne)==J)}var cn=Array.isArray;function sn(Ne){return Ne!=null&&er(Ne.length)&&!Hn(Ne)}function wn(Ne){return Mn(Ne)&&sn(Ne)}function Hn(Ne){var Qe=Wn(Ne)?Ut.call(Ne):"";return Qe==te||Qe==ne}function er(Ne){return typeof Ne=="number"&&Ne>-1&&Ne%1==0&&Ne<=Y}function Wn(Ne){var Qe=typeof Ne;return!!Ne&&(Qe=="object"||Qe=="function")}function Mn(Ne){return!!Ne&&typeof Ne=="object"}function cr(Ne,Qe){return Ne===Qe||ar(Ne,Qe,Ze(Qe))}var sr=Ce?Me(Ce):or;function qn(Ne){return sn(Ne)?jn(Ne):nr(Ne)}$.exports=cr}(lodash_ismatch,lodash_ismatch.exports);var lodash_ismatchExports=lodash_ismatch.exports;const isMatch=getDefaultExportFromCjs(lodash_ismatchExports);var FUNC_ERROR_TEXT="Expected a function",HASH_UNDEFINED="__lodash_hash_undefined__",INFINITY=1/0,funcTag="[object Function]",genTag="[object GeneratorFunction]",symbolTag="[object Symbol]",reLeadingDot=/^\./,rePropName=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,reRegExpChar=/[\\^$.*+?()[\]{}|]/g,reEscapeChar=/\\(\\)?/g,reIsHostCtor=/^\[object .+?Constructor\]$/,freeGlobal=typeof commonjsGlobal=="object"&&commonjsGlobal&&commonjsGlobal.Object===Object&&commonjsGlobal,freeSelf=typeof self=="object"&&self&&self.Object===Object&&self,root=freeGlobal||freeSelf||Function("return this")();function getValue$1($,I){return $==null?void 0:$[I]}function isHostObject($){var I=!1;if($!=null&&typeof $.toString!="function")try{I=!!($+"")}catch{}return I}var arrayProto=Array.prototype,funcProto=Function.prototype,objectProto=Object.prototype,coreJsData=root["__core-js_shared__"],maskSrcKey=function(){var $=/[^.]+$/.exec(coreJsData&&coreJsData.keys&&coreJsData.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),funcToString=funcProto.toString,hasOwnProperty=objectProto.hasOwnProperty,objectToString=objectProto.toString,reIsNative=RegExp("^"+funcToString.call(hasOwnProperty).replace(reRegExpChar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Symbol$1=root.Symbol,splice=arrayProto.splice,Map$1=getNative(root,"Map"),nativeCreate=getNative(Object,"create"),symbolProto=Symbol$1?Symbol$1.prototype:void 0,symbolToString=symbolProto?symbolProto.toString:void 0;function Hash($){var I=-1,U=$?$.length:0;for(this.clear();++I<U;){var q=$[I];this.set(q[0],q[1])}}function hashClear(){this.__data__=nativeCreate?nativeCreate(null):{}}function hashDelete($){return this.has($)&&delete this.__data__[$]}function hashGet($){var I=this.__data__;if(nativeCreate){var U=I[$];return U===HASH_UNDEFINED?void 0:U}return hasOwnProperty.call(I,$)?I[$]:void 0}function hashHas($){var I=this.__data__;return nativeCreate?I[$]!==void 0:hasOwnProperty.call(I,$)}function hashSet($,I){var U=this.__data__;return U[$]=nativeCreate&&I===void 0?HASH_UNDEFINED:I,this}Hash.prototype.clear=hashClear,Hash.prototype.delete=hashDelete,Hash.prototype.get=hashGet,Hash.prototype.has=hashHas,Hash.prototype.set=hashSet;function ListCache($){var I=-1,U=$?$.length:0;for(this.clear();++I<U;){var q=$[I];this.set(q[0],q[1])}}function listCacheClear(){this.__data__=[]}function listCacheDelete($){var I=this.__data__,U=assocIndexOf(I,$);if(U<0)return!1;var q=I.length-1;return U==q?I.pop():splice.call(I,U,1),!0}function listCacheGet($){var I=this.__data__,U=assocIndexOf(I,$);return U<0?void 0:I[U][1]}function listCacheHas($){return assocIndexOf(this.__data__,$)>-1}function listCacheSet($,I){var U=this.__data__,q=assocIndexOf(U,$);return q<0?U.push([$,I]):U[q][1]=I,this}ListCache.prototype.clear=listCacheClear,ListCache.prototype.delete=listCacheDelete,ListCache.prototype.get=listCacheGet,ListCache.prototype.has=listCacheHas,ListCache.prototype.set=listCacheSet;function MapCache($){var I=-1,U=$?$.length:0;for(this.clear();++I<U;){var q=$[I];this.set(q[0],q[1])}}function mapCacheClear(){this.__data__={hash:new Hash,map:new(Map$1||ListCache),string:new Hash}}function mapCacheDelete($){return getMapData(this,$).delete($)}function mapCacheGet($){return getMapData(this,$).get($)}function mapCacheHas($){return getMapData(this,$).has($)}function mapCacheSet($,I){return getMapData(this,$).set($,I),this}MapCache.prototype.clear=mapCacheClear,MapCache.prototype.delete=mapCacheDelete,MapCache.prototype.get=mapCacheGet,MapCache.prototype.has=mapCacheHas,MapCache.prototype.set=mapCacheSet;function assocIndexOf($,I){for(var U=$.length;U--;)if(eq($[U][0],I))return U;return-1}function baseIsNative($){if(!isObject($)||isMasked($))return!1;var I=isFunction$1($)||isHostObject($)?reIsNative:reIsHostCtor;return I.test(toSource($))}function baseToString($){if(typeof $=="string")return $;if(isSymbol($))return symbolToString?symbolToString.call($):"";var I=$+"";return I=="0"&&1/$==-INFINITY?"-0":I}function getMapData($,I){var U=$.__data__;return isKeyable(I)?U[typeof I=="string"?"string":"hash"]:U.map}function getNative($,I){var U=getValue$1($,I);return baseIsNative(U)?U:void 0}function isKeyable($){var I=typeof $;return I=="string"||I=="number"||I=="symbol"||I=="boolean"?$!=="__proto__":$===null}function isMasked($){return!!maskSrcKey&&maskSrcKey in $}memoize(function($){$=toString($);var I=[];return reLeadingDot.test($)&&I.push(""),$.replace(rePropName,function(U,q,G,K){I.push(G?K.replace(reEscapeChar,"$1"):q||U)}),I});function toSource($){if($!=null){try{return funcToString.call($)}catch{}try{return $+""}catch{}}return""}function memoize($,I){if(typeof $!="function"||I&&typeof I!="function")throw new TypeError(FUNC_ERROR_TEXT);var U=function(){var q=arguments,G=I?I.apply(this,q):q[0],K=U.cache;if(K.has(G))return K.get(G);var Y=$.apply(this,q);return U.cache=K.set(G,Y),Y};return U.cache=new(memoize.Cache||MapCache),U}memoize.Cache=MapCache;function eq($,I){return $===I||$!==$&&I!==I}function isFunction$1($){var I=isObject($)?objectToString.call($):"";return I==funcTag||I==genTag}function isObject($){var I=typeof $;return!!$&&(I=="object"||I=="function")}function isObjectLike($){return!!$&&typeof $=="object"}function isSymbol($){return typeof $=="symbol"||isObjectLike($)&&objectToString.call($)==symbolTag}function toString($){return $==null?"":baseToString($)}function commonjsRequire($){throw new Error('Could not dynamically require "'+$+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var localforage={exports:{}};/*!
|
|
908
908
|
localForage -- Offline Storage, Improved
|
|
909
909
|
Version 1.10.0
|
|
910
910
|
https://localforage.github.io/localForage
|
|
911
911
|
(c) 2013-2017 Mozilla, Apache License 2.0
|
|
912
|
-
*/(function($,I){(function(U){$.exports=U()})(function(){return function U(q,G,K){function Y(Z,Q){if(!G[Z]){if(!q[Z]){var ee=typeof commonjsRequire=="function"&&commonjsRequire;if(!Q&&ee)return ee(Z,!0);if(J)return J(Z,!0);var te=new Error("Cannot find module '"+Z+"'");throw te.code="MODULE_NOT_FOUND",te}var ne=G[Z]={exports:{}};q[Z][0].call(ne.exports,function(ie){var oe=q[Z][1][ie];return Y(oe||ie)},ne,ne.exports,U,q,G,K)}return G[Z].exports}for(var J=typeof commonjsRequire=="function"&&commonjsRequire,X=0;X<K.length;X++)Y(K[X]);return Y}({1:[function(U,q,G){(function(K){var Y=K.MutationObserver||K.WebKitMutationObserver,J;if(Y){var X=0,Z=new Y(ie),Q=K.document.createTextNode("");Z.observe(Q,{characterData:!0}),J=function(){Q.data=X=++X%2}}else if(!K.setImmediate&&typeof K.MessageChannel<"u"){var ee=new K.MessageChannel;ee.port1.onmessage=ie,J=function(){ee.port2.postMessage(0)}}else"document"in K&&"onreadystatechange"in K.document.createElement("script")?J=function(){var ce=K.document.createElement("script");ce.onreadystatechange=function(){ie(),ce.onreadystatechange=null,ce.parentNode.removeChild(ce),ce=null},K.document.documentElement.appendChild(ce)}:J=function(){setTimeout(ie,0)};var te,ne=[];function ie(){te=!0;for(var ce,fe,se=ne.length;se;){for(fe=ne,ne=[],ce=-1;++ce<se;)fe[ce]();se=ne.length}te=!1}q.exports=oe;function oe(ce){ne.push(ce)===1&&!te&&J()}}).call(this,typeof commonjsGlobal<"u"?commonjsGlobal:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(U,q,G){var K=U(1);function Y(){}var J={},X=["REJECTED"],Z=["FULFILLED"],Q=["PENDING"];q.exports=ee;function ee(pe){if(typeof pe!="function")throw new TypeError("resolver must be a function");this.state=Q,this.queue=[],this.outcome=void 0,pe!==Y&&oe(this,pe)}ee.prototype.catch=function(pe){return this.then(null,pe)},ee.prototype.then=function(pe,ve){if(typeof pe!="function"&&this.state===Z||typeof ve!="function"&&this.state===X)return this;var me=new this.constructor(Y);if(this.state!==Q){var be=this.state===Z?pe:ve;ne(me,be,this.outcome)}else this.queue.push(new te(me,pe,ve));return me};function te(pe,ve,me){this.promise=pe,typeof ve=="function"&&(this.onFulfilled=ve,this.callFulfilled=this.otherCallFulfilled),typeof me=="function"&&(this.onRejected=me,this.callRejected=this.otherCallRejected)}te.prototype.callFulfilled=function(pe){J.resolve(this.promise,pe)},te.prototype.otherCallFulfilled=function(pe){ne(this.promise,this.onFulfilled,pe)},te.prototype.callRejected=function(pe){J.reject(this.promise,pe)},te.prototype.otherCallRejected=function(pe){ne(this.promise,this.onRejected,pe)};function ne(pe,ve,me){K(function(){var be;try{be=ve(me)}catch(_e){return J.reject(pe,_e)}be===pe?J.reject(pe,new TypeError("Cannot resolve promise with itself")):J.resolve(pe,be)})}J.resolve=function(pe,ve){var me=ce(ie,ve);if(me.status==="error")return J.reject(pe,me.value);var be=me.value;if(be)oe(pe,be);else{pe.state=Z,pe.outcome=ve;for(var _e=-1,Se=pe.queue.length;++_e<Se;)pe.queue[_e].callFulfilled(ve)}return pe},J.reject=function(pe,ve){pe.state=X,pe.outcome=ve;for(var me=-1,be=pe.queue.length;++me<be;)pe.queue[me].callRejected(ve);return pe};function ie(pe){var ve=pe&&pe.then;if(pe&&(typeof pe=="object"||typeof pe=="function")&&typeof ve=="function")return function(){ve.apply(pe,arguments)}}function oe(pe,ve){var me=!1;function be(ke){me||(me=!0,J.reject(pe,ke))}function _e(ke){me||(me=!0,J.resolve(pe,ke))}function Se(){ve(_e,be)}var xe=ce(Se);xe.status==="error"&&be(xe.value)}function ce(pe,ve){var me={};try{me.value=pe(ve),me.status="success"}catch(be){me.status="error",me.value=be}return me}ee.resolve=fe;function fe(pe){return pe instanceof this?pe:J.resolve(new this(Y),pe)}ee.reject=se;function se(pe){var ve=new this(Y);return J.reject(ve,pe)}ee.all=de;function de(pe){var ve=this;if(Object.prototype.toString.call(pe)!=="[object Array]")return this.reject(new TypeError("must be an array"));var me=pe.length,be=!1;if(!me)return this.resolve([]);for(var _e=new Array(me),Se=0,xe=-1,ke=new this(Y);++xe<me;)De(pe[xe],xe);return ke;function De(Be,Ve){ve.resolve(Be).then(nt,function(ot){be||(be=!0,J.reject(ke,ot))});function nt(ot){_e[Ve]=ot,++Se===me&&!be&&(be=!0,J.resolve(ke,_e))}}}ee.race=ue;function ue(pe){var ve=this;if(Object.prototype.toString.call(pe)!=="[object Array]")return this.reject(new TypeError("must be an array"));var me=pe.length,be=!1;if(!me)return this.resolve([]);for(var _e=-1,Se=new this(Y);++_e<me;)xe(pe[_e]);return Se;function xe(ke){ve.resolve(ke).then(function(De){be||(be=!0,J.resolve(Se,De))},function(De){be||(be=!0,J.reject(Se,De))})}}},{1:1}],3:[function(U,q,G){(function(K){typeof K.Promise!="function"&&(K.Promise=U(2))}).call(this,typeof commonjsGlobal<"u"?commonjsGlobal:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(U,q,G){var K=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Te){return typeof Te}:function(Te){return Te&&typeof Symbol=="function"&&Te.constructor===Symbol&&Te!==Symbol.prototype?"symbol":typeof Te};function Y(Te,qe){if(!(Te instanceof qe))throw new TypeError("Cannot call a class as a function")}function J(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}var X=J();function Z(){try{if(!X||!X.open)return!1;var Te=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),qe=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!Te||qe)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}function Q(Te,qe){Te=Te||[],qe=qe||{};try{return new Blob(Te,qe)}catch(Ge){if(Ge.name!=="TypeError")throw Ge;for(var Oe=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,Ye=new Oe,Ze=0;Ze<Te.length;Ze+=1)Ye.append(Te[Ze]);return Ye.getBlob(qe.type)}}typeof Promise>"u"&&U(3);var ee=Promise;function te(Te,qe){qe&&Te.then(function(Oe){qe(null,Oe)},function(Oe){qe(Oe)})}function ne(Te,qe,Oe){typeof qe=="function"&&Te.then(qe),typeof Oe=="function"&&Te.catch(Oe)}function ie(Te){return typeof Te!="string"&&(console.warn(Te+" used as a key, but it is not a string."),Te=String(Te)),Te}function oe(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var ce="local-forage-detect-blob-support",fe=void 0,se={},de=Object.prototype.toString,ue="readonly",pe="readwrite";function ve(Te){for(var qe=Te.length,Oe=new ArrayBuffer(qe),Ye=new Uint8Array(Oe),Ze=0;Ze<qe;Ze++)Ye[Ze]=Te.charCodeAt(Ze);return Oe}function me(Te){return new ee(function(qe){var Oe=Te.transaction(ce,pe),Ye=Q([""]);Oe.objectStore(ce).put(Ye,"key"),Oe.onabort=function(Ze){Ze.preventDefault(),Ze.stopPropagation(),qe(!1)},Oe.oncomplete=function(){var Ze=navigator.userAgent.match(/Chrome\/(\d+)/),Ge=navigator.userAgent.match(/Edge\//);qe(Ge||!Ze||parseInt(Ze[1],10)>=43)}}).catch(function(){return!1})}function be(Te){return typeof fe=="boolean"?ee.resolve(fe):me(Te).then(function(qe){return fe=qe,fe})}function _e(Te){var qe=se[Te.name],Oe={};Oe.promise=new ee(function(Ye,Ze){Oe.resolve=Ye,Oe.reject=Ze}),qe.deferredOperations.push(Oe),qe.dbReady?qe.dbReady=qe.dbReady.then(function(){return Oe.promise}):qe.dbReady=Oe.promise}function Se(Te){var qe=se[Te.name],Oe=qe.deferredOperations.pop();if(Oe)return Oe.resolve(),Oe.promise}function xe(Te,qe){var Oe=se[Te.name],Ye=Oe.deferredOperations.pop();if(Ye)return Ye.reject(qe),Ye.promise}function ke(Te,qe){return new ee(function(Oe,Ye){if(se[Te.name]=se[Te.name]||Ue(),Te.db)if(qe)_e(Te),Te.db.close();else return Oe(Te.db);var Ze=[Te.name];qe&&Ze.push(Te.version);var Ge=X.open.apply(X,Ze);qe&&(Ge.onupgradeneeded=function(ct){var ht=Ge.result;try{ht.createObjectStore(Te.storeName),ct.oldVersion<=1&&ht.createObjectStore(ce)}catch(mt){if(mt.name==="ConstraintError")console.warn('The database "'+Te.name+'" has been upgraded from version '+ct.oldVersion+" to version "+ct.newVersion+', but the storage "'+Te.storeName+'" already exists.');else throw mt}}),Ge.onerror=function(ct){ct.preventDefault(),Ye(Ge.error)},Ge.onsuccess=function(){var ct=Ge.result;ct.onversionchange=function(ht){ht.target.close()},Oe(ct),Se(Te)}})}function De(Te){return ke(Te,!1)}function Be(Te){return ke(Te,!0)}function Ve(Te,qe){if(!Te.db)return!0;var Oe=!Te.db.objectStoreNames.contains(Te.storeName),Ye=Te.version<Te.db.version,Ze=Te.version>Te.db.version;if(Ye&&(Te.version!==qe&&console.warn('The database "'+Te.name+`" can't be downgraded from version `+Te.db.version+" to version "+Te.version+"."),Te.version=Te.db.version),Ze||Oe){if(Oe){var Ge=Te.db.version+1;Ge>Te.version&&(Te.version=Ge)}return!0}return!1}function nt(Te){return new ee(function(qe,Oe){var Ye=new FileReader;Ye.onerror=Oe,Ye.onloadend=function(Ze){var Ge=btoa(Ze.target.result||"");qe({__local_forage_encoded_blob:!0,data:Ge,type:Te.type})},Ye.readAsBinaryString(Te)})}function ot(Te){var qe=ve(atob(Te.data));return Q([qe],{type:Te.type})}function ft(Te){return Te&&Te.__local_forage_encoded_blob}function it(Te){var qe=this,Oe=qe._initReady().then(function(){var Ye=se[qe._dbInfo.name];if(Ye&&Ye.dbReady)return Ye.dbReady});return ne(Oe,Te,Te),Oe}function ut(Te){_e(Te);for(var qe=se[Te.name],Oe=qe.forages,Ye=0;Ye<Oe.length;Ye++){var Ze=Oe[Ye];Ze._dbInfo.db&&(Ze._dbInfo.db.close(),Ze._dbInfo.db=null)}return Te.db=null,De(Te).then(function(Ge){return Te.db=Ge,Ve(Te)?Be(Te):Ge}).then(function(Ge){Te.db=qe.db=Ge;for(var ct=0;ct<Oe.length;ct++)Oe[ct]._dbInfo.db=Ge}).catch(function(Ge){throw xe(Te,Ge),Ge})}function et(Te,qe,Oe,Ye){Ye===void 0&&(Ye=1);try{var Ze=Te.db.transaction(Te.storeName,qe);Oe(null,Ze)}catch(Ge){if(Ye>0&&(!Te.db||Ge.name==="InvalidStateError"||Ge.name==="NotFoundError"))return ee.resolve().then(function(){if(!Te.db||Ge.name==="NotFoundError"&&!Te.db.objectStoreNames.contains(Te.storeName)&&Te.version<=Te.db.version)return Te.db&&(Te.version=Te.db.version+1),Be(Te)}).then(function(){return ut(Te).then(function(){et(Te,qe,Oe,Ye-1)})}).catch(Oe);Oe(Ge)}}function Ue(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function We(Te){var qe=this,Oe={db:null};if(Te)for(var Ye in Te)Oe[Ye]=Te[Ye];var Ze=se[Oe.name];Ze||(Ze=Ue(),se[Oe.name]=Ze),Ze.forages.push(qe),qe._initReady||(qe._initReady=qe.ready,qe.ready=it);var Ge=[];function ct(){return ee.resolve()}for(var ht=0;ht<Ze.forages.length;ht++){var mt=Ze.forages[ht];mt!==qe&&Ge.push(mt._initReady().catch(ct))}var gt=Ze.forages.slice(0);return ee.all(Ge).then(function(){return Oe.db=Ze.db,De(Oe)}).then(function(wt){return Oe.db=wt,Ve(Oe,qe._defaultConfig.version)?Be(Oe):wt}).then(function(wt){Oe.db=Ze.db=wt,qe._dbInfo=Oe;for(var Ft=0;Ft<gt.length;Ft++){var Ht=gt[Ft];Ht!==qe&&(Ht._dbInfo.db=Oe.db,Ht._dbInfo.version=Oe.version)}})}function tt(Te,qe){var Oe=this;Te=ie(Te);var Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){et(Oe._dbInfo,ue,function(ct,ht){if(ct)return Ge(ct);try{var mt=ht.objectStore(Oe._dbInfo.storeName),gt=mt.get(Te);gt.onsuccess=function(){var wt=gt.result;wt===void 0&&(wt=null),ft(wt)&&(wt=ot(wt)),Ze(wt)},gt.onerror=function(){Ge(gt.error)}}catch(wt){Ge(wt)}})}).catch(Ge)});return te(Ye,qe),Ye}function vt(Te,qe){var Oe=this,Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){et(Oe._dbInfo,ue,function(ct,ht){if(ct)return Ge(ct);try{var mt=ht.objectStore(Oe._dbInfo.storeName),gt=mt.openCursor(),wt=1;gt.onsuccess=function(){var Ft=gt.result;if(Ft){var Ht=Ft.value;ft(Ht)&&(Ht=ot(Ht));var Yt=Te(Ht,Ft.key,wt++);Yt!==void 0?Ze(Yt):Ft.continue()}else Ze()},gt.onerror=function(){Ge(gt.error)}}catch(Ft){Ge(Ft)}})}).catch(Ge)});return te(Ye,qe),Ye}function je(Te,qe,Oe){var Ye=this;Te=ie(Te);var Ze=new ee(function(Ge,ct){var ht;Ye.ready().then(function(){return ht=Ye._dbInfo,de.call(qe)==="[object Blob]"?be(ht.db).then(function(mt){return mt?qe:nt(qe)}):qe}).then(function(mt){et(Ye._dbInfo,pe,function(gt,wt){if(gt)return ct(gt);try{var Ft=wt.objectStore(Ye._dbInfo.storeName);mt===null&&(mt=void 0);var Ht=Ft.put(mt,Te);wt.oncomplete=function(){mt===void 0&&(mt=null),Ge(mt)},wt.onabort=wt.onerror=function(){var Yt=Ht.error?Ht.error:Ht.transaction.error;ct(Yt)}}catch(Yt){ct(Yt)}})}).catch(ct)});return te(Ze,Oe),Ze}function ze(Te,qe){var Oe=this;Te=ie(Te);var Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){et(Oe._dbInfo,pe,function(ct,ht){if(ct)return Ge(ct);try{var mt=ht.objectStore(Oe._dbInfo.storeName),gt=mt.delete(Te);ht.oncomplete=function(){Ze()},ht.onerror=function(){Ge(gt.error)},ht.onabort=function(){var wt=gt.error?gt.error:gt.transaction.error;Ge(wt)}}catch(wt){Ge(wt)}})}).catch(Ge)});return te(Ye,qe),Ye}function Ae(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){et(qe._dbInfo,pe,function(Ge,ct){if(Ge)return Ze(Ge);try{var ht=ct.objectStore(qe._dbInfo.storeName),mt=ht.clear();ct.oncomplete=function(){Ye()},ct.onabort=ct.onerror=function(){var gt=mt.error?mt.error:mt.transaction.error;Ze(gt)}}catch(gt){Ze(gt)}})}).catch(Ze)});return te(Oe,Te),Oe}function Re(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){et(qe._dbInfo,ue,function(Ge,ct){if(Ge)return Ze(Ge);try{var ht=ct.objectStore(qe._dbInfo.storeName),mt=ht.count();mt.onsuccess=function(){Ye(mt.result)},mt.onerror=function(){Ze(mt.error)}}catch(gt){Ze(gt)}})}).catch(Ze)});return te(Oe,Te),Oe}function Ce(Te,qe){var Oe=this,Ye=new ee(function(Ze,Ge){if(Te<0){Ze(null);return}Oe.ready().then(function(){et(Oe._dbInfo,ue,function(ct,ht){if(ct)return Ge(ct);try{var mt=ht.objectStore(Oe._dbInfo.storeName),gt=!1,wt=mt.openKeyCursor();wt.onsuccess=function(){var Ft=wt.result;if(!Ft){Ze(null);return}Te===0||gt?Ze(Ft.key):(gt=!0,Ft.advance(Te))},wt.onerror=function(){Ge(wt.error)}}catch(Ft){Ge(Ft)}})}).catch(Ge)});return te(Ye,qe),Ye}function ge(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){et(qe._dbInfo,ue,function(Ge,ct){if(Ge)return Ze(Ge);try{var ht=ct.objectStore(qe._dbInfo.storeName),mt=ht.openKeyCursor(),gt=[];mt.onsuccess=function(){var wt=mt.result;if(!wt){Ye(gt);return}gt.push(wt.key),wt.continue()},mt.onerror=function(){Ze(mt.error)}}catch(wt){Ze(wt)}})}).catch(Ze)});return te(Oe,Te),Oe}function ye(Te,qe){qe=oe.apply(this,arguments);var Oe=this.config();Te=typeof Te!="function"&&Te||{},Te.name||(Te.name=Te.name||Oe.name,Te.storeName=Te.storeName||Oe.storeName);var Ye=this,Ze;if(!Te.name)Ze=ee.reject("Invalid arguments");else{var Ge=Te.name===Oe.name&&Ye._dbInfo.db,ct=Ge?ee.resolve(Ye._dbInfo.db):De(Te).then(function(ht){var mt=se[Te.name],gt=mt.forages;mt.db=ht;for(var wt=0;wt<gt.length;wt++)gt[wt]._dbInfo.db=ht;return ht});Te.storeName?Ze=ct.then(function(ht){if(ht.objectStoreNames.contains(Te.storeName)){var mt=ht.version+1;_e(Te);var gt=se[Te.name],wt=gt.forages;ht.close();for(var Ft=0;Ft<wt.length;Ft++){var Ht=wt[Ft];Ht._dbInfo.db=null,Ht._dbInfo.version=mt}var Yt=new ee(function(en,cn){var sn=X.open(Te.name,mt);sn.onerror=function(wn){var Hn=sn.result;Hn.close(),cn(wn)},sn.onupgradeneeded=function(){var wn=sn.result;wn.deleteObjectStore(Te.storeName)},sn.onsuccess=function(){var wn=sn.result;wn.close(),en(wn)}});return Yt.then(function(en){gt.db=en;for(var cn=0;cn<wt.length;cn++){var sn=wt[cn];sn._dbInfo.db=en,Se(sn._dbInfo)}}).catch(function(en){throw(xe(Te,en)||ee.resolve()).catch(function(){}),en})}}):Ze=ct.then(function(ht){_e(Te);var mt=se[Te.name],gt=mt.forages;ht.close();for(var wt=0;wt<gt.length;wt++){var Ft=gt[wt];Ft._dbInfo.db=null}var Ht=new ee(function(Yt,en){var cn=X.deleteDatabase(Te.name);cn.onerror=function(){var sn=cn.result;sn&&sn.close(),en(cn.error)},cn.onblocked=function(){console.warn('dropInstance blocked for database "'+Te.name+'" until all open connections are closed')},cn.onsuccess=function(){var sn=cn.result;sn&&sn.close(),Yt(sn)}});return Ht.then(function(Yt){mt.db=Yt;for(var en=0;en<gt.length;en++){var cn=gt[en];Se(cn._dbInfo)}}).catch(function(Yt){throw(xe(Te,Yt)||ee.resolve()).catch(function(){}),Yt})})}return te(Ze,qe),Ze}var Me={_driver:"asyncStorage",_initStorage:We,_support:Z(),iterate:vt,getItem:tt,setItem:je,removeItem:ze,clear:Ae,length:Re,key:Ce,keys:ge,dropInstance:ye};function Ke(){return typeof openDatabase=="function"}var st="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",dt="~~local_forage_type~",$t=/^~~local_forage_type~([^~]+)~/,Et="__lfsc__:",rt=Et.length,jt="arbf",Gt="blob",At="si08",zt="ui08",nn="uic8",St="si16",Ut="si32",le="ur16",re="ui32",ae="fl32",he="fl64",we=rt+jt.length,Ee=Object.prototype.toString;function Le(Te){var qe=Te.length*.75,Oe=Te.length,Ye,Ze=0,Ge,ct,ht,mt;Te[Te.length-1]==="="&&(qe--,Te[Te.length-2]==="="&&qe--);var gt=new ArrayBuffer(qe),wt=new Uint8Array(gt);for(Ye=0;Ye<Oe;Ye+=4)Ge=st.indexOf(Te[Ye]),ct=st.indexOf(Te[Ye+1]),ht=st.indexOf(Te[Ye+2]),mt=st.indexOf(Te[Ye+3]),wt[Ze++]=Ge<<2|ct>>4,wt[Ze++]=(ct&15)<<4|ht>>2,wt[Ze++]=(ht&3)<<6|mt&63;return gt}function bt(Te){var qe=new Uint8Array(Te),Oe="",Ye;for(Ye=0;Ye<qe.length;Ye+=3)Oe+=st[qe[Ye]>>2],Oe+=st[(qe[Ye]&3)<<4|qe[Ye+1]>>4],Oe+=st[(qe[Ye+1]&15)<<2|qe[Ye+2]>>6],Oe+=st[qe[Ye+2]&63];return qe.length%3===2?Oe=Oe.substring(0,Oe.length-1)+"=":qe.length%3===1&&(Oe=Oe.substring(0,Oe.length-2)+"=="),Oe}function Lt(Te,qe){var Oe="";if(Te&&(Oe=Ee.call(Te)),Te&&(Oe==="[object ArrayBuffer]"||Te.buffer&&Ee.call(Te.buffer)==="[object ArrayBuffer]")){var Ye,Ze=Et;Te instanceof ArrayBuffer?(Ye=Te,Ze+=jt):(Ye=Te.buffer,Oe==="[object Int8Array]"?Ze+=At:Oe==="[object Uint8Array]"?Ze+=zt:Oe==="[object Uint8ClampedArray]"?Ze+=nn:Oe==="[object Int16Array]"?Ze+=St:Oe==="[object Uint16Array]"?Ze+=le:Oe==="[object Int32Array]"?Ze+=Ut:Oe==="[object Uint32Array]"?Ze+=re:Oe==="[object Float32Array]"?Ze+=ae:Oe==="[object Float64Array]"?Ze+=he:qe(new Error("Failed to get type for BinaryArray"))),qe(Ze+bt(Ye))}else if(Oe==="[object Blob]"){var Ge=new FileReader;Ge.onload=function(){var ct=dt+Te.type+"~"+bt(this.result);qe(Et+Gt+ct)},Ge.readAsArrayBuffer(Te)}else try{qe(JSON.stringify(Te))}catch(ct){console.error("Couldn't convert value into a JSON string: ",Te),qe(null,ct)}}function Ct(Te){if(Te.substring(0,rt)!==Et)return JSON.parse(Te);var qe=Te.substring(we),Oe=Te.substring(rt,we),Ye;if(Oe===Gt&&$t.test(qe)){var Ze=qe.match($t);Ye=Ze[1],qe=qe.substring(Ze[0].length)}var Ge=Le(qe);switch(Oe){case jt:return Ge;case Gt:return Q([Ge],{type:Ye});case At:return new Int8Array(Ge);case zt:return new Uint8Array(Ge);case nn:return new Uint8ClampedArray(Ge);case St:return new Int16Array(Ge);case le:return new Uint16Array(Ge);case Ut:return new Int32Array(Ge);case re:return new Uint32Array(Ge);case ae:return new Float32Array(Ge);case he:return new Float64Array(Ge);default:throw new Error("Unkown type: "+Oe)}}var It={serialize:Lt,deserialize:Ct,stringToBuffer:Le,bufferToString:bt};function Tt(Te,qe,Oe,Ye){Te.executeSql("CREATE TABLE IF NOT EXISTS "+qe.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],Oe,Ye)}function Sn(Te){var qe=this,Oe={db:null};if(Te)for(var Ye in Te)Oe[Ye]=typeof Te[Ye]!="string"?Te[Ye].toString():Te[Ye];var Ze=new ee(function(Ge,ct){try{Oe.db=openDatabase(Oe.name,String(Oe.version),Oe.description,Oe.size)}catch(ht){return ct(ht)}Oe.db.transaction(function(ht){Tt(ht,Oe,function(){qe._dbInfo=Oe,Ge()},function(mt,gt){ct(gt)})},ct)});return Oe.serializer=It,Ze}function gn(Te,qe,Oe,Ye,Ze,Ge){Te.executeSql(Oe,Ye,Ze,function(ct,ht){ht.code===ht.SYNTAX_ERR?ct.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[qe.storeName],function(mt,gt){gt.rows.length?Ge(mt,ht):Tt(mt,qe,function(){mt.executeSql(Oe,Ye,Ze,Ge)},Ge)},Ge):Ge(ct,ht)},Ge)}function pn(Te,qe){var Oe=this;Te=ie(Te);var Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){var ct=Oe._dbInfo;ct.db.transaction(function(ht){gn(ht,ct,"SELECT * FROM "+ct.storeName+" WHERE key = ? LIMIT 1",[Te],function(mt,gt){var wt=gt.rows.length?gt.rows.item(0).value:null;wt&&(wt=ct.serializer.deserialize(wt)),Ze(wt)},function(mt,gt){Ge(gt)})})}).catch(Ge)});return te(Ye,qe),Ye}function vn(Te,qe){var Oe=this,Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){var ct=Oe._dbInfo;ct.db.transaction(function(ht){gn(ht,ct,"SELECT * FROM "+ct.storeName,[],function(mt,gt){for(var wt=gt.rows,Ft=wt.length,Ht=0;Ht<Ft;Ht++){var Yt=wt.item(Ht),en=Yt.value;if(en&&(en=ct.serializer.deserialize(en)),en=Te(en,Yt.key,Ht+1),en!==void 0){Ze(en);return}}Ze()},function(mt,gt){Ge(gt)})})}).catch(Ge)});return te(Ye,qe),Ye}function Tn(Te,qe,Oe,Ye){var Ze=this;Te=ie(Te);var Ge=new ee(function(ct,ht){Ze.ready().then(function(){qe===void 0&&(qe=null);var mt=qe,gt=Ze._dbInfo;gt.serializer.serialize(qe,function(wt,Ft){Ft?ht(Ft):gt.db.transaction(function(Ht){gn(Ht,gt,"INSERT OR REPLACE INTO "+gt.storeName+" (key, value) VALUES (?, ?)",[Te,wt],function(){ct(mt)},function(Yt,en){ht(en)})},function(Ht){if(Ht.code===Ht.QUOTA_ERR){if(Ye>0){ct(Tn.apply(Ze,[Te,mt,Oe,Ye-1]));return}ht(Ht)}})})}).catch(ht)});return te(Ge,Oe),Ge}function dn(Te,qe,Oe){return Tn.apply(this,[Te,qe,Oe,1])}function Pn(Te,qe){var Oe=this;Te=ie(Te);var Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){var ct=Oe._dbInfo;ct.db.transaction(function(ht){gn(ht,ct,"DELETE FROM "+ct.storeName+" WHERE key = ?",[Te],function(){Ze()},function(mt,gt){Ge(gt)})})}).catch(Ge)});return te(Ye,qe),Ye}function $n(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){var Ge=qe._dbInfo;Ge.db.transaction(function(ct){gn(ct,Ge,"DELETE FROM "+Ge.storeName,[],function(){Ye()},function(ht,mt){Ze(mt)})})}).catch(Ze)});return te(Oe,Te),Oe}function Vn(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){var Ge=qe._dbInfo;Ge.db.transaction(function(ct){gn(ct,Ge,"SELECT COUNT(key) as c FROM "+Ge.storeName,[],function(ht,mt){var gt=mt.rows.item(0).c;Ye(gt)},function(ht,mt){Ze(mt)})})}).catch(Ze)});return te(Oe,Te),Oe}function Nn(Te,qe){var Oe=this,Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){var ct=Oe._dbInfo;ct.db.transaction(function(ht){gn(ht,ct,"SELECT key FROM "+ct.storeName+" WHERE id = ? LIMIT 1",[Te+1],function(mt,gt){var wt=gt.rows.length?gt.rows.item(0).key:null;Ze(wt)},function(mt,gt){Ge(gt)})})}).catch(Ge)});return te(Ye,qe),Ye}function Fn(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){var Ge=qe._dbInfo;Ge.db.transaction(function(ct){gn(ct,Ge,"SELECT key FROM "+Ge.storeName,[],function(ht,mt){for(var gt=[],wt=0;wt<mt.rows.length;wt++)gt.push(mt.rows.item(wt).key);Ye(gt)},function(ht,mt){Ze(mt)})})}).catch(Ze)});return te(Oe,Te),Oe}function fn(Te){return new ee(function(qe,Oe){Te.transaction(function(Ye){Ye.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(Ze,Ge){for(var ct=[],ht=0;ht<Ge.rows.length;ht++)ct.push(Ge.rows.item(ht).name);qe({db:Te,storeNames:ct})},function(Ze,Ge){Oe(Ge)})},function(Ye){Oe(Ye)})})}function Gn(Te,qe){qe=oe.apply(this,arguments);var Oe=this.config();Te=typeof Te!="function"&&Te||{},Te.name||(Te.name=Te.name||Oe.name,Te.storeName=Te.storeName||Oe.storeName);var Ye=this,Ze;return Te.name?Ze=new ee(function(Ge){var ct;Te.name===Oe.name?ct=Ye._dbInfo.db:ct=openDatabase(Te.name,"","",0),Te.storeName?Ge({db:ct,storeNames:[Te.storeName]}):Ge(fn(ct))}).then(function(Ge){return new ee(function(ct,ht){Ge.db.transaction(function(mt){function gt(Yt){return new ee(function(en,cn){mt.executeSql("DROP TABLE IF EXISTS "+Yt,[],function(){en()},function(sn,wn){cn(wn)})})}for(var wt=[],Ft=0,Ht=Ge.storeNames.length;Ft<Ht;Ft++)wt.push(gt(Ge.storeNames[Ft]));ee.all(wt).then(function(){ct()}).catch(function(Yt){ht(Yt)})},function(mt){ht(mt)})})}):Ze=ee.reject("Invalid arguments"),te(Ze,qe),Ze}var bn={_driver:"webSQLStorage",_initStorage:Sn,_support:Ke(),iterate:vn,getItem:pn,setItem:dn,removeItem:Pn,clear:$n,length:Vn,key:Nn,keys:Fn,dropInstance:Gn};function Kn(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function He(Te,qe){var Oe=Te.name+"/";return Te.storeName!==qe.storeName&&(Oe+=Te.storeName+"/"),Oe}function pt(){var Te="_localforage_support_test";try{return localStorage.setItem(Te,!0),localStorage.removeItem(Te),!1}catch{return!0}}function kt(){return!pt()||localStorage.length>0}function Pe(Te){var qe=this,Oe={};if(Te)for(var Ye in Te)Oe[Ye]=Te[Ye];return Oe.keyPrefix=He(Te,qe._defaultConfig),kt()?(qe._dbInfo=Oe,Oe.serializer=It,ee.resolve()):ee.reject()}function at(Te){var qe=this,Oe=qe.ready().then(function(){for(var Ye=qe._dbInfo.keyPrefix,Ze=localStorage.length-1;Ze>=0;Ze--){var Ge=localStorage.key(Ze);Ge.indexOf(Ye)===0&&localStorage.removeItem(Ge)}});return te(Oe,Te),Oe}function lt(Te,qe){var Oe=this;Te=ie(Te);var Ye=Oe.ready().then(function(){var Ze=Oe._dbInfo,Ge=localStorage.getItem(Ze.keyPrefix+Te);return Ge&&(Ge=Ze.serializer.deserialize(Ge)),Ge});return te(Ye,qe),Ye}function xt(Te,qe){var Oe=this,Ye=Oe.ready().then(function(){for(var Ze=Oe._dbInfo,Ge=Ze.keyPrefix,ct=Ge.length,ht=localStorage.length,mt=1,gt=0;gt<ht;gt++){var wt=localStorage.key(gt);if(wt.indexOf(Ge)===0){var Ft=localStorage.getItem(wt);if(Ft&&(Ft=Ze.serializer.deserialize(Ft)),Ft=Te(Ft,wt.substring(ct),mt++),Ft!==void 0)return Ft}}});return te(Ye,qe),Ye}function Rt(Te,qe){var Oe=this,Ye=Oe.ready().then(function(){var Ze=Oe._dbInfo,Ge;try{Ge=localStorage.key(Te)}catch{Ge=null}return Ge&&(Ge=Ge.substring(Ze.keyPrefix.length)),Ge});return te(Ye,qe),Ye}function Dt(Te){var qe=this,Oe=qe.ready().then(function(){for(var Ye=qe._dbInfo,Ze=localStorage.length,Ge=[],ct=0;ct<Ze;ct++){var ht=localStorage.key(ct);ht.indexOf(Ye.keyPrefix)===0&&Ge.push(ht.substring(Ye.keyPrefix.length))}return Ge});return te(Oe,Te),Oe}function Mt(Te){var qe=this,Oe=qe.keys().then(function(Ye){return Ye.length});return te(Oe,Te),Oe}function Ot(Te,qe){var Oe=this;Te=ie(Te);var Ye=Oe.ready().then(function(){var Ze=Oe._dbInfo;localStorage.removeItem(Ze.keyPrefix+Te)});return te(Ye,qe),Ye}function Xt(Te,qe,Oe){var Ye=this;Te=ie(Te);var Ze=Ye.ready().then(function(){qe===void 0&&(qe=null);var Ge=qe;return new ee(function(ct,ht){var mt=Ye._dbInfo;mt.serializer.serialize(qe,function(gt,wt){if(wt)ht(wt);else try{localStorage.setItem(mt.keyPrefix+Te,gt),ct(Ge)}catch(Ft){(Ft.name==="QuotaExceededError"||Ft.name==="NS_ERROR_DOM_QUOTA_REACHED")&&ht(Ft),ht(Ft)}})})});return te(Ze,Oe),Ze}function Zt(Te,qe){if(qe=oe.apply(this,arguments),Te=typeof Te!="function"&&Te||{},!Te.name){var Oe=this.config();Te.name=Te.name||Oe.name,Te.storeName=Te.storeName||Oe.storeName}var Ye=this,Ze;return Te.name?Ze=new ee(function(Ge){Te.storeName?Ge(He(Te,Ye._defaultConfig)):Ge(Te.name+"/")}).then(function(Ge){for(var ct=localStorage.length-1;ct>=0;ct--){var ht=localStorage.key(ct);ht.indexOf(Ge)===0&&localStorage.removeItem(ht)}}):Ze=ee.reject("Invalid arguments"),te(Ze,qe),Ze}var Kt={_driver:"localStorageWrapper",_initStorage:Pe,_support:Kn(),iterate:xt,getItem:lt,setItem:Xt,removeItem:Ot,clear:at,length:Mt,key:Rt,keys:Dt,dropInstance:Zt},an=function(qe,Oe){return qe===Oe||typeof qe=="number"&&typeof Oe=="number"&&isNaN(qe)&&isNaN(Oe)},xn=function(qe,Oe){for(var Ye=qe.length,Ze=0;Ze<Ye;){if(an(qe[Ze],Oe))return!0;Ze++}return!1},Yn=Array.isArray||function(Te){return Object.prototype.toString.call(Te)==="[object Array]"},ln={},Bn={},jn={INDEXEDDB:Me,WEBSQL:bn,LOCALSTORAGE:Kt},An=[jn.INDEXEDDB._driver,jn.WEBSQL._driver,jn.LOCALSTORAGE._driver],Un=["dropInstance"],Qn=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(Un),ir={description:"",driver:An.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ar(Te,qe){Te[qe]=function(){var Oe=arguments;return Te.ready().then(function(){return Te[qe].apply(Te,Oe)})}}function zn(){for(var Te=1;Te<arguments.length;Te++){var qe=arguments[Te];if(qe)for(var Oe in qe)qe.hasOwnProperty(Oe)&&(Yn(qe[Oe])?arguments[0][Oe]=qe[Oe].slice():arguments[0][Oe]=qe[Oe])}return arguments[0]}var or=function(){function Te(qe){Y(this,Te);for(var Oe in jn)if(jn.hasOwnProperty(Oe)){var Ye=jn[Oe],Ze=Ye._driver;this[Oe]=Ze,ln[Ze]||this.defineDriver(Ye)}this._defaultConfig=zn({},ir),this._config=zn({},this._defaultConfig,qe),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return Te.prototype.config=function(Oe){if((typeof Oe>"u"?"undefined":K(Oe))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var Ye in Oe){if(Ye==="storeName"&&(Oe[Ye]=Oe[Ye].replace(/\W/g,"_")),Ye==="version"&&typeof Oe[Ye]!="number")return new Error("Database version must be a number.");this._config[Ye]=Oe[Ye]}return"driver"in Oe&&Oe.driver?this.setDriver(this._config.driver):!0}else return typeof Oe=="string"?this._config[Oe]:this._config},Te.prototype.defineDriver=function(Oe,Ye,Ze){var Ge=new ee(function(ct,ht){try{var mt=Oe._driver,gt=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!Oe._driver){ht(gt);return}for(var wt=Qn.concat("_initStorage"),Ft=0,Ht=wt.length;Ft<Ht;Ft++){var Yt=wt[Ft],en=!xn(Un,Yt);if((en||Oe[Yt])&&typeof Oe[Yt]!="function"){ht(gt);return}}var cn=function(){for(var Hn=function(sr){return function(){var qn=new Error("Method "+sr+" is not implemented by the current driver"),Ne=ee.reject(qn);return te(Ne,arguments[arguments.length-1]),Ne}},er=0,Wn=Un.length;er<Wn;er++){var Mn=Un[er];Oe[Mn]||(Oe[Mn]=Hn(Mn))}};cn();var sn=function(Hn){ln[mt]&&console.info("Redefining LocalForage driver: "+mt),ln[mt]=Oe,Bn[mt]=Hn,ct()};"_support"in Oe?Oe._support&&typeof Oe._support=="function"?Oe._support().then(sn,ht):sn(!!Oe._support):sn(!0)}catch(wn){ht(wn)}});return ne(Ge,Ye,Ze),Ge},Te.prototype.driver=function(){return this._driver||null},Te.prototype.getDriver=function(Oe,Ye,Ze){var Ge=ln[Oe]?ee.resolve(ln[Oe]):ee.reject(new Error("Driver not found."));return ne(Ge,Ye,Ze),Ge},Te.prototype.getSerializer=function(Oe){var Ye=ee.resolve(It);return ne(Ye,Oe),Ye},Te.prototype.ready=function(Oe){var Ye=this,Ze=Ye._driverSet.then(function(){return Ye._ready===null&&(Ye._ready=Ye._initDriver()),Ye._ready});return ne(Ze,Oe,Oe),Ze},Te.prototype.setDriver=function(Oe,Ye,Ze){var Ge=this;Yn(Oe)||(Oe=[Oe]);var ct=this._getSupportedDrivers(Oe);function ht(){Ge._config.driver=Ge.driver()}function mt(Ft){return Ge._extend(Ft),ht(),Ge._ready=Ge._initStorage(Ge._config),Ge._ready}function gt(Ft){return function(){var Ht=0;function Yt(){for(;Ht<Ft.length;){var en=Ft[Ht];return Ht++,Ge._dbInfo=null,Ge._ready=null,Ge.getDriver(en).then(mt).catch(Yt)}ht();var cn=new Error("No available storage method found.");return Ge._driverSet=ee.reject(cn),Ge._driverSet}return Yt()}}var wt=this._driverSet!==null?this._driverSet.catch(function(){return ee.resolve()}):ee.resolve();return this._driverSet=wt.then(function(){var Ft=ct[0];return Ge._dbInfo=null,Ge._ready=null,Ge.getDriver(Ft).then(function(Ht){Ge._driver=Ht._driver,ht(),Ge._wrapLibraryMethodsWithReady(),Ge._initDriver=gt(ct)})}).catch(function(){ht();var Ft=new Error("No available storage method found.");return Ge._driverSet=ee.reject(Ft),Ge._driverSet}),ne(this._driverSet,Ye,Ze),this._driverSet},Te.prototype.supports=function(Oe){return!!Bn[Oe]},Te.prototype._extend=function(Oe){zn(this,Oe)},Te.prototype._getSupportedDrivers=function(Oe){for(var Ye=[],Ze=0,Ge=Oe.length;Ze<Ge;Ze++){var ct=Oe[Ze];this.supports(ct)&&Ye.push(ct)}return Ye},Te.prototype._wrapLibraryMethodsWithReady=function(){for(var Oe=0,Ye=Qn.length;Oe<Ye;Oe++)ar(this,Qn[Oe])},Te.prototype.createInstance=function(Oe){return new Te(Oe)},Te}(),nr=new or;q.exports=nr},{3:3}]},{},[4])(4)})})(localforage);function _ts_decorate$6($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var configRootType=protocols.schema.getCodecForType("dxos.config.Config"),validateConfig=$=>{if(!("version"in $))throw new protocols.InvalidConfigError("Version not specified");if(($==null?void 0:$.version)!==1)throw new protocols.InvalidConfigError(`Invalid config version: ${$.version}`);const I=configRootType.protoType.verify($);if(I)throw new protocols.InvalidConfigError(I);return $},ConfigResource=Symbol.for("dxos.resource.Config"),Config=class{constructor($={},...I){this._config=validateConfig(defaultsDeep($,...I,{version:1}))}get values(){return this._config}get($,I){return get$1(this._config,$,I)}find($,I){const U=get$1(this._config,$);if(Array.isArray(U))return U.find(q=>isMatch(q,I))}getUnchecked($,I){return get$1(this._config,$,I)}getOrThrow($){const I=get$1(this._config,$);if(!I)throw new Error(`Config option not present: ${$}`);return I}};Config=_ts_decorate$6([trace.resource({annotation:ConfigResource})],Config);var SignalState;(function($){$[$.CONNECTING=0]="CONNECTING",$[$.RECONNECTING=1]="RECONNECTING",$[$.CONNECTED=2]="CONNECTED",$[$.DISCONNECTED=3]="DISCONNECTED",$[$.ERROR=4]="ERROR",$[$.CLOSED=5]="CLOSED"})(SignalState||(SignalState={}));var ws=null;typeof WebSocket<"u"?ws=WebSocket:typeof MozWebSocket<"u"?ws=MozWebSocket:typeof commonjsGlobal<"u"?ws=commonjsGlobal.WebSocket||commonjsGlobal.MozWebSocket:typeof window<"u"?ws=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(ws=self.WebSocket||self.MozWebSocket);var browser$3=ws;const WebSocket2=getDefaultExportFromCjs(browser$3);var MessageTrace;(function($){(function(I){I[I.INCOMING=0]="INCOMING",I[I.OUTGOING=1]="OUTGOING"})($.Direction||($.Direction={}))})(MessageTrace||(MessageTrace={}));var decodeRpcError=($,I)=>protocols.decodeError($,{appendStack:`
|
|
912
|
+
*/(function($,I){(function(U){$.exports=U()})(function(){return function U(q,G,K){function Y(Z,Q){if(!G[Z]){if(!q[Z]){var ee=typeof commonjsRequire=="function"&&commonjsRequire;if(!Q&&ee)return ee(Z,!0);if(J)return J(Z,!0);var te=new Error("Cannot find module '"+Z+"'");throw te.code="MODULE_NOT_FOUND",te}var ne=G[Z]={exports:{}};q[Z][0].call(ne.exports,function(ie){var oe=q[Z][1][ie];return Y(oe||ie)},ne,ne.exports,U,q,G,K)}return G[Z].exports}for(var J=typeof commonjsRequire=="function"&&commonjsRequire,X=0;X<K.length;X++)Y(K[X]);return Y}({1:[function(U,q,G){(function(K){var Y=K.MutationObserver||K.WebKitMutationObserver,J;if(Y){var X=0,Z=new Y(ie),Q=K.document.createTextNode("");Z.observe(Q,{characterData:!0}),J=function(){Q.data=X=++X%2}}else if(!K.setImmediate&&typeof K.MessageChannel<"u"){var ee=new K.MessageChannel;ee.port1.onmessage=ie,J=function(){ee.port2.postMessage(0)}}else"document"in K&&"onreadystatechange"in K.document.createElement("script")?J=function(){var ce=K.document.createElement("script");ce.onreadystatechange=function(){ie(),ce.onreadystatechange=null,ce.parentNode.removeChild(ce),ce=null},K.document.documentElement.appendChild(ce)}:J=function(){setTimeout(ie,0)};var te,ne=[];function ie(){te=!0;for(var ce,fe,se=ne.length;se;){for(fe=ne,ne=[],ce=-1;++ce<se;)fe[ce]();se=ne.length}te=!1}q.exports=oe;function oe(ce){ne.push(ce)===1&&!te&&J()}}).call(this,typeof commonjsGlobal<"u"?commonjsGlobal:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(U,q,G){var K=U(1);function Y(){}var J={},X=["REJECTED"],Z=["FULFILLED"],Q=["PENDING"];q.exports=ee;function ee(pe){if(typeof pe!="function")throw new TypeError("resolver must be a function");this.state=Q,this.queue=[],this.outcome=void 0,pe!==Y&&oe(this,pe)}ee.prototype.catch=function(pe){return this.then(null,pe)},ee.prototype.then=function(pe,ve){if(typeof pe!="function"&&this.state===Z||typeof ve!="function"&&this.state===X)return this;var me=new this.constructor(Y);if(this.state!==Q){var be=this.state===Z?pe:ve;ne(me,be,this.outcome)}else this.queue.push(new te(me,pe,ve));return me};function te(pe,ve,me){this.promise=pe,typeof ve=="function"&&(this.onFulfilled=ve,this.callFulfilled=this.otherCallFulfilled),typeof me=="function"&&(this.onRejected=me,this.callRejected=this.otherCallRejected)}te.prototype.callFulfilled=function(pe){J.resolve(this.promise,pe)},te.prototype.otherCallFulfilled=function(pe){ne(this.promise,this.onFulfilled,pe)},te.prototype.callRejected=function(pe){J.reject(this.promise,pe)},te.prototype.otherCallRejected=function(pe){ne(this.promise,this.onRejected,pe)};function ne(pe,ve,me){K(function(){var be;try{be=ve(me)}catch(_e){return J.reject(pe,_e)}be===pe?J.reject(pe,new TypeError("Cannot resolve promise with itself")):J.resolve(pe,be)})}J.resolve=function(pe,ve){var me=ce(ie,ve);if(me.status==="error")return J.reject(pe,me.value);var be=me.value;if(be)oe(pe,be);else{pe.state=Z,pe.outcome=ve;for(var _e=-1,Se=pe.queue.length;++_e<Se;)pe.queue[_e].callFulfilled(ve)}return pe},J.reject=function(pe,ve){pe.state=X,pe.outcome=ve;for(var me=-1,be=pe.queue.length;++me<be;)pe.queue[me].callRejected(ve);return pe};function ie(pe){var ve=pe&&pe.then;if(pe&&(typeof pe=="object"||typeof pe=="function")&&typeof ve=="function")return function(){ve.apply(pe,arguments)}}function oe(pe,ve){var me=!1;function be(ke){me||(me=!0,J.reject(pe,ke))}function _e(ke){me||(me=!0,J.resolve(pe,ke))}function Se(){ve(_e,be)}var xe=ce(Se);xe.status==="error"&&be(xe.value)}function ce(pe,ve){var me={};try{me.value=pe(ve),me.status="success"}catch(be){me.status="error",me.value=be}return me}ee.resolve=fe;function fe(pe){return pe instanceof this?pe:J.resolve(new this(Y),pe)}ee.reject=se;function se(pe){var ve=new this(Y);return J.reject(ve,pe)}ee.all=de;function de(pe){var ve=this;if(Object.prototype.toString.call(pe)!=="[object Array]")return this.reject(new TypeError("must be an array"));var me=pe.length,be=!1;if(!me)return this.resolve([]);for(var _e=new Array(me),Se=0,xe=-1,ke=new this(Y);++xe<me;)De(pe[xe],xe);return ke;function De(Be,Ve){ve.resolve(Be).then(nt,function(ot){be||(be=!0,J.reject(ke,ot))});function nt(ot){_e[Ve]=ot,++Se===me&&!be&&(be=!0,J.resolve(ke,_e))}}}ee.race=ue;function ue(pe){var ve=this;if(Object.prototype.toString.call(pe)!=="[object Array]")return this.reject(new TypeError("must be an array"));var me=pe.length,be=!1;if(!me)return this.resolve([]);for(var _e=-1,Se=new this(Y);++_e<me;)xe(pe[_e]);return Se;function xe(ke){ve.resolve(ke).then(function(De){be||(be=!0,J.resolve(Se,De))},function(De){be||(be=!0,J.reject(Se,De))})}}},{1:1}],3:[function(U,q,G){(function(K){typeof K.Promise!="function"&&(K.Promise=U(2))}).call(this,typeof commonjsGlobal<"u"?commonjsGlobal:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(U,q,G){var K=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(Te){return typeof Te}:function(Te){return Te&&typeof Symbol=="function"&&Te.constructor===Symbol&&Te!==Symbol.prototype?"symbol":typeof Te};function Y(Te,qe){if(!(Te instanceof qe))throw new TypeError("Cannot call a class as a function")}function J(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}var X=J();function Z(){try{if(!X||!X.open)return!1;var Te=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),qe=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!Te||qe)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}function Q(Te,qe){Te=Te||[],qe=qe||{};try{return new Blob(Te,qe)}catch(Ge){if(Ge.name!=="TypeError")throw Ge;for(var Oe=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,Ye=new Oe,Ze=0;Ze<Te.length;Ze+=1)Ye.append(Te[Ze]);return Ye.getBlob(qe.type)}}typeof Promise>"u"&&U(3);var ee=Promise;function te(Te,qe){qe&&Te.then(function(Oe){qe(null,Oe)},function(Oe){qe(Oe)})}function ne(Te,qe,Oe){typeof qe=="function"&&Te.then(qe),typeof Oe=="function"&&Te.catch(Oe)}function ie(Te){return typeof Te!="string"&&(console.warn(Te+" used as a key, but it is not a string."),Te=String(Te)),Te}function oe(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var ce="local-forage-detect-blob-support",fe=void 0,se={},de=Object.prototype.toString,ue="readonly",pe="readwrite";function ve(Te){for(var qe=Te.length,Oe=new ArrayBuffer(qe),Ye=new Uint8Array(Oe),Ze=0;Ze<qe;Ze++)Ye[Ze]=Te.charCodeAt(Ze);return Oe}function me(Te){return new ee(function(qe){var Oe=Te.transaction(ce,pe),Ye=Q([""]);Oe.objectStore(ce).put(Ye,"key"),Oe.onabort=function(Ze){Ze.preventDefault(),Ze.stopPropagation(),qe(!1)},Oe.oncomplete=function(){var Ze=navigator.userAgent.match(/Chrome\/(\d+)/),Ge=navigator.userAgent.match(/Edge\//);qe(Ge||!Ze||parseInt(Ze[1],10)>=43)}}).catch(function(){return!1})}function be(Te){return typeof fe=="boolean"?ee.resolve(fe):me(Te).then(function(qe){return fe=qe,fe})}function _e(Te){var qe=se[Te.name],Oe={};Oe.promise=new ee(function(Ye,Ze){Oe.resolve=Ye,Oe.reject=Ze}),qe.deferredOperations.push(Oe),qe.dbReady?qe.dbReady=qe.dbReady.then(function(){return Oe.promise}):qe.dbReady=Oe.promise}function Se(Te){var qe=se[Te.name],Oe=qe.deferredOperations.pop();if(Oe)return Oe.resolve(),Oe.promise}function xe(Te,qe){var Oe=se[Te.name],Ye=Oe.deferredOperations.pop();if(Ye)return Ye.reject(qe),Ye.promise}function ke(Te,qe){return new ee(function(Oe,Ye){if(se[Te.name]=se[Te.name]||Ue(),Te.db)if(qe)_e(Te),Te.db.close();else return Oe(Te.db);var Ze=[Te.name];qe&&Ze.push(Te.version);var Ge=X.open.apply(X,Ze);qe&&(Ge.onupgradeneeded=function(ct){var ht=Ge.result;try{ht.createObjectStore(Te.storeName),ct.oldVersion<=1&&ht.createObjectStore(ce)}catch(mt){if(mt.name==="ConstraintError")console.warn('The database "'+Te.name+'" has been upgraded from version '+ct.oldVersion+" to version "+ct.newVersion+', but the storage "'+Te.storeName+'" already exists.');else throw mt}}),Ge.onerror=function(ct){ct.preventDefault(),Ye(Ge.error)},Ge.onsuccess=function(){var ct=Ge.result;ct.onversionchange=function(ht){ht.target.close()},Oe(ct),Se(Te)}})}function De(Te){return ke(Te,!1)}function Be(Te){return ke(Te,!0)}function Ve(Te,qe){if(!Te.db)return!0;var Oe=!Te.db.objectStoreNames.contains(Te.storeName),Ye=Te.version<Te.db.version,Ze=Te.version>Te.db.version;if(Ye&&(Te.version!==qe&&console.warn('The database "'+Te.name+`" can't be downgraded from version `+Te.db.version+" to version "+Te.version+"."),Te.version=Te.db.version),Ze||Oe){if(Oe){var Ge=Te.db.version+1;Ge>Te.version&&(Te.version=Ge)}return!0}return!1}function nt(Te){return new ee(function(qe,Oe){var Ye=new FileReader;Ye.onerror=Oe,Ye.onloadend=function(Ze){var Ge=btoa(Ze.target.result||"");qe({__local_forage_encoded_blob:!0,data:Ge,type:Te.type})},Ye.readAsBinaryString(Te)})}function ot(Te){var qe=ve(atob(Te.data));return Q([qe],{type:Te.type})}function ft(Te){return Te&&Te.__local_forage_encoded_blob}function it(Te){var qe=this,Oe=qe._initReady().then(function(){var Ye=se[qe._dbInfo.name];if(Ye&&Ye.dbReady)return Ye.dbReady});return ne(Oe,Te,Te),Oe}function ut(Te){_e(Te);for(var qe=se[Te.name],Oe=qe.forages,Ye=0;Ye<Oe.length;Ye++){var Ze=Oe[Ye];Ze._dbInfo.db&&(Ze._dbInfo.db.close(),Ze._dbInfo.db=null)}return Te.db=null,De(Te).then(function(Ge){return Te.db=Ge,Ve(Te)?Be(Te):Ge}).then(function(Ge){Te.db=qe.db=Ge;for(var ct=0;ct<Oe.length;ct++)Oe[ct]._dbInfo.db=Ge}).catch(function(Ge){throw xe(Te,Ge),Ge})}function et(Te,qe,Oe,Ye){Ye===void 0&&(Ye=1);try{var Ze=Te.db.transaction(Te.storeName,qe);Oe(null,Ze)}catch(Ge){if(Ye>0&&(!Te.db||Ge.name==="InvalidStateError"||Ge.name==="NotFoundError"))return ee.resolve().then(function(){if(!Te.db||Ge.name==="NotFoundError"&&!Te.db.objectStoreNames.contains(Te.storeName)&&Te.version<=Te.db.version)return Te.db&&(Te.version=Te.db.version+1),Be(Te)}).then(function(){return ut(Te).then(function(){et(Te,qe,Oe,Ye-1)})}).catch(Oe);Oe(Ge)}}function Ue(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function We(Te){var qe=this,Oe={db:null};if(Te)for(var Ye in Te)Oe[Ye]=Te[Ye];var Ze=se[Oe.name];Ze||(Ze=Ue(),se[Oe.name]=Ze),Ze.forages.push(qe),qe._initReady||(qe._initReady=qe.ready,qe.ready=it);var Ge=[];function ct(){return ee.resolve()}for(var ht=0;ht<Ze.forages.length;ht++){var mt=Ze.forages[ht];mt!==qe&&Ge.push(mt._initReady().catch(ct))}var gt=Ze.forages.slice(0);return ee.all(Ge).then(function(){return Oe.db=Ze.db,De(Oe)}).then(function(wt){return Oe.db=wt,Ve(Oe,qe._defaultConfig.version)?Be(Oe):wt}).then(function(wt){Oe.db=Ze.db=wt,qe._dbInfo=Oe;for(var Ft=0;Ft<gt.length;Ft++){var Ht=gt[Ft];Ht!==qe&&(Ht._dbInfo.db=Oe.db,Ht._dbInfo.version=Oe.version)}})}function tt(Te,qe){var Oe=this;Te=ie(Te);var Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){et(Oe._dbInfo,ue,function(ct,ht){if(ct)return Ge(ct);try{var mt=ht.objectStore(Oe._dbInfo.storeName),gt=mt.get(Te);gt.onsuccess=function(){var wt=gt.result;wt===void 0&&(wt=null),ft(wt)&&(wt=ot(wt)),Ze(wt)},gt.onerror=function(){Ge(gt.error)}}catch(wt){Ge(wt)}})}).catch(Ge)});return te(Ye,qe),Ye}function vt(Te,qe){var Oe=this,Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){et(Oe._dbInfo,ue,function(ct,ht){if(ct)return Ge(ct);try{var mt=ht.objectStore(Oe._dbInfo.storeName),gt=mt.openCursor(),wt=1;gt.onsuccess=function(){var Ft=gt.result;if(Ft){var Ht=Ft.value;ft(Ht)&&(Ht=ot(Ht));var Yt=Te(Ht,Ft.key,wt++);Yt!==void 0?Ze(Yt):Ft.continue()}else Ze()},gt.onerror=function(){Ge(gt.error)}}catch(Ft){Ge(Ft)}})}).catch(Ge)});return te(Ye,qe),Ye}function je(Te,qe,Oe){var Ye=this;Te=ie(Te);var Ze=new ee(function(Ge,ct){var ht;Ye.ready().then(function(){return ht=Ye._dbInfo,de.call(qe)==="[object Blob]"?be(ht.db).then(function(mt){return mt?qe:nt(qe)}):qe}).then(function(mt){et(Ye._dbInfo,pe,function(gt,wt){if(gt)return ct(gt);try{var Ft=wt.objectStore(Ye._dbInfo.storeName);mt===null&&(mt=void 0);var Ht=Ft.put(mt,Te);wt.oncomplete=function(){mt===void 0&&(mt=null),Ge(mt)},wt.onabort=wt.onerror=function(){var Yt=Ht.error?Ht.error:Ht.transaction.error;ct(Yt)}}catch(Yt){ct(Yt)}})}).catch(ct)});return te(Ze,Oe),Ze}function ze(Te,qe){var Oe=this;Te=ie(Te);var Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){et(Oe._dbInfo,pe,function(ct,ht){if(ct)return Ge(ct);try{var mt=ht.objectStore(Oe._dbInfo.storeName),gt=mt.delete(Te);ht.oncomplete=function(){Ze()},ht.onerror=function(){Ge(gt.error)},ht.onabort=function(){var wt=gt.error?gt.error:gt.transaction.error;Ge(wt)}}catch(wt){Ge(wt)}})}).catch(Ge)});return te(Ye,qe),Ye}function Ae(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){et(qe._dbInfo,pe,function(Ge,ct){if(Ge)return Ze(Ge);try{var ht=ct.objectStore(qe._dbInfo.storeName),mt=ht.clear();ct.oncomplete=function(){Ye()},ct.onabort=ct.onerror=function(){var gt=mt.error?mt.error:mt.transaction.error;Ze(gt)}}catch(gt){Ze(gt)}})}).catch(Ze)});return te(Oe,Te),Oe}function Re(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){et(qe._dbInfo,ue,function(Ge,ct){if(Ge)return Ze(Ge);try{var ht=ct.objectStore(qe._dbInfo.storeName),mt=ht.count();mt.onsuccess=function(){Ye(mt.result)},mt.onerror=function(){Ze(mt.error)}}catch(gt){Ze(gt)}})}).catch(Ze)});return te(Oe,Te),Oe}function Ce(Te,qe){var Oe=this,Ye=new ee(function(Ze,Ge){if(Te<0){Ze(null);return}Oe.ready().then(function(){et(Oe._dbInfo,ue,function(ct,ht){if(ct)return Ge(ct);try{var mt=ht.objectStore(Oe._dbInfo.storeName),gt=!1,wt=mt.openKeyCursor();wt.onsuccess=function(){var Ft=wt.result;if(!Ft){Ze(null);return}Te===0||gt?Ze(Ft.key):(gt=!0,Ft.advance(Te))},wt.onerror=function(){Ge(wt.error)}}catch(Ft){Ge(Ft)}})}).catch(Ge)});return te(Ye,qe),Ye}function ge(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){et(qe._dbInfo,ue,function(Ge,ct){if(Ge)return Ze(Ge);try{var ht=ct.objectStore(qe._dbInfo.storeName),mt=ht.openKeyCursor(),gt=[];mt.onsuccess=function(){var wt=mt.result;if(!wt){Ye(gt);return}gt.push(wt.key),wt.continue()},mt.onerror=function(){Ze(mt.error)}}catch(wt){Ze(wt)}})}).catch(Ze)});return te(Oe,Te),Oe}function ye(Te,qe){qe=oe.apply(this,arguments);var Oe=this.config();Te=typeof Te!="function"&&Te||{},Te.name||(Te.name=Te.name||Oe.name,Te.storeName=Te.storeName||Oe.storeName);var Ye=this,Ze;if(!Te.name)Ze=ee.reject("Invalid arguments");else{var Ge=Te.name===Oe.name&&Ye._dbInfo.db,ct=Ge?ee.resolve(Ye._dbInfo.db):De(Te).then(function(ht){var mt=se[Te.name],gt=mt.forages;mt.db=ht;for(var wt=0;wt<gt.length;wt++)gt[wt]._dbInfo.db=ht;return ht});Te.storeName?Ze=ct.then(function(ht){if(ht.objectStoreNames.contains(Te.storeName)){var mt=ht.version+1;_e(Te);var gt=se[Te.name],wt=gt.forages;ht.close();for(var Ft=0;Ft<wt.length;Ft++){var Ht=wt[Ft];Ht._dbInfo.db=null,Ht._dbInfo.version=mt}var Yt=new ee(function(en,cn){var sn=X.open(Te.name,mt);sn.onerror=function(wn){var Hn=sn.result;Hn.close(),cn(wn)},sn.onupgradeneeded=function(){var wn=sn.result;wn.deleteObjectStore(Te.storeName)},sn.onsuccess=function(){var wn=sn.result;wn.close(),en(wn)}});return Yt.then(function(en){gt.db=en;for(var cn=0;cn<wt.length;cn++){var sn=wt[cn];sn._dbInfo.db=en,Se(sn._dbInfo)}}).catch(function(en){throw(xe(Te,en)||ee.resolve()).catch(function(){}),en})}}):Ze=ct.then(function(ht){_e(Te);var mt=se[Te.name],gt=mt.forages;ht.close();for(var wt=0;wt<gt.length;wt++){var Ft=gt[wt];Ft._dbInfo.db=null}var Ht=new ee(function(Yt,en){var cn=X.deleteDatabase(Te.name);cn.onerror=function(){var sn=cn.result;sn&&sn.close(),en(cn.error)},cn.onblocked=function(){console.warn('dropInstance blocked for database "'+Te.name+'" until all open connections are closed')},cn.onsuccess=function(){var sn=cn.result;sn&&sn.close(),Yt(sn)}});return Ht.then(function(Yt){mt.db=Yt;for(var en=0;en<gt.length;en++){var cn=gt[en];Se(cn._dbInfo)}}).catch(function(Yt){throw(xe(Te,Yt)||ee.resolve()).catch(function(){}),Yt})})}return te(Ze,qe),Ze}var Me={_driver:"asyncStorage",_initStorage:We,_support:Z(),iterate:vt,getItem:tt,setItem:je,removeItem:ze,clear:Ae,length:Re,key:Ce,keys:ge,dropInstance:ye};function Ke(){return typeof openDatabase=="function"}var st="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",dt="~~local_forage_type~",$t=/^~~local_forage_type~([^~]+)~/,Et="__lfsc__:",rt=Et.length,jt="arbf",Gt="blob",At="si08",zt="ui08",nn="uic8",St="si16",Ut="si32",le="ur16",re="ui32",ae="fl32",he="fl64",we=rt+jt.length,Ee=Object.prototype.toString;function Le(Te){var qe=Te.length*.75,Oe=Te.length,Ye,Ze=0,Ge,ct,ht,mt;Te[Te.length-1]==="="&&(qe--,Te[Te.length-2]==="="&&qe--);var gt=new ArrayBuffer(qe),wt=new Uint8Array(gt);for(Ye=0;Ye<Oe;Ye+=4)Ge=st.indexOf(Te[Ye]),ct=st.indexOf(Te[Ye+1]),ht=st.indexOf(Te[Ye+2]),mt=st.indexOf(Te[Ye+3]),wt[Ze++]=Ge<<2|ct>>4,wt[Ze++]=(ct&15)<<4|ht>>2,wt[Ze++]=(ht&3)<<6|mt&63;return gt}function bt(Te){var qe=new Uint8Array(Te),Oe="",Ye;for(Ye=0;Ye<qe.length;Ye+=3)Oe+=st[qe[Ye]>>2],Oe+=st[(qe[Ye]&3)<<4|qe[Ye+1]>>4],Oe+=st[(qe[Ye+1]&15)<<2|qe[Ye+2]>>6],Oe+=st[qe[Ye+2]&63];return qe.length%3===2?Oe=Oe.substring(0,Oe.length-1)+"=":qe.length%3===1&&(Oe=Oe.substring(0,Oe.length-2)+"=="),Oe}function Lt(Te,qe){var Oe="";if(Te&&(Oe=Ee.call(Te)),Te&&(Oe==="[object ArrayBuffer]"||Te.buffer&&Ee.call(Te.buffer)==="[object ArrayBuffer]")){var Ye,Ze=Et;Te instanceof ArrayBuffer?(Ye=Te,Ze+=jt):(Ye=Te.buffer,Oe==="[object Int8Array]"?Ze+=At:Oe==="[object Uint8Array]"?Ze+=zt:Oe==="[object Uint8ClampedArray]"?Ze+=nn:Oe==="[object Int16Array]"?Ze+=St:Oe==="[object Uint16Array]"?Ze+=le:Oe==="[object Int32Array]"?Ze+=Ut:Oe==="[object Uint32Array]"?Ze+=re:Oe==="[object Float32Array]"?Ze+=ae:Oe==="[object Float64Array]"?Ze+=he:qe(new Error("Failed to get type for BinaryArray"))),qe(Ze+bt(Ye))}else if(Oe==="[object Blob]"){var Ge=new FileReader;Ge.onload=function(){var ct=dt+Te.type+"~"+bt(this.result);qe(Et+Gt+ct)},Ge.readAsArrayBuffer(Te)}else try{qe(JSON.stringify(Te))}catch(ct){console.error("Couldn't convert value into a JSON string: ",Te),qe(null,ct)}}function Ct(Te){if(Te.substring(0,rt)!==Et)return JSON.parse(Te);var qe=Te.substring(we),Oe=Te.substring(rt,we),Ye;if(Oe===Gt&&$t.test(qe)){var Ze=qe.match($t);Ye=Ze[1],qe=qe.substring(Ze[0].length)}var Ge=Le(qe);switch(Oe){case jt:return Ge;case Gt:return Q([Ge],{type:Ye});case At:return new Int8Array(Ge);case zt:return new Uint8Array(Ge);case nn:return new Uint8ClampedArray(Ge);case St:return new Int16Array(Ge);case le:return new Uint16Array(Ge);case Ut:return new Int32Array(Ge);case re:return new Uint32Array(Ge);case ae:return new Float32Array(Ge);case he:return new Float64Array(Ge);default:throw new Error("Unkown type: "+Oe)}}var It={serialize:Lt,deserialize:Ct,stringToBuffer:Le,bufferToString:bt};function Tt(Te,qe,Oe,Ye){Te.executeSql("CREATE TABLE IF NOT EXISTS "+qe.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],Oe,Ye)}function Sn(Te){var qe=this,Oe={db:null};if(Te)for(var Ye in Te)Oe[Ye]=typeof Te[Ye]!="string"?Te[Ye].toString():Te[Ye];var Ze=new ee(function(Ge,ct){try{Oe.db=openDatabase(Oe.name,String(Oe.version),Oe.description,Oe.size)}catch(ht){return ct(ht)}Oe.db.transaction(function(ht){Tt(ht,Oe,function(){qe._dbInfo=Oe,Ge()},function(mt,gt){ct(gt)})},ct)});return Oe.serializer=It,Ze}function gn(Te,qe,Oe,Ye,Ze,Ge){Te.executeSql(Oe,Ye,Ze,function(ct,ht){ht.code===ht.SYNTAX_ERR?ct.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[qe.storeName],function(mt,gt){gt.rows.length?Ge(mt,ht):Tt(mt,qe,function(){mt.executeSql(Oe,Ye,Ze,Ge)},Ge)},Ge):Ge(ct,ht)},Ge)}function pn(Te,qe){var Oe=this;Te=ie(Te);var Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){var ct=Oe._dbInfo;ct.db.transaction(function(ht){gn(ht,ct,"SELECT * FROM "+ct.storeName+" WHERE key = ? LIMIT 1",[Te],function(mt,gt){var wt=gt.rows.length?gt.rows.item(0).value:null;wt&&(wt=ct.serializer.deserialize(wt)),Ze(wt)},function(mt,gt){Ge(gt)})})}).catch(Ge)});return te(Ye,qe),Ye}function vn(Te,qe){var Oe=this,Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){var ct=Oe._dbInfo;ct.db.transaction(function(ht){gn(ht,ct,"SELECT * FROM "+ct.storeName,[],function(mt,gt){for(var wt=gt.rows,Ft=wt.length,Ht=0;Ht<Ft;Ht++){var Yt=wt.item(Ht),en=Yt.value;if(en&&(en=ct.serializer.deserialize(en)),en=Te(en,Yt.key,Ht+1),en!==void 0){Ze(en);return}}Ze()},function(mt,gt){Ge(gt)})})}).catch(Ge)});return te(Ye,qe),Ye}function Tn(Te,qe,Oe,Ye){var Ze=this;Te=ie(Te);var Ge=new ee(function(ct,ht){Ze.ready().then(function(){qe===void 0&&(qe=null);var mt=qe,gt=Ze._dbInfo;gt.serializer.serialize(qe,function(wt,Ft){Ft?ht(Ft):gt.db.transaction(function(Ht){gn(Ht,gt,"INSERT OR REPLACE INTO "+gt.storeName+" (key, value) VALUES (?, ?)",[Te,wt],function(){ct(mt)},function(Yt,en){ht(en)})},function(Ht){if(Ht.code===Ht.QUOTA_ERR){if(Ye>0){ct(Tn.apply(Ze,[Te,mt,Oe,Ye-1]));return}ht(Ht)}})})}).catch(ht)});return te(Ge,Oe),Ge}function dn(Te,qe,Oe){return Tn.apply(this,[Te,qe,Oe,1])}function Pn(Te,qe){var Oe=this;Te=ie(Te);var Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){var ct=Oe._dbInfo;ct.db.transaction(function(ht){gn(ht,ct,"DELETE FROM "+ct.storeName+" WHERE key = ?",[Te],function(){Ze()},function(mt,gt){Ge(gt)})})}).catch(Ge)});return te(Ye,qe),Ye}function $n(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){var Ge=qe._dbInfo;Ge.db.transaction(function(ct){gn(ct,Ge,"DELETE FROM "+Ge.storeName,[],function(){Ye()},function(ht,mt){Ze(mt)})})}).catch(Ze)});return te(Oe,Te),Oe}function Vn(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){var Ge=qe._dbInfo;Ge.db.transaction(function(ct){gn(ct,Ge,"SELECT COUNT(key) as c FROM "+Ge.storeName,[],function(ht,mt){var gt=mt.rows.item(0).c;Ye(gt)},function(ht,mt){Ze(mt)})})}).catch(Ze)});return te(Oe,Te),Oe}function Nn(Te,qe){var Oe=this,Ye=new ee(function(Ze,Ge){Oe.ready().then(function(){var ct=Oe._dbInfo;ct.db.transaction(function(ht){gn(ht,ct,"SELECT key FROM "+ct.storeName+" WHERE id = ? LIMIT 1",[Te+1],function(mt,gt){var wt=gt.rows.length?gt.rows.item(0).key:null;Ze(wt)},function(mt,gt){Ge(gt)})})}).catch(Ge)});return te(Ye,qe),Ye}function Fn(Te){var qe=this,Oe=new ee(function(Ye,Ze){qe.ready().then(function(){var Ge=qe._dbInfo;Ge.db.transaction(function(ct){gn(ct,Ge,"SELECT key FROM "+Ge.storeName,[],function(ht,mt){for(var gt=[],wt=0;wt<mt.rows.length;wt++)gt.push(mt.rows.item(wt).key);Ye(gt)},function(ht,mt){Ze(mt)})})}).catch(Ze)});return te(Oe,Te),Oe}function fn(Te){return new ee(function(qe,Oe){Te.transaction(function(Ye){Ye.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(Ze,Ge){for(var ct=[],ht=0;ht<Ge.rows.length;ht++)ct.push(Ge.rows.item(ht).name);qe({db:Te,storeNames:ct})},function(Ze,Ge){Oe(Ge)})},function(Ye){Oe(Ye)})})}function Gn(Te,qe){qe=oe.apply(this,arguments);var Oe=this.config();Te=typeof Te!="function"&&Te||{},Te.name||(Te.name=Te.name||Oe.name,Te.storeName=Te.storeName||Oe.storeName);var Ye=this,Ze;return Te.name?Ze=new ee(function(Ge){var ct;Te.name===Oe.name?ct=Ye._dbInfo.db:ct=openDatabase(Te.name,"","",0),Te.storeName?Ge({db:ct,storeNames:[Te.storeName]}):Ge(fn(ct))}).then(function(Ge){return new ee(function(ct,ht){Ge.db.transaction(function(mt){function gt(Yt){return new ee(function(en,cn){mt.executeSql("DROP TABLE IF EXISTS "+Yt,[],function(){en()},function(sn,wn){cn(wn)})})}for(var wt=[],Ft=0,Ht=Ge.storeNames.length;Ft<Ht;Ft++)wt.push(gt(Ge.storeNames[Ft]));ee.all(wt).then(function(){ct()}).catch(function(Yt){ht(Yt)})},function(mt){ht(mt)})})}):Ze=ee.reject("Invalid arguments"),te(Ze,qe),Ze}var bn={_driver:"webSQLStorage",_initStorage:Sn,_support:Ke(),iterate:vn,getItem:pn,setItem:dn,removeItem:Pn,clear:$n,length:Vn,key:Nn,keys:Fn,dropInstance:Gn};function Kn(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function He(Te,qe){var Oe=Te.name+"/";return Te.storeName!==qe.storeName&&(Oe+=Te.storeName+"/"),Oe}function pt(){var Te="_localforage_support_test";try{return localStorage.setItem(Te,!0),localStorage.removeItem(Te),!1}catch{return!0}}function kt(){return!pt()||localStorage.length>0}function Pe(Te){var qe=this,Oe={};if(Te)for(var Ye in Te)Oe[Ye]=Te[Ye];return Oe.keyPrefix=He(Te,qe._defaultConfig),kt()?(qe._dbInfo=Oe,Oe.serializer=It,ee.resolve()):ee.reject()}function at(Te){var qe=this,Oe=qe.ready().then(function(){for(var Ye=qe._dbInfo.keyPrefix,Ze=localStorage.length-1;Ze>=0;Ze--){var Ge=localStorage.key(Ze);Ge.indexOf(Ye)===0&&localStorage.removeItem(Ge)}});return te(Oe,Te),Oe}function lt(Te,qe){var Oe=this;Te=ie(Te);var Ye=Oe.ready().then(function(){var Ze=Oe._dbInfo,Ge=localStorage.getItem(Ze.keyPrefix+Te);return Ge&&(Ge=Ze.serializer.deserialize(Ge)),Ge});return te(Ye,qe),Ye}function xt(Te,qe){var Oe=this,Ye=Oe.ready().then(function(){for(var Ze=Oe._dbInfo,Ge=Ze.keyPrefix,ct=Ge.length,ht=localStorage.length,mt=1,gt=0;gt<ht;gt++){var wt=localStorage.key(gt);if(wt.indexOf(Ge)===0){var Ft=localStorage.getItem(wt);if(Ft&&(Ft=Ze.serializer.deserialize(Ft)),Ft=Te(Ft,wt.substring(ct),mt++),Ft!==void 0)return Ft}}});return te(Ye,qe),Ye}function Rt(Te,qe){var Oe=this,Ye=Oe.ready().then(function(){var Ze=Oe._dbInfo,Ge;try{Ge=localStorage.key(Te)}catch{Ge=null}return Ge&&(Ge=Ge.substring(Ze.keyPrefix.length)),Ge});return te(Ye,qe),Ye}function Dt(Te){var qe=this,Oe=qe.ready().then(function(){for(var Ye=qe._dbInfo,Ze=localStorage.length,Ge=[],ct=0;ct<Ze;ct++){var ht=localStorage.key(ct);ht.indexOf(Ye.keyPrefix)===0&&Ge.push(ht.substring(Ye.keyPrefix.length))}return Ge});return te(Oe,Te),Oe}function Mt(Te){var qe=this,Oe=qe.keys().then(function(Ye){return Ye.length});return te(Oe,Te),Oe}function Ot(Te,qe){var Oe=this;Te=ie(Te);var Ye=Oe.ready().then(function(){var Ze=Oe._dbInfo;localStorage.removeItem(Ze.keyPrefix+Te)});return te(Ye,qe),Ye}function Xt(Te,qe,Oe){var Ye=this;Te=ie(Te);var Ze=Ye.ready().then(function(){qe===void 0&&(qe=null);var Ge=qe;return new ee(function(ct,ht){var mt=Ye._dbInfo;mt.serializer.serialize(qe,function(gt,wt){if(wt)ht(wt);else try{localStorage.setItem(mt.keyPrefix+Te,gt),ct(Ge)}catch(Ft){(Ft.name==="QuotaExceededError"||Ft.name==="NS_ERROR_DOM_QUOTA_REACHED")&&ht(Ft),ht(Ft)}})})});return te(Ze,Oe),Ze}function Zt(Te,qe){if(qe=oe.apply(this,arguments),Te=typeof Te!="function"&&Te||{},!Te.name){var Oe=this.config();Te.name=Te.name||Oe.name,Te.storeName=Te.storeName||Oe.storeName}var Ye=this,Ze;return Te.name?Ze=new ee(function(Ge){Te.storeName?Ge(He(Te,Ye._defaultConfig)):Ge(Te.name+"/")}).then(function(Ge){for(var ct=localStorage.length-1;ct>=0;ct--){var ht=localStorage.key(ct);ht.indexOf(Ge)===0&&localStorage.removeItem(ht)}}):Ze=ee.reject("Invalid arguments"),te(Ze,qe),Ze}var Kt={_driver:"localStorageWrapper",_initStorage:Pe,_support:Kn(),iterate:xt,getItem:lt,setItem:Xt,removeItem:Ot,clear:at,length:Mt,key:Rt,keys:Dt,dropInstance:Zt},an=function(qe,Oe){return qe===Oe||typeof qe=="number"&&typeof Oe=="number"&&isNaN(qe)&&isNaN(Oe)},xn=function(qe,Oe){for(var Ye=qe.length,Ze=0;Ze<Ye;){if(an(qe[Ze],Oe))return!0;Ze++}return!1},Yn=Array.isArray||function(Te){return Object.prototype.toString.call(Te)==="[object Array]"},ln={},Bn={},jn={INDEXEDDB:Me,WEBSQL:bn,LOCALSTORAGE:Kt},An=[jn.INDEXEDDB._driver,jn.WEBSQL._driver,jn.LOCALSTORAGE._driver],Un=["dropInstance"],Qn=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(Un),ir={description:"",driver:An.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ar(Te,qe){Te[qe]=function(){var Oe=arguments;return Te.ready().then(function(){return Te[qe].apply(Te,Oe)})}}function zn(){for(var Te=1;Te<arguments.length;Te++){var qe=arguments[Te];if(qe)for(var Oe in qe)qe.hasOwnProperty(Oe)&&(Yn(qe[Oe])?arguments[0][Oe]=qe[Oe].slice():arguments[0][Oe]=qe[Oe])}return arguments[0]}var or=function(){function Te(qe){Y(this,Te);for(var Oe in jn)if(jn.hasOwnProperty(Oe)){var Ye=jn[Oe],Ze=Ye._driver;this[Oe]=Ze,ln[Ze]||this.defineDriver(Ye)}this._defaultConfig=zn({},ir),this._config=zn({},this._defaultConfig,qe),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return Te.prototype.config=function(Oe){if((typeof Oe>"u"?"undefined":K(Oe))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var Ye in Oe){if(Ye==="storeName"&&(Oe[Ye]=Oe[Ye].replace(/\W/g,"_")),Ye==="version"&&typeof Oe[Ye]!="number")return new Error("Database version must be a number.");this._config[Ye]=Oe[Ye]}return"driver"in Oe&&Oe.driver?this.setDriver(this._config.driver):!0}else return typeof Oe=="string"?this._config[Oe]:this._config},Te.prototype.defineDriver=function(Oe,Ye,Ze){var Ge=new ee(function(ct,ht){try{var mt=Oe._driver,gt=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!Oe._driver){ht(gt);return}for(var wt=Qn.concat("_initStorage"),Ft=0,Ht=wt.length;Ft<Ht;Ft++){var Yt=wt[Ft],en=!xn(Un,Yt);if((en||Oe[Yt])&&typeof Oe[Yt]!="function"){ht(gt);return}}var cn=function(){for(var Hn=function(sr){return function(){var qn=new Error("Method "+sr+" is not implemented by the current driver"),Ne=ee.reject(qn);return te(Ne,arguments[arguments.length-1]),Ne}},er=0,Wn=Un.length;er<Wn;er++){var Mn=Un[er];Oe[Mn]||(Oe[Mn]=Hn(Mn))}};cn();var sn=function(Hn){ln[mt]&&console.info("Redefining LocalForage driver: "+mt),ln[mt]=Oe,Bn[mt]=Hn,ct()};"_support"in Oe?Oe._support&&typeof Oe._support=="function"?Oe._support().then(sn,ht):sn(!!Oe._support):sn(!0)}catch(wn){ht(wn)}});return ne(Ge,Ye,Ze),Ge},Te.prototype.driver=function(){return this._driver||null},Te.prototype.getDriver=function(Oe,Ye,Ze){var Ge=ln[Oe]?ee.resolve(ln[Oe]):ee.reject(new Error("Driver not found."));return ne(Ge,Ye,Ze),Ge},Te.prototype.getSerializer=function(Oe){var Ye=ee.resolve(It);return ne(Ye,Oe),Ye},Te.prototype.ready=function(Oe){var Ye=this,Ze=Ye._driverSet.then(function(){return Ye._ready===null&&(Ye._ready=Ye._initDriver()),Ye._ready});return ne(Ze,Oe,Oe),Ze},Te.prototype.setDriver=function(Oe,Ye,Ze){var Ge=this;Yn(Oe)||(Oe=[Oe]);var ct=this._getSupportedDrivers(Oe);function ht(){Ge._config.driver=Ge.driver()}function mt(Ft){return Ge._extend(Ft),ht(),Ge._ready=Ge._initStorage(Ge._config),Ge._ready}function gt(Ft){return function(){var Ht=0;function Yt(){for(;Ht<Ft.length;){var en=Ft[Ht];return Ht++,Ge._dbInfo=null,Ge._ready=null,Ge.getDriver(en).then(mt).catch(Yt)}ht();var cn=new Error("No available storage method found.");return Ge._driverSet=ee.reject(cn),Ge._driverSet}return Yt()}}var wt=this._driverSet!==null?this._driverSet.catch(function(){return ee.resolve()}):ee.resolve();return this._driverSet=wt.then(function(){var Ft=ct[0];return Ge._dbInfo=null,Ge._ready=null,Ge.getDriver(Ft).then(function(Ht){Ge._driver=Ht._driver,ht(),Ge._wrapLibraryMethodsWithReady(),Ge._initDriver=gt(ct)})}).catch(function(){ht();var Ft=new Error("No available storage method found.");return Ge._driverSet=ee.reject(Ft),Ge._driverSet}),ne(this._driverSet,Ye,Ze),this._driverSet},Te.prototype.supports=function(Oe){return!!Bn[Oe]},Te.prototype._extend=function(Oe){zn(this,Oe)},Te.prototype._getSupportedDrivers=function(Oe){for(var Ye=[],Ze=0,Ge=Oe.length;Ze<Ge;Ze++){var ct=Oe[Ze];this.supports(ct)&&Ye.push(ct)}return Ye},Te.prototype._wrapLibraryMethodsWithReady=function(){for(var Oe=0,Ye=Qn.length;Oe<Ye;Oe++)ar(this,Qn[Oe])},Te.prototype.createInstance=function(Oe){return new Te(Oe)},Te}(),nr=new or;q.exports=nr},{3:3}]},{},[4])(4)})})(localforage);function _ts_decorate$6($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var configRootType=protocols.schema.getCodecForType("dxos.config.Config"),validateConfig=$=>{if(!("version"in $))throw new protocols.InvalidConfigError("Version not specified");if(($==null?void 0:$.version)!==1)throw new protocols.InvalidConfigError(`Invalid config version: ${$.version}`);const I=configRootType.protoType.verify($);if(I)throw new protocols.InvalidConfigError(I);return $},ConfigResource=Symbol.for("dxos.resource.Config"),Config=class{constructor($={},...I){this._config=validateConfig(defaultsDeep($,...I,{version:1}))}get values(){return this._config}get($,I){return get$1(this._config,$,I)}find($,I){const U=get$1(this._config,$);if(Array.isArray(U))return U.find(q=>isMatch(q,I))}getUnchecked($,I){return get$1(this._config,$,I)}getOrThrow($){const I=get$1(this._config,$);if(!I)throw new Error(`Config option not present: ${$}`);return I}};Config=_ts_decorate$6([trace.resource({annotation:ConfigResource})],Config);var SignalState;(function($){$[$.CONNECTING=0]="CONNECTING",$[$.RECONNECTING=1]="RECONNECTING",$[$.CONNECTED=2]="CONNECTED",$[$.DISCONNECTED=3]="DISCONNECTED",$[$.ERROR=4]="ERROR",$[$.CLOSED=5]="CLOSED"})(SignalState||(SignalState={}));var ws=null;typeof WebSocket<"u"?ws=WebSocket:typeof MozWebSocket<"u"?ws=MozWebSocket:typeof commonjsGlobal<"u"?ws=commonjsGlobal.WebSocket||commonjsGlobal.MozWebSocket:typeof window<"u"?ws=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(ws=self.WebSocket||self.MozWebSocket);var browser$3=ws;const WebSocket3=getDefaultExportFromCjs(browser$3);var MessageTrace;(function($){(function(I){I[I.INCOMING=0]="INCOMING",I[I.OUTGOING=1]="OUTGOING"})($.Direction||($.Direction={}))})(MessageTrace||(MessageTrace={}));var decodeRpcError=($,I)=>protocols.decodeError($,{appendStack:`
|
|
913
913
|
at RPC ${I}
|
|
914
914
|
`+new StackTrace().getStack(1)});function _ts_decorate$5($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$5="/home/runner/work/dxos/dxos/packages/core/mesh/rpc/src/rpc.ts",DEFAULT_TIMEOUT=3e3,BYE_SEND_TIMEOUT=2e3,CLOSE_TIMEOUT=3e3,PendingRpcRequest=class{constructor($,I,U){this.resolve=$,this.reject=I,this.stream=U}},RpcMessage=protocols.schema.getCodecForType("dxos.rpc.RpcMessage"),RpcState;(function($){$.INITIAL="INITIAL",$.OPENING="OPENING",$.OPENED="OPENED",$.CLOSING="CLOSING",$.CLOSED="CLOSED"})(RpcState||(RpcState={}));var RpcPeer=class{constructor($){this._outgoingRequests=new Map,this._localStreams=new Map,this._remoteOpenTrigger=new Trigger,this._closingTrigger=new Trigger,this._byeTrigger=new Trigger,this._nextId=0,this._state="INITIAL",this._unsubscribeFromPort=void 0,this._clearOpenInterval=void 0,this._params={timeout:void 0,streamHandler:void 0,noHandshake:!1,...$}}async open(){var $;if(this._state==="INITIAL"){if(this._unsubscribeFromPort=this._params.port.subscribe(async I=>{try{await this._receive(I)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file$5,L:146,S:this,C:(q,G)=>q(...G)})}}),this._state="OPENING",this._params.noHandshake){this._state="OPENED",this._remoteOpenTrigger.wake();return}log$2("sending open message",void 0,{F:__dxlog_file$5,L:158,S:this,C:(I,U)=>I(...U)}),await this._sendMessage({open:!0}),this._state==="OPENING"&&(this._clearOpenInterval=exponentialBackoffInterval(()=>{this._sendMessage({open:!0}).catch(I=>log$2.warn(I,void 0,{F:__dxlog_file$5,L:167,S:this,C:(U,q)=>U(...q)}))},50),await Promise.race([this._remoteOpenTrigger.wait(),this._closingTrigger.wait()]),($=this._clearOpenInterval)==null||$.call(this),this._state="OPENED",this._state==="OPENED"&&(log$2("sending second open message",void 0,{F:__dxlog_file$5,L:182,S:this,C:(I,U)=>I(...U)}),await this._sendMessage({openAck:!0})))}}async close({timeout:$=CLOSE_TIMEOUT}={}){if(this._state!=="CLOSED"){if(this._abortRequests(),this._state==="OPENED"&&!this._params.noHandshake){try{this._state="CLOSING",await this._sendMessage({bye:{}},BYE_SEND_TIMEOUT)}catch(I){log$2("error closing peer, sending bye",{err:I},{F:__dxlog_file$5,L:204,S:this,C:(U,q)=>U(...q)})}try{log$2("closing waiting on bye",void 0,{F:__dxlog_file$5,L:207,S:this,C:(I,U)=>I(...U)}),await this._byeTrigger.wait({timeout:$})}catch(I){log$2("error closing peer",{err:I},{F:__dxlog_file$5,L:210,S:this,C:(U,q)=>U(...q)});return}}this._disposeAndClose()}}async abort(){this._state!=="CLOSED"&&(this._abortRequests(),this._disposeAndClose())}_abortRequests(){var $;($=this._clearOpenInterval)==null||$.call(this),this._closingTrigger.wake();for(const I of this._outgoingRequests.values())I.reject(new protocols.RpcClosedError);this._outgoingRequests.clear()}_disposeAndClose(){var $,I;($=this._unsubscribeFromPort)==null||$.call(this),this._unsubscribeFromPort=void 0,(I=this._clearOpenInterval)==null||I.call(this),this._state="CLOSED"}async _receive($){var U,q;const I=RpcMessage.decode($,{preserveAny:!0});if(log$2("received message",{type:Object.keys(I)[0]},{F:__dxlog_file$5,L:254,S:this,C:(G,K)=>G(...K)}),I.request){if(this._state!=="OPENED"&&this._state!=="OPENING"){log$2("received request while closed",void 0,{F:__dxlog_file$5,L:258,S:this,C:(K,Y)=>K(...Y)}),await this._sendMessage({response:{id:I.request.id,error:protocols.encodeError(new protocols.RpcClosedError)}});return}const G=I.request;if(G.stream)log$2("stream request",{method:G.method},{F:__dxlog_file$5,L:270,S:this,C:(K,Y)=>K(...Y)}),this._callStreamHandler(G,K=>{var Y;log$2("sending stream response",{method:G.method,response:(Y=K.payload)==null?void 0:Y.type_url,error:K.error,close:K.close},{F:__dxlog_file$5,L:272,S:this,C:(J,X)=>J(...X)}),this._sendMessage({response:K}).catch(J=>{log$2.warn("failed during close",J,{F:__dxlog_file$5,L:280,S:this,C:(X,Z)=>X(...Z)})})});else{log$2("request",{method:G.method},{F:__dxlog_file$5,L:284,S:this,C:(Y,J)=>Y(...J)});const K=await this._callHandler(G);log$2("sending response",{method:G.method,response:(U=K.payload)==null?void 0:U.type_url,error:K.error},{F:__dxlog_file$5,L:287,S:this,C:(Y,J)=>Y(...J)}),await this._sendMessage({response:K})}}else if(I.response){if(this._state!=="OPENED"){log$2("received response while closed",void 0,{F:__dxlog_file$5,L:296,S:this,C:(Y,J)=>Y(...J)});return}const G=I.response.id;if(invariant(typeof G=="number",void 0,{F:__dxlog_file$5,L:301,S:this,A:["typeof responseId === 'number'",""]}),!this._outgoingRequests.has(G)){log$2("received response with invalid id",{responseId:G},{F:__dxlog_file$5,L:303,S:this,C:(Y,J)=>Y(...J)});return}const K=this._outgoingRequests.get(G);K.stream||this._outgoingRequests.delete(G),log$2("response",{type_url:(q=I.response.payload)==null?void 0:q.type_url},{F:__dxlog_file$5,L:313,S:this,C:(Y,J)=>Y(...J)}),K.resolve(I.response)}else if(I.open){if(log$2("received open message",void 0,{F:__dxlog_file$5,L:316,S:this,C:(G,K)=>G(...K)}),this._params.noHandshake)return;await this._sendMessage({openAck:!0})}else if(I.openAck){if(log$2("received openAck message",void 0,{F:__dxlog_file$5,L:323,S:this,C:(G,K)=>G(...K)}),this._params.noHandshake)return;this._remoteOpenTrigger.wake()}else if(I.streamClose){if(this._state!=="OPENED"){log$2("received stream close while closed",void 0,{F:__dxlog_file$5,L:331,S:this,C:(K,Y)=>K(...Y)});return}log$2("received stream close",{id:I.streamClose.id},{F:__dxlog_file$5,L:335,S:this,C:(K,Y)=>K(...Y)}),invariant(typeof I.streamClose.id=="number",void 0,{F:__dxlog_file$5,L:336,S:this,A:["typeof decoded.streamClose.id === 'number'",""]});const G=this._localStreams.get(I.streamClose.id);if(!G){log$2("no local stream",{id:I.streamClose.id},{F:__dxlog_file$5,L:339,S:this,C:(K,Y)=>K(...Y)});return}this._localStreams.delete(I.streamClose.id),await G.close()}else if(I.bye)this._byeTrigger.wake(),this._state!=="CLOSING"&&this._state!=="CLOSED"&&(log$2("replying to bye",void 0,{F:__dxlog_file$5,L:349,S:this,C:(G,K)=>G(...K)}),this._state="CLOSING",await this._sendMessage({bye:{}}),this._abortRequests(),this._disposeAndClose());else throw log$2.error("received malformed message",{msg:$},{F:__dxlog_file$5,L:357,S:this,C:(G,K)=>G(...K)}),new Error("Malformed message.")}async call($,I,U){var G;log$2("calling",{method:$},{F:__dxlog_file$5,L:367,S:this,C:(K,Y)=>K(...Y)}),throwIfNotOpen(this._state);let q;try{const K=this._nextId++,Y=new Promise((Z,Q)=>{this._outgoingRequests.set(K,new PendingRpcRequest(Z,Q,!1))}),J=this._sendMessage({request:{id:K,method:$,payload:I,stream:!1}}),X=asyncTimeout(Y,(U==null?void 0:U.timeout)??this._params.timeout??DEFAULT_TIMEOUT);await Promise.race([J,X]),q=await X,invariant(q.id===K,void 0,{F:__dxlog_file$5,L:392,S:this,A:["response.id === id",""]})}catch(K){if(K instanceof protocols.RpcClosedError){const Y=new protocols.RpcClosedError;throw Y.stack+=`
|
|
915
915
|
|
|
@@ -919,8 +919,8 @@ ${(G=K.stack)==null?void 0:G.split(`
|
|
|
919
919
|
`)}`,Y}throw K}if(q.payload)return q.payload;throw q.error?decodeRpcError(q.error,$):new Error("Malformed response.")}callStream($,I,U){throwIfNotOpen(this._state);const q=this._nextId++;return new Stream$1(({ready:G,next:K,close:Y})=>{const J=Q=>{if(Q.streamReady)G();else if(Q.close)Y();else if(Q.error)Y(decodeRpcError(Q.error,$));else if(Q.payload)K(Q.payload);else throw new Error("Malformed response.")},X=new StackTrace,Z=Q=>{Q?(Q.stack+=`
|
|
920
920
|
|
|
921
921
|
Error happened in the stream at:
|
|
922
|
-
${X.getStack()}`,Y(Q)):Y()};return this._outgoingRequests.set(q,new PendingRpcRequest(J,Z,!0)),this._sendMessage({request:{id:q,method:$,payload:I,stream:!0}}).catch(Q=>{Y(Q)}),()=>{this._sendMessage({streamClose:{id:q}}).catch(Q=>{log$2.catch(Q,void 0,{F:__dxlog_file$5,L:465,S:this,C:(ee,te)=>ee(...te)})})}})}async _sendMessage($,I){log$2("sending message",{type:Object.keys($)[0]},{F:__dxlog_file$5,L:472,S:this,C:(U,q)=>U(...q)}),await this._params.port.send(RpcMessage.encode($,{preserveAny:!0}),I)}async _callHandler($){try{invariant(typeof $.id=="number",void 0,{F:__dxlog_file$5,L:478,S:this,A:["typeof req.id === 'number'",""]}),invariant($.payload,void 0,{F:__dxlog_file$5,L:479,S:this,A:["req.payload",""]}),invariant($.method,void 0,{F:__dxlog_file$5,L:480,S:this,A:["req.method",""]});const I=await this._params.callHandler($.method,$.payload);return{id:$.id,payload:I}}catch(I){return{id:$.id,error:protocols.encodeError(I)}}}_callStreamHandler($,I){try{invariant(this._params.streamHandler,"Requests with streaming responses are not supported.",{F:__dxlog_file$5,L:497,S:this,A:["this._params.streamHandler","'Requests with streaming responses are not supported.'"]}),invariant(typeof $.id=="number",void 0,{F:__dxlog_file$5,L:498,S:this,A:["typeof req.id === 'number'",""]}),invariant($.payload,void 0,{F:__dxlog_file$5,L:499,S:this,A:["req.payload",""]}),invariant($.method,void 0,{F:__dxlog_file$5,L:500,S:this,A:["req.method",""]});const U=this._params.streamHandler($.method,$.payload);U.onReady(()=>{I({id:$.id,streamReady:!0})}),U.subscribe(q=>{I({id:$.id,payload:q})},q=>{I(q?{id:$.id,error:protocols.encodeError(q)}:{id:$.id,close:!0})}),this._localStreams.set($.id,U)}catch(U){I({id:$.id,error:protocols.encodeError(U)})}}};_ts_decorate$5([synchronized],RpcPeer.prototype,"open",null);var throwIfNotOpen=$=>{switch($){case"OPENED":return;case"INITIAL":throw new protocols.RpcNotOpenError;case"CLOSED":throw new protocols.RpcClosedError}},__dxlog_file2$4="/home/runner/work/dxos/dxos/packages/core/mesh/rpc/src/service.ts",ProtoRpcPeer=class{constructor($,I){this.rpc=$,this._peer=I}async open(){await this._peer.open()}async close(){await this._peer.close()}async abort(){await this._peer.abort()}},createProtoRpcPeer=({requested:$,exposed:I,handlers:U,encodingOptions:q,...G})=>{const K={};if(I){invariant(U,void 0,{F:__dxlog_file2$4,L:93,S:void 0,A:["handlers",""]});for(const X of Object.keys(I)){const Z=I[X].serviceProto.fullName.slice(1),Q=U[X];K[Z]=I[X].createServer(Q,q)}}const Y=new RpcPeer({...G,callHandler:(X,Z)=>{const[Q,ee]=parseMethodName(X);if(!K[Q])throw new Error(`Service not supported: ${Q}`);return K[Q].call(ee,Z)},streamHandler:(X,Z)=>{const[Q,ee]=parseMethodName(X);if(!K[Q])throw new Error(`Service not supported: ${Q}`);return K[Q].callStream(ee,Z)}}),J={};if($)for(const X of Object.keys($)){const Z=$[X].serviceProto.fullName.slice(1);J[X]=$[X].createClient({call:(Q,ee,te)=>Y.call(`${Z}.${Q}`,ee,te),callStream:(Q,ee,te)=>Y.callStream(`${Z}.${Q}`,ee,te)},q)}return new ProtoRpcPeer(J,Y)},parseMethodName=$=>{const I=$.lastIndexOf("."),U=$.slice(0,I),q=$.slice(I+1);if(U.length===0||q.length===0)throw new Error(`Invalid method: ${$}`);return[U,q]},createBundledRpcServer=({services:$,handlers:I,...U})=>{const q={};for(const G of Object.keys($)){const K=$[G].serviceProto.fullName.slice(1);q[K]=$[G].createServer(I[G])}return new RpcPeer({...U,callHandler:(G,K)=>{const[Y,J]=parseMethodName(G);if(!q[Y])throw new Error(`Service not supported: ${Y}`);return q[Y].call(J,K)},streamHandler:(G,K)=>{const[Y,J]=parseMethodName(G);if(!q[Y])throw new Error(`Service not supported: ${Y}`);return q[Y].callStream(J,K)}})};protocols.schema.getCodecForType("dxos.mesh.messaging.ReliablePayload"),protocols.schema.getCodecForType("dxos.mesh.messaging.Acknowledgement");var __dxlog_file2$3="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts",SIGNAL_KEEPALIVE_INTERVAL=1e4,SignalRPCClient=class{constructor({url:$,callbacks:I={}}){this._connectTrigger=new Trigger,this._closed=!1,this._closeComplete=new Trigger;const U=PublicKey.random().toHex();log$2.trace("dxos.mesh.signal-rpc-client.constructor",protocols.trace.begin({id:U}),{F:__dxlog_file2$3,L:55,S:this,C:(q,G)=>q(...G)}),this._url=$,this._callbacks=I,this._socket=new WebSocket2(this._url),this._rpc=createProtoRpcPeer({requested:{Signal:protocols.schema.getService("dxos.mesh.signal.Signal")},noHandshake:!0,port:{send:q=>{if(!this._closed)try{this._socket.send(q)}catch(G){log$2.warn("send error",G,{F:__dxlog_file2$3,L:74,S:this,C:(K,Y)=>K(...Y)})}},subscribe:q=>{this._socket.onmessage=async G=>{typeof Blob<"u"&&G.data instanceof Blob?q(export_Buffer.from(await G.data.arrayBuffer())):q(G.data)}}},encodingOptions:{preserveAny:!0}}),this._socket.onopen=async()=>{var q,G,K,Y;try{await this._rpc.open(),log$2(`RPC open ${this._url}`,void 0,{F:__dxlog_file2$3,L:95,S:this,C:(J,X)=>J(...X)}),(G=(q=this._callbacks).onConnected)==null||G.call(q),this._connectTrigger.wake(),this._keepaliveCtx=new Context,scheduleTaskInterval(this._keepaliveCtx,async()=>{var J;(J=this._socket)==null||J.send("__ping__")},SIGNAL_KEEPALIVE_INTERVAL)}catch(J){(Y=(K=this._callbacks).onError)==null||Y.call(K,J)}},this._socket.onclose=async()=>{var q,G;log$2(`Disconnected ${this._url}`,void 0,{F:__dxlog_file2$3,L:116,S:this,C:(K,Y)=>K(...Y)}),(G=(q=this._callbacks).onDisconnected)==null||G.call(q),this._closeComplete.wake(),await this.close()},this._socket.onerror=async q=>{var G,K,Y;if(!this._closed){(K=(G=this._callbacks).onError)==null||K.call(G,q.error??new Error(q.message)),this._connectTrigger.reset();try{await((Y=this._rpc)==null?void 0:Y.close())}catch(J){log$2.catch(J,void 0,{F:__dxlog_file2$3,L:134,S:this,C:(X,Z)=>X(...Z)})}this._closed=!0,log$2.warn(q.message??"Socket error",{url:this._url},{F:__dxlog_file2$3,L:138,S:this,C:(J,X)=>J(...X)})}},log$2.trace("dxos.mesh.signal-rpc-client.constructor",protocols.trace.end({id:U}),{F:__dxlog_file2$3,L:141,S:this,C:(q,G)=>q(...G)})}async close(){var $,I,U,q;await(($=this._keepaliveCtx)==null?void 0:$.dispose()),this._closed=!0;try{await((I=this._rpc)==null?void 0:I.close()),(((U=this._socket)==null?void 0:U.readyState)===WebSocket2.OPEN||((q=this._socket)==null?void 0:q.readyState)===WebSocket2.CONNECTING)&&this._socket.close(),await this._closeComplete.wait({timeout:1e3})}catch(G){log$2.warn("close error",G,{F:__dxlog_file2$3,L:156,S:this,C:(K,Y)=>K(...Y)})}}async join({topic:$,peerId:I}){var q,G;log$2("join",{topic:$,peerId:I},{F:__dxlog_file2$3,L:161,S:this,C:(K,Y)=>K(...Y)}),await this._connectTrigger.wait(),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$3,L:163,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$3,L:164,S:this,A:["this._rpc","'Rpc is not initialized'"]});const U=this._rpc.rpc.Signal.join({swarm:$.asUint8Array(),peer:I.asUint8Array(),metadata:(G=(q=this._callbacks)==null?void 0:q.getMetadata)==null?void 0:G.call(q)});return await U.waitUntilReady(),U}async receiveMessages($){log$2("receiveMessages",{peerId:$},{F:__dxlog_file2$3,L:175,S:this,C:(U,q)=>U(...q)}),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$3,L:176,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),await this._connectTrigger.wait(),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$3,L:178,S:this,A:["this._rpc","'Rpc is not initialized'"]});const I=this._rpc.rpc.Signal.receiveMessages({peer:$.asUint8Array()});return await I.waitUntilReady(),I}async sendMessage({author:$,recipient:I,payload:U}){var q,G;log$2("sendMessage",{author:$,recipient:I,payload:U},{F:__dxlog_file2$3,L:187,S:this,C:(K,Y)=>K(...Y)}),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$3,L:188,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),await this._connectTrigger.wait(),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$3,L:190,S:this,A:["this._rpc","'Rpc is not initialized'"]}),await this._rpc.rpc.Signal.sendMessage({author:$.asUint8Array(),recipient:I.asUint8Array(),payload:U,metadata:(G=(q=this._callbacks)==null?void 0:q.getMetadata)==null?void 0:G.call(q)})}},__dxlog_file3$3="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-client.ts",DEFAULT_RECONNECT_TIMEOUT=100,MAX_RECONNECT_TIMEOUT=5e3,ERROR_RECONCILE_DELAY=1e3,RECONCILE_INTERVAL=5e3,SignalClient=class{constructor($,I,U,q){if(this._host=$,this._onMessage=I,this._onSwarmEvent=U,this._getMetadata=q,this._state=SignalState.CLOSED,this._reconnectAfter=DEFAULT_RECONNECT_TIMEOUT,this._connectionStarted=new Date,this._lastStateChange=new Date,this._clientReady=new Trigger,this.statusChanged=new Event$1,this.commandTrace=new Event$1,this._swarmStreams=new ComplexMap(({topic:G,peerId:K})=>G.toHex()+K.toHex()),this._joinedTopics=new ComplexSet(({topic:G,peerId:K})=>G.toHex()+K.toHex()),this._messageStreams=new ComplexMap(G=>G.toHex()),this._subscribedMessages=new ComplexSet(({peerId:G})=>G.toHex()),this._reconciled=new Event$1,this._instanceId=PublicKey.random().toHex(),this._performance={sentMessages:0,receivedMessages:0,reconnectCounter:0,joinCounter:0,leaveCounter:0},!this._host.startsWith("wss://")&&!this._host.startsWith("ws://"))throw new Error(`Signal server requires a websocket URL. Provided: ${this._host}`)}open(){log$2.trace("dxos.mesh.signal-client.open",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file3$3,L:136,S:this,C:($,I)=>$(...I)}),![SignalState.CONNECTED,SignalState.CONNECTING].includes(this._state)&&(this._ctx=new Context({onError:$=>{var I;this._state===SignalState.CLOSED||(I=this._ctx)!=null&&I.disposed||(this._state===SignalState.CONNECTED&&log$2.warn("SignalClient error:",$,{F:__dxlog_file3$3,L:148,S:this,C:(U,q)=>U(...q)}),this._scheduleReconcileAfterError())}}),this._reconcileTask=new DeferredTask(this._ctx,async()=>{await this._reconcileSwarmSubscriptions(),await this._reconcileMessageSubscriptions(),this._reconciled.emit()}),scheduleTaskInterval(this._ctx,async()=>{this._state===SignalState.CONNECTED&&this._reconcileTask.schedule()},RECONCILE_INTERVAL),this._reconnectTask=new DeferredTask(this._ctx,async()=>{await this._reconnect()}),this._setState(SignalState.CONNECTING),this._createClient(),log$2.trace("dxos.mesh.signal-client.open",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file3$3,L:177,S:this,C:($,I)=>$(...I)}))}async close(){var $,I;log$2("closing...",void 0,{F:__dxlog_file3$3,L:181,S:this,C:(U,q)=>U(...q)}),![SignalState.CLOSED].includes(this._state)&&(await(($=this._ctx)==null?void 0:$.dispose()),this._clientReady.reset(),await((I=this._client)==null?void 0:I.close()),this._client=void 0,this._setState(SignalState.CLOSED),log$2("closed",void 0,{F:__dxlog_file3$3,L:192,S:this,C:(U,q)=>U(...q)}))}getStatus(){var $;return{host:this._host,state:this._state,error:($=this._lastError)==null?void 0:$.message,reconnectIn:this._reconnectAfter,connectionStarted:this._connectionStarted,lastStateChange:this._lastStateChange}}async join({topic:$,peerId:I}){log$2("joining",{topic:$,peerId:I},{F:__dxlog_file3$3,L:207,S:this,C:(U,q)=>U(...q)}),this._performance.joinCounter++,this._joinedTopics.add({topic:$,peerId:I}),this._reconcileTask.schedule()}async leave({topic:$,peerId:I}){var U;this._performance.leaveCounter++,log$2("leaving",{topic:$,peerId:I},{F:__dxlog_file3$3,L:215,S:this,C:(q,G)=>q(...G)}),(U=this._swarmStreams.get({topic:$,peerId:I}))==null||U.close(),this._swarmStreams.delete({topic:$,peerId:I}),this._joinedTopics.delete({topic:$,peerId:I})}async sendMessage($){this._performance.sentMessages++,await this._clientReady.wait(),invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$3,L:224,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]}),await this._client.sendMessage($)}async subscribeMessages($){log$2("subscribing to messages",{peerId:$},{F:__dxlog_file3$3,L:229,S:this,C:(I,U)=>I(...U)}),this._subscribedMessages.add({peerId:$}),this._reconcileTask.schedule()}async unsubscribeMessages($){var I;log$2("unsubscribing from messages",{peerId:$},{F:__dxlog_file3$3,L:235,S:this,C:(U,q)=>U(...q)}),this._subscribedMessages.delete({peerId:$}),(I=this._messageStreams.get($))==null||I.close(),this._messageStreams.delete($)}_scheduleReconcileAfterError(){scheduleTask(this._ctx,()=>{this._reconcileTask.schedule()},ERROR_RECONCILE_DELAY)}_setState($){this._state=$,this._lastStateChange=new Date,log$2("signal state changed",{status:this.getStatus()},{F:__dxlog_file3$3,L:254,S:this,C:(I,U)=>I(...U)}),this.statusChanged.emit(this.getStatus())}_createClient(){log$2("creating client",{host:this._host,state:this._state},{F:__dxlog_file3$3,L:259,S:this,C:($,I)=>$(...I)}),invariant(!this._client,"Client already created",{F:__dxlog_file3$3,L:260,S:this,A:["!this._client","'Client already created'"]}),this._connectionStarted=new Date,this._connectionCtx=this._ctx.derive(),this._connectionCtx.onDispose(async()=>{log$2("connection context disposed",void 0,{F:__dxlog_file3$3,L:267,S:this,C:($,I)=>$(...I)}),await Promise.all(Array.from(this._swarmStreams.values()).map($=>$.close())),await Promise.all(Array.from(this._messageStreams.values()).map($=>$.close())),this._swarmStreams.clear(),this._messageStreams.clear()});try{this._client=new SignalRPCClient({url:this._host,callbacks:{onConnected:()=>{log$2("socket connected",void 0,{F:__dxlog_file3$3,L:279,S:this,C:($,I)=>$(...I)}),this._lastError=void 0,this._reconnectAfter=DEFAULT_RECONNECT_TIMEOUT,this._setState(SignalState.CONNECTED),this._clientReady.wake(),this._reconcileTask.schedule()},onDisconnected:()=>{if(log$2("socket disconnected",{state:this._state},{F:__dxlog_file3$3,L:288,S:this,C:($,I)=>$(...I)}),this._state===SignalState.ERROR){this._setState(SignalState.DISCONNECTED);return}this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._setState(SignalState.DISCONNECTED),this._reconnectTask.schedule()},onError:$=>{log$2("socket error",{error:$,state:this._state},{F:__dxlog_file3$3,L:303,S:this,C:(I,U)=>I(...U)}),this._lastError=$,this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._setState(SignalState.ERROR),this._reconnectTask.schedule()},getMetadata:this._getMetadata}})}catch($){this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._lastError=$,this._setState(SignalState.DISCONNECTED),this._reconnectTask.schedule()}}_incrementReconnectTimeout(){this._reconnectAfter*=2,this._reconnectAfter=Math.min(this._reconnectAfter,MAX_RECONNECT_TIMEOUT)}async _reconnect(){var $,I;if(log$2(`reconnecting in ${this._reconnectAfter}ms`,{state:this._state},{F:__dxlog_file3$3,L:331,S:this,C:(U,q)=>U(...q)}),this._performance.reconnectCounter++,this._state===SignalState.RECONNECTING){log$2.warn("Signal api already reconnecting.",void 0,{F:__dxlog_file3$3,L:335,S:this,C:(U,q)=>U(...q)});return}this._state!==SignalState.CLOSED&&(this._clientReady.reset(),await(($=this._connectionCtx)==null?void 0:$.dispose()),(I=this._client)==null||I.close().catch(()=>{}),this._client=void 0,await cancelWithContext(this._ctx,sleep(this._reconnectAfter)),this._setState(SignalState.RECONNECTING),this._createClient())}async _reconcileSwarmSubscriptions(){var I;await asyncTimeout(cancelWithContext(this._connectionCtx,this._clientReady.wait()),5e3);const $=this._client;invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$3,L:360,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]});for(const{topic:U,peerId:q}of this._swarmStreams.keys())this._joinedTopics.has({topic:U,peerId:q})||((I=this._swarmStreams.get({topic:U,peerId:q}))==null||I.close(),this._swarmStreams.delete({topic:U,peerId:q}));for(const{topic:U,peerId:q}of this._joinedTopics.values()){if(this._swarmStreams.has({topic:U,peerId:q}))continue;const G=await asyncTimeout(cancelWithContext(this._connectionCtx,$.join({topic:U,peerId:q})),5e3);G.subscribe(async K=>{log$2("swarm event",{swarmEvent:K},{F:__dxlog_file3$3,L:387,S:this,C:(Y,J)=>Y(...J)}),await this._onSwarmEvent({topic:U,swarmEvent:K})}),this._swarmStreams.set({topic:U,peerId:q},G)}}async _reconcileMessageSubscriptions(){var I;await asyncTimeout(cancelWithContext(this._connectionCtx,this._clientReady.wait()),5e3);const $=this._client;invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$3,L:400,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]});for(const U of this._messageStreams.keys())this._subscribedMessages.has({peerId:U})||((I=this._messageStreams.get(U))==null||I.close(),this._messageStreams.delete(U));for(const{peerId:U}of this._subscribedMessages.values()){if(this._messageStreams.has(U))continue;const q=await asyncTimeout(cancelWithContext(this._connectionCtx,$.receiveMessages(U)),5e3);q.subscribe(async G=>{this._performance.receivedMessages++,await this._onMessage({author:PublicKey.from(G.author),recipient:PublicKey.from(G.recipient),payload:G.payload})}),this._messageStreams.set(U,q)}}};function _ts_decorate$4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$2="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/websocket-signal-manager.ts",MAX_SERVER_FAILURES=5,WSS_SIGNAL_SERVER_REBOOT_DELAY=3e3,WebsocketSignalManager=class{constructor($,I){this._hosts=$,this._getMetadata=I,this._servers=new Map,this._opened=!1,this.failureCount=new Map,this.statusChanged=new Event$1,this.commandTrace=new Event$1,this.swarmEvent=new Event$1,this.onMessage=new Event$1,this._instanceId=PublicKey.random().toHex(),log$2("Created WebsocketSignalManager",{hosts:this._hosts},{F:__dxlog_file5$2,L:49,S:this,C:(U,q)=>U(...q)});for(const U of this._hosts){if(this._servers.has(U.server))continue;const q=new SignalClient(U.server,async G=>this.onMessage.emit(G),async G=>this.swarmEvent.emit(G),this._getMetadata);q.statusChanged.on(()=>this.statusChanged.emit(this.getStatus())),this._servers.set(U.server,q),this.failureCount.set(U.server,0),q.commandTrace.on(G=>this.commandTrace.emit(G))}}async open(){this._opened||(log$2("open signal manager",{hosts:this._hosts},{F:__dxlog_file5$2,L:73,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.websocket-signal-manager.open",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file5$2,L:74,S:this,C:($,I)=>$(...I)}),this._initContext(),[...this._servers.values()].forEach($=>$.open()),this._opened=!0,log$2.trace("dxos.mesh.websocket-signal-manager.open",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file5$2,L:81,S:this,C:($,I)=>$(...I)}))}async close(){this._opened&&(this._opened=!1,await this._ctx.dispose(),await Promise.all(Array.from(this._servers.values()).map($=>$.close())))}async restartServer($){log$2("Restarting server",{serverName:$},{F:__dxlog_file5$2,L:97,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"server already closed",{F:__dxlog_file5$2,L:98,S:this,A:["this._opened","'server already closed'"]});const I=this._servers.get($);invariant(I,"server not found",{F:__dxlog_file5$2,L:101,S:this,A:["server","'server not found'"]}),await I.close(),await sleep(WSS_SIGNAL_SERVER_REBOOT_DELAY),await I.open()}getStatus(){return Array.from(this._servers.values()).map($=>$.getStatus())}async join({topic:$,peerId:I}){log$2("Join",{topic:$,peerId:I},{F:__dxlog_file5$2,L:114,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:115,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(U=>U.join({topic:$,peerId:I}))}async leave({topic:$,peerId:I}){log$2("leaving",{topic:$,peerId:I},{F:__dxlog_file5$2,L:121,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:122,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(U=>U.leave({topic:$,peerId:I}))}async sendMessage({author:$,recipient:I,payload:U}){log$2(`Signal ${I.truncate()}`,void 0,{F:__dxlog_file5$2,L:136,S:this,C:(q,G)=>q(...G)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:137,S:this,A:["this._opened","'Closed'"]}),this._forEachServer(async(q,G)=>{q.sendMessage({author:$,recipient:I,payload:U}).catch(K=>{K instanceof protocols.RateLimitExceededError?log$2.info("WSS rate limit exceeded",{err:K},{F:__dxlog_file5$2,L:142,S:this,C:(Y,J)=>Y(...J)}):K instanceof protocols.TimeoutError||K.constructor.name==="TimeoutError"?(log$2.info("WSS sendMessage timeout",{err:K},{F:__dxlog_file5$2,L:144,S:this,C:(Y,J)=>Y(...J)}),this.checkServerFailure(G)):(log$2.info(`error sending to ${G}`,{err:K},{F:__dxlog_file5$2,L:147,S:this,C:(Y,J)=>Y(...J)}),this.checkServerFailure(G))})})}async checkServerFailure($){const I=this.failureCount.get($)??0;if(I>MAX_SERVER_FAILURES){log$2.warn(`Too many failures sending to ${$} (${I} > ${MAX_SERVER_FAILURES}), restarting`,void 0,{F:__dxlog_file5$2,L:158,S:this,C:(U,q)=>U(...q)}),await this.restartServer($),this.failureCount.set($,0);return}this.failureCount.set($,(this.failureCount.get($)??0)+1)}async subscribeMessages($){log$2(`Subscribed for message stream peerId=${$}`,void 0,{F:__dxlog_file5$2,L:167,S:this,C:(I,U)=>I(...U)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:168,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(async I=>I.subscribeMessages($))}async unsubscribeMessages($){log$2(`Subscribed for message stream peerId=${$}`,void 0,{F:__dxlog_file5$2,L:174,S:this,C:(I,U)=>I(...U)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:175,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(async I=>I.unsubscribeMessages($))}_initContext(){this._ctx=new Context({onError:$=>log$2.catch($,void 0,{F:__dxlog_file5$2,L:182,S:this,C:(I,U)=>I(...U)})})}async _forEachServer($){return Promise.all(Array.from(this._servers.entries()).map(([I,U])=>$(U,I)))}};_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"open",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"close",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"join",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"leave",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"checkServerFailure",null);var __dxlog_file6="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/utils.ts",setIdentityTags=({identityService:$,devicesService:I,setTag:U})=>{$.queryIdentity().subscribe(q=>{var G;if(!((G=q==null?void 0:q.identity)!=null&&G.identityKey)){log$2("empty response from identity service",{idqr:q},{F:__dxlog_file6,L:21,S:void 0,C:(K,Y)=>K(...Y)});return}U("identityKey",q.identity.identityKey.truncate())}),I.queryDevices().subscribe(q=>{if(!q||!q.devices||q.devices.length===0){log$2("empty response from device service",{device:q},{F:__dxlog_file6,L:30,S:void 0,C:(K,Y)=>K(...Y)});return}invariant(q,"empty response from device service",{F:__dxlog_file6,L:33,S:void 0,A:["dqr","'empty response from device service'"]});const G=q.devices.find(K=>K.kind===DeviceKind.CURRENT);if(!G){log$2("no current device",{device:q},{F:__dxlog_file6,L:37,S:void 0,C:(K,Y)=>K(...Y)});return}U("deviceKey",G.deviceKey.truncate())})};function dist($,I){if($.length!==I.length)throw new Error("Inputs should have the same length");for(var U=Buffer.allocUnsafe($.length),q=0;q<$.length;q++)U[q]=$[q]^I[q];return U}dist.compare=function $(I,U){if(I.length!==U.length)throw new Error("Inputs should have the same length");for(var q=0;q<I.length;q++)if(I[q]!==U[q])return I[q]<U[q]?-1:1;return 0},dist.gt=function $(I,U){return dist.compare(I,U)===1},dist.lt=function $(I,U){return dist.compare(I,U)===-1},dist.eq=function $(I,U){return dist.compare(I,U)===0};var browser$2={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var $=1e3,I=$*60,U=I*60,q=U*24,G=q*7,K=q*365.25;ms=function(Q,ee){ee=ee||{};var te=typeof Q;if(te==="string"&&Q.length>0)return Y(Q);if(te==="number"&&isFinite(Q))return ee.long?X(Q):J(Q);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(Q))};function Y(Q){if(Q=String(Q),!(Q.length>100)){var ee=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(Q);if(ee){var te=parseFloat(ee[1]),ne=(ee[2]||"ms").toLowerCase();switch(ne){case"years":case"year":case"yrs":case"yr":case"y":return te*K;case"weeks":case"week":case"w":return te*G;case"days":case"day":case"d":return te*q;case"hours":case"hour":case"hrs":case"hr":case"h":return te*U;case"minutes":case"minute":case"mins":case"min":case"m":return te*I;case"seconds":case"second":case"secs":case"sec":case"s":return te*$;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return te;default:return}}}}function J(Q){var ee=Math.abs(Q);return ee>=q?Math.round(Q/q)+"d":ee>=U?Math.round(Q/U)+"h":ee>=I?Math.round(Q/I)+"m":ee>=$?Math.round(Q/$)+"s":Q+"ms"}function X(Q){var ee=Math.abs(Q);return ee>=q?Z(Q,ee,q,"day"):ee>=U?Z(Q,ee,U,"hour"):ee>=I?Z(Q,ee,I,"minute"):ee>=$?Z(Q,ee,$,"second"):Q+" ms"}function Z(Q,ee,te,ne){var ie=ee>=te*1.5;return Math.round(Q/te)+" "+ne+(ie?"s":"")}return ms}function setup($){U.debug=U,U.default=U,U.coerce=X,U.disable=K,U.enable=G,U.enabled=Y,U.humanize=requireMs(),U.destroy=Z,Object.keys($).forEach(Q=>{U[Q]=$[Q]}),U.names=[],U.skips=[],U.formatters={};function I(Q){let ee=0;for(let te=0;te<Q.length;te++)ee=(ee<<5)-ee+Q.charCodeAt(te),ee|=0;return U.colors[Math.abs(ee)%U.colors.length]}U.selectColor=I;function U(Q){let ee,te=null,ne,ie;function oe(...ce){if(!oe.enabled)return;const fe=oe,se=Number(new Date),de=se-(ee||se);fe.diff=de,fe.prev=ee,fe.curr=se,ee=se,ce[0]=U.coerce(ce[0]),typeof ce[0]!="string"&&ce.unshift("%O");let ue=0;ce[0]=ce[0].replace(/%([a-zA-Z%])/g,(ve,me)=>{if(ve==="%%")return"%";ue++;const be=U.formatters[me];if(typeof be=="function"){const _e=ce[ue];ve=be.call(fe,_e),ce.splice(ue,1),ue--}return ve}),U.formatArgs.call(fe,ce),(fe.log||U.log).apply(fe,ce)}return oe.namespace=Q,oe.useColors=U.useColors(),oe.color=U.selectColor(Q),oe.extend=q,oe.destroy=U.destroy,Object.defineProperty(oe,"enabled",{enumerable:!0,configurable:!1,get:()=>te!==null?te:(ne!==U.namespaces&&(ne=U.namespaces,ie=U.enabled(Q)),ie),set:ce=>{te=ce}}),typeof U.init=="function"&&U.init(oe),oe}function q(Q,ee){const te=U(this.namespace+(typeof ee>"u"?":":ee)+Q);return te.log=this.log,te}function G(Q){U.save(Q),U.namespaces=Q,U.names=[],U.skips=[];let ee;const te=(typeof Q=="string"?Q:"").split(/[\s,]+/),ne=te.length;for(ee=0;ee<ne;ee++)te[ee]&&(Q=te[ee].replace(/\*/g,".*?"),Q[0]==="-"?U.skips.push(new RegExp("^"+Q.slice(1)+"$")):U.names.push(new RegExp("^"+Q+"$")))}function K(){const Q=[...U.names.map(J),...U.skips.map(J).map(ee=>"-"+ee)].join(",");return U.enable(""),Q}function Y(Q){if(Q[Q.length-1]==="*")return!0;let ee,te;for(ee=0,te=U.skips.length;ee<te;ee++)if(U.skips[ee].test(Q))return!1;for(ee=0,te=U.names.length;ee<te;ee++)if(U.names[ee].test(Q))return!0;return!1}function J(Q){return Q.toString().substring(2,Q.toString().length-2).replace(/\.\*\?$/,"*")}function X(Q){return Q instanceof Error?Q.stack||Q.message:Q}function Z(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return U.enable(U.load()),U}var common=setup;(function($,I){I.formatArgs=q,I.save=G,I.load=K,I.useColors=U,I.storage=Y(),I.destroy=(()=>{let X=!1;return()=>{X||(X=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),I.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function U(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function q(X){if(X[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+X[0]+(this.useColors?"%c ":" ")+"+"+$.exports.humanize(this.diff),!this.useColors)return;const Z="color: "+this.color;X.splice(1,0,Z,"color: inherit");let Q=0,ee=0;X[0].replace(/%[a-zA-Z%]/g,te=>{te!=="%%"&&(Q++,te==="%c"&&(ee=Q))}),X.splice(ee,0,Z)}I.log=console.debug||console.log||(()=>{});function G(X){try{X?I.storage.setItem("debug",X):I.storage.removeItem("debug")}catch{}}function K(){let X;try{X=I.storage.getItem("debug")}catch{}return!X&&typeof process<"u"&&"env"in process&&(X=process.env.DEBUG),X}function Y(){try{return localStorage}catch{}}$.exports=common(I);const{formatters:J}=$.exports;J.j=function(X){try{return JSON.stringify(X)}catch(Z){return"[UnexpectedJSONParseError]: "+Z.message}}})(browser$2,browser$2.exports);var browserExports$1=browser$2.exports,getBrowserRtc=function $(){if(typeof globalThis>"u")return null;var I={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return I.RTCPeerConnection?I:null},browser$1={exports:{}},MAX_BYTES=65536,MAX_UINT32=4294967295;function oldBrowser(){throw new Error(`Secure random number generation is not supported by this browser.
|
|
923
|
-
Use Chrome, Firefox or Internet Explorer 11`)}var Buffer$2=requireSafeBuffer().Buffer,crypto=commonjsGlobal.crypto||commonjsGlobal.msCrypto;crypto&&crypto.getRandomValues?browser$1.exports=randomBytes:browser$1.exports=oldBrowser;function randomBytes($,I){if($>MAX_UINT32)throw new RangeError("requested too many random bytes");var U=Buffer$2.allocUnsafe($);if($>0)if($>MAX_BYTES)for(var q=0;q<$;q+=MAX_BYTES)crypto.getRandomValues(U.slice(q,q+MAX_BYTES));else crypto.getRandomValues(U);return typeof I=="function"?process.nextTick(function(){I(null,U)}):U}var browserExports=browser$1.exports;/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let promise;var queueMicrotask_1=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:commonjsGlobal):$=>(promise||(promise=Promise.resolve())).then($).catch(I=>setTimeout(()=>{throw I},0));function assign$3($,I){for(const U in I)Object.defineProperty($,U,{value:I[U],enumerable:!0,configurable:!0});return $}function createError($,I,U){if(!$||typeof $=="string")throw new TypeError("Please pass an Error to err-code");U||(U={}),typeof I=="object"&&(U=I,I=""),I&&(U.code=I);try{return assign$3($,U)}catch{U.message=$.message,U.stack=$.stack;const G=function(){};return G.prototype=Object.create(Object.getPrototypeOf($)),assign$3(new G,U)}}var errCode$1=createError;/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const debug=browserExports$1("simple-peer"),getBrowserRTC=getBrowserRtc,randombytes=browserExports,stream$1=readableBrowserExports,queueMicrotask$1=queueMicrotask_1,errCode=errCode$1,{Buffer:Buffer$1}=buffer,MAX_BUFFERED_AMOUNT$1=64*1024,ICECOMPLETE_TIMEOUT=5*1e3,CHANNEL_CLOSING_TIMEOUT=5*1e3;function filterTrickle($){return $.replace(/a=ice-options:trickle\s\n/g,"")}function warn$1($){console.warn($)}let Peer$1=class pr extends stream$1.Duplex{constructor(I){if(I=Object.assign({allowHalfOpen:!1},I),super(I),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",I),this.channelName=I.initiator?I.channelName||randombytes(20).toString("hex"):null,this.initiator=I.initiator||!1,this.channelConfig=I.channelConfig||pr.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},pr.config,I.config),this.offerOptions=I.offerOptions||{},this.answerOptions=I.answerOptions||{},this.sdpTransform=I.sdpTransform||(U=>U),this.streams=I.streams||(I.stream?[I.stream]:[]),this.trickle=I.trickle!==void 0?I.trickle:!0,this.allowHalfTrickle=I.allowHalfTrickle!==void 0?I.allowHalfTrickle:!1,this.iceCompleteTimeout=I.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=I.wrtc&&typeof I.wrtc=="object"?I.wrtc:getBrowserRTC(),!this._wrtc)throw errCode(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(U){this.destroy(errCode(U,"ERR_PC_CONSTRUCTOR"));return}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=U=>{this._onIceCandidate(U)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(U=>{this.destroy(errCode(U,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=U=>{this._setupData(U)},this.streams&&this.streams.forEach(U=>{this.addStream(U)}),this._pc.ontrack=U=>{this._onTrack(U)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof I=="string")try{I=JSON.parse(I)}catch{I={}}this._debug("signal()"),I.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),I.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(I.transceiverRequest.kind,I.transceiverRequest.init)),I.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(I.candidate):this._pendingCandidates.push(I.candidate)),I.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(I)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(U=>{this._addIceCandidate(U)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(U=>{this.destroy(errCode(U,"ERR_SET_REMOTE_DESCRIPTION"))}),!I.sdp&&!I.candidate&&!I.renegotiate&&!I.transceiverRequest&&this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(I){const U=new this._wrtc.RTCIceCandidate(I);this._pc.addIceCandidate(U).catch(q=>{!U.address||U.address.endsWith(".local")?warn$1("Ignoring unsupported ICE candidate."):this.destroy(errCode(q,"ERR_ADD_ICE_CANDIDATE"))})}send(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(I)}}addTransceiver(I,U){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(I,U),this._needsNegotiation()}catch(q){this.destroy(errCode(q,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:I,init:U}})}}addStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),I.getTracks().forEach(U=>{this.addTrack(U,I)})}}addTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const q=this._senderMap.get(I)||new Map;let G=q.get(U);if(!G)G=this._pc.addTrack(I,U),q.set(U,G),this._senderMap.set(I,q),this._needsNegotiation();else throw G.removed?errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(I,U,q){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const G=this._senderMap.get(I),K=G?G.get(q):null;if(!K)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");U&&this._senderMap.set(U,G),K.replaceTrack!=null?K.replaceTrack(U):this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const q=this._senderMap.get(I),G=q?q.get(U):null;if(!G)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{G.removed=!0,this._pc.removeTrack(G)}catch(K){K.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(G):this.destroy(errCode(K,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),I.getTracks().forEach(U=>{this.removeTrack(U,I)})}}_needsNegotiation(){this._debug("_needsNegotiation"),!this._batchedNegotiation&&(this._batchedNegotiation=!0,queueMicrotask$1(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(I){this._destroy(I,()=>{})}_destroy(I,U){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",I&&(I.message||I)),queueMicrotask$1(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",I&&(I.message||I)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,I&&this.emit("error",I),this.emit("close"),U()}))}_setupData(I){if(!I.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=I.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT$1),this.channelName=this._channel.label,this._channel.onmessage=q=>{this._onChannelMessage(q)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=q=>{const G=q.error instanceof Error?q.error:new Error(`Datachannel error: ${q.message} ${q.filename}:${q.lineno}:${q.colno}`);this.destroy(errCode(G,"ERR_DATA_CHANNEL"))};let U=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(U&&this._onChannelClose(),U=!0):U=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(I,U,q){if(this.destroyed)return q(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(I)}catch(G){return this.destroy(errCode(G,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=q):q(null)}else this._debug("write before connect"),this._chunk=I,this._cb=q}_onFinish(){if(this.destroyed)return;const I=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?I():this.once("connect",I)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp})},q=()=>{this._debug("createOffer success"),!this.destroyed&&(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(I=>{!I.mid&&I.sender.track&&!I.requested&&(I.requested=!0,this.addTransceiver(I.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp}),this.initiator||this._requestMissingTransceivers()},q=()=>{this.destroyed||(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const I=this._pc.iceConnectionState,U=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",I,U),this.emit("iceStateChange",I,U),(I==="connected"||I==="completed")&&(this._pcReady=!0,this._maybeReady()),I==="failed"&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),I==="closed"&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(I){const U=q=>(Object.prototype.toString.call(q.values)==="[object Array]"&&q.values.forEach(G=>{Object.assign(q,G)}),q);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(q=>{const G=[];q.forEach(K=>{G.push(U(K))}),I(null,G)},q=>I(q)):this._pc.getStats.length>0?this._pc.getStats(q=>{if(this.destroyed)return;const G=[];q.result().forEach(K=>{const Y={};K.names().forEach(J=>{Y[J]=K.stat(J)}),Y.id=K.id,Y.type=K.type,Y.timestamp=K.timestamp,G.push(U(Y))}),I(null,G)},q=>I(q)):I(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const I=()=>{this.destroyed||this.getStats((U,q)=>{if(this.destroyed)return;U&&(q=[]);const G={},K={},Y={};let J=!1;q.forEach(Z=>{(Z.type==="remotecandidate"||Z.type==="remote-candidate")&&(G[Z.id]=Z),(Z.type==="localcandidate"||Z.type==="local-candidate")&&(K[Z.id]=Z),(Z.type==="candidatepair"||Z.type==="candidate-pair")&&(Y[Z.id]=Z)});const X=Z=>{J=!0;let Q=K[Z.localCandidateId];Q&&(Q.ip||Q.address)?(this.localAddress=Q.ip||Q.address,this.localPort=Number(Q.port)):Q&&Q.ipAddress?(this.localAddress=Q.ipAddress,this.localPort=Number(Q.portNumber)):typeof Z.googLocalAddress=="string"&&(Q=Z.googLocalAddress.split(":"),this.localAddress=Q[0],this.localPort=Number(Q[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let ee=G[Z.remoteCandidateId];ee&&(ee.ip||ee.address)?(this.remoteAddress=ee.ip||ee.address,this.remotePort=Number(ee.port)):ee&&ee.ipAddress?(this.remoteAddress=ee.ipAddress,this.remotePort=Number(ee.portNumber)):typeof Z.googRemoteAddress=="string"&&(ee=Z.googRemoteAddress.split(":"),this.remoteAddress=ee[0],this.remotePort=Number(ee[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(q.forEach(Z=>{Z.type==="transport"&&Z.selectedCandidatePairId&&X(Y[Z.selectedCandidatePairId]),(Z.type==="googCandidatePair"&&Z.googActiveConnection==="true"||(Z.type==="candidatepair"||Z.type==="candidate-pair")&&Z.selected)&&X(Z)}),!J&&(!Object.keys(Y).length||Object.keys(K).length)){setTimeout(I,100);return}else this._connecting=!1,this._connected=!0;if(this._chunk){try{this.send(this._chunk)}catch(Q){return this.destroy(errCode(Q,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const Z=this._cb;this._cb=null,Z(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};I()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(I=>{this._pc.removeTrack(I),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(I){this.destroyed||(I.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:I.candidate.candidate,sdpMLineIndex:I.candidate.sdpMLineIndex,sdpMid:I.candidate.sdpMid}}):!I.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),I.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(I){if(this.destroyed)return;let U=I.data;U instanceof ArrayBuffer&&(U=Buffer$1.from(U)),this.push(U)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const I=this._cb;this._cb=null,I(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(I){this.destroyed||I.streams.forEach(U=>{this._debug("on track"),this.emit("track",I.track,U),this._remoteTracks.push({track:I.track,stream:U}),!this._remoteStreams.some(q=>q.id===U.id)&&(this._remoteStreams.push(U),queueMicrotask$1(()=>{this._debug("on stream"),this.emit("stream",U)}))})}_debug(){const I=[].slice.call(arguments);I[0]="["+this._id+"] "+I[0],debug.apply(null,I)}};Peer$1.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer$1.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer$1.channelConfig={};var ConnectionState$1;(function($){$[$.INVALID=0]="INVALID",$[$.CONNECTING=1]="CONNECTING",$[$.CONNECTED=2]="CONNECTED",$[$.CLOSED=3]="CLOSED"})(ConnectionState$1||(ConnectionState$1={}));var emitterComponent=Emitter$1;function Emitter$1($){if($)return mixin($)}function mixin($){for(var I in Emitter$1.prototype)$[I]=Emitter$1.prototype[I];return $}Emitter$1.prototype.on=Emitter$1.prototype.addEventListener=function($,I){return this._callbacks=this._callbacks||{},(this._callbacks[$]=this._callbacks[$]||[]).push(I),this},Emitter$1.prototype.once=function($,I){var U=this;this._callbacks=this._callbacks||{};function q(){U.off($,q),I.apply(this,arguments)}return q.fn=I,this.on($,q),this},Emitter$1.prototype.off=Emitter$1.prototype.removeListener=Emitter$1.prototype.removeAllListeners=Emitter$1.prototype.removeEventListener=function($,I){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var U=this._callbacks[$];if(!U)return this;if(arguments.length==1)return delete this._callbacks[$],this;for(var q,G=0;G<U.length;G++)if(q=U[G],q===I||q.fn===I){U.splice(G,1);break}return this},Emitter$1.prototype.emit=function($){this._callbacks=this._callbacks||{};var I=[].slice.call(arguments,1),U=this._callbacks[$];if(U){U=U.slice(0);for(var q=0,G=U.length;q<G;++q)U[q].apply(this,I)}return this},Emitter$1.prototype.listeners=function($){return this._callbacks=this._callbacks||{},this._callbacks[$]||[]},Emitter$1.prototype.hasListeners=function($){return!!this.listeners($).length};var Emitter=emitterComponent;function Stream(){Emitter.call(this)}Stream.prototype=new Emitter;var stream=Stream;Stream.Stream=Stream,Stream.prototype.pipe=function($,I){var U=this;function q(Q){$.writable&&$.write(Q)===!1&&U.pause&&U.pause()}U.on("data",q);function G(){U.readable&&U.resume&&U.resume()}$.on("drain",G),!$._isStdio&&(!I||I.end!==!1)&&(U.on("end",Y),U.on("close",J));var K=!1;function Y(){K||(K=!0,$.end())}function J(){K||(K=!0,typeof $.destroy=="function"&&$.destroy())}function X(Q){if(Z(),!this.hasListeners("error"))throw Q}U.on("error",X),$.on("error",X);function Z(){U.off("data",q),$.off("drain",G),U.off("end",Y),U.off("close",J),U.off("error",X),$.off("error",X),U.off("end",Z),U.off("close",Z),$.off("end",Z),$.off("close",Z)}return U.on("end",Z),U.on("close",Z),$.on("end",Z),$.on("close",Z),$.emit("pipe",U),$};var encode_1=encode,MSB$1=128,REST$1=127,MSBALL=~REST$1,INT=Math.pow(2,31);function encode($,I,U){if(Number.MAX_SAFE_INTEGER&&$>Number.MAX_SAFE_INTEGER)throw encode.bytes=0,new RangeError("Could not encode varint");I=I||[],U=U||0;for(var q=U;$>=INT;)I[U++]=$&255|MSB$1,$/=128;for(;$&MSBALL;)I[U++]=$&255|MSB$1,$>>>=7;return I[U]=$|0,encode.bytes=U-q+1,I}var decode=read,MSB=128,REST=127;function read($,q){var U=0,q=q||0,G=0,K=q,Y,J=$.length;do{if(K>=J||G>49)throw read.bytes=0,new RangeError("Could not decode varint");Y=$[K++],U+=G<28?(Y&REST)<<G:(Y&REST)*Math.pow(2,G),G+=7}while(Y>=MSB);return read.bytes=K-q,U}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function($){return $<N1?1:$<N2?2:$<N3?3:$<N4?4:$<N5?5:$<N6?6:$<N7?7:$<N8?8:$<N9?9:10},varint={encode:encode_1,decode,encodingLength:length},__dxlog_file$4="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/control-extension.ts",HEARTBEAT_RTT_WARN_THRESH=1e4,ControlExtension=class{constructor($,I,U){this.opts=$,this.localPeerId=I,this.remotePeerId=U,this._ctx=new Context({onError:q=>{this._extensionContext.close(q)}}),this.onExtensionRegistered=new Callback}async registerExtension($){await this._rpc.rpc.Control.registerExtension({name:$})}async onOpen($){this._extensionContext=$,this._rpc=createProtoRpcPeer({requested:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},exposed:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},handlers:{Control:{registerExtension:async I=>{this.onExtensionRegistered.call(I.name)},heartbeat:async I=>(log$2("received heartbeat request",{ts:I.requestTimestamp,localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:66,S:this,C:(U,q)=>U(...q)}),{requestTimestamp:I.requestTimestamp})}},port:await $.createPort("rpc",{contentType:'application/x-protobuf; messageType="dxos.rpc.Message"'}),timeout:this.opts.heartbeatTimeout}),await this._rpc.open(),scheduleTaskInterval(this._ctx,async()=>{const I=new Date;try{const U=await asyncTimeout(this._rpc.rpc.Control.heartbeat({requestTimestamp:I}),this.opts.heartbeatTimeout),q=Date.now();U.requestTimestamp instanceof Date&&(q-U.requestTimestamp.getTime()>(HEARTBEAT_RTT_WARN_THRESH<this.opts.heartbeatTimeout?HEARTBEAT_RTT_WARN_THRESH:this.opts.heartbeatTimeout/2)?log$2.warn(`heartbeat RTT for Teleport > ${HEARTBEAT_RTT_WARN_THRESH/1e3}s`,{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:103,S:this,C:(G,K)=>G(...K)}):log$2("heartbeat RTT",{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:109,S:this,C:(G,K)=>G(...K)}))}catch(U){const q=Date.now();if(U instanceof protocols.RpcClosedError){log$2("ignoring RpcClosedError in heartbeat",void 0,{F:__dxlog_file$4,L:119,S:this,C:(G,K)=>G(...K)});return}U instanceof TimeoutError?(log$2("timeout waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:123,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U)):(log$2.info("other error waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:126,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U))}},this.opts.heartbeatInterval)}async onClose($){await this._ctx.dispose(),await this._rpc.close()}async onAbort($){await this._ctx.dispose(),await this._rpc.abort()}},__dxlog_file2$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/framer.ts",FRAME_LENGTH_SIZE=2,Framer=class{constructor(){this._messageCb=void 0,this._subscribeCb=void 0,this._buffer=void 0,this._sendCallbacks=[],this._bytesSent=0,this._bytesReceived=0,this._writable=!0,this.drain=new Event$1,this._stream=new readableBrowserExports.Duplex({objectMode:!1,read:()=>{this._processResponseQueue()},write:($,I,U)=>{invariant(!this._subscribeCb,"Internal Framer bug. Concurrent writes detected.",{F:__dxlog_file2$2,L:40,S:this,A:["!this._subscribeCb","'Internal Framer bug. Concurrent writes detected.'"]}),this._bytesReceived+=$.length,this._buffer&&this._buffer.length>0?this._buffer=export_Buffer.concat([this._buffer,$]):this._buffer=$,this._messageCb?(this._popFrames(),U()):this._subscribeCb=()=>{this._popFrames(),this._subscribeCb=void 0,U()}}}),this.port={send:$=>new Promise(I=>{const U=encodeFrame($);this._bytesSent+=U.length,this._writable=this._stream.push(U),this._writable?I():this._sendCallbacks.push(I)}),subscribe:$=>{var I;return invariant(!this._messageCb,"Rpc port already has a message listener.",{F:__dxlog_file2$2,L:79,S:this,A:["!this._messageCb","'Rpc port already has a message listener.'"]}),this._messageCb=$,(I=this._subscribeCb)==null||I.call(this),()=>{this._messageCb=void 0}}}}get stream(){return this._stream}get bytesSent(){return this._bytesSent}get bytesReceived(){return this._bytesReceived}get writable(){return this._writable}_processResponseQueue(){const $=this._sendCallbacks;this._sendCallbacks=[],this._writable=!0,this.drain.emit(),$.forEach(I=>I())}_popFrames(){let $=0;for(;$<this._buffer.length;){const I=decodeFrame(this._buffer,$);if(!I)break;$+=I.bytesConsumed,this._messageCb(I.payload)}$<this._buffer.length?this._buffer=this._buffer.subarray($):this._buffer=void 0}destroy(){this._stream.readableLength>0&&log$2.info("framer destroyed while there are still read bytes in the buffer.",void 0,{F:__dxlog_file2$2,L:140,S:this,C:($,I)=>$(...I)}),this._stream.writableLength>0&&log$2.warn("framer destroyed while there are still write bytes in the buffer.",void 0,{F:__dxlog_file2$2,L:143,S:this,C:($,I)=>$(...I)}),this._stream.destroy()}},decodeFrame=($,I)=>{if($.length<I+FRAME_LENGTH_SIZE)return;const U=$.readUInt16BE(I),q=FRAME_LENGTH_SIZE+U;return $.length<I+q?void 0:{payload:$.subarray(I+FRAME_LENGTH_SIZE,I+q),bytesConsumed:q}},encodeFrame=$=>{const I=export_Buffer.allocUnsafe(FRAME_LENGTH_SIZE+$.length);return I.writeUInt16BE($.length,0),I.set($,FRAME_LENGTH_SIZE),I},__dxlog_file3$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/balancer.ts",MAX_CHUNK_SIZE=8192,Balancer=class{constructor($){this._sysChannelId=$,this._lastCallerIndex=0,this._channels=[],this._framer=new Framer,this._sendBuffers=new Map,this._receiveBuffers=new Map,this._sending=!1,this.incomingData=new Event$1,this.stream=this._framer.stream,this._channels.push($),this._framer.port.subscribe(this._processIncomingMessage.bind(this))}get bytesSent(){return this._framer.bytesSent}get bytesReceived(){return this._framer.bytesReceived}get buffersCount(){return this._sendBuffers.size}addChannel($){this._channels.push($)}pushData($,I,U){this._enqueueChunk($,I,U),this._sendChunks().catch(q=>log$2.catch(q,void 0,{F:__dxlog_file3$2,L:75,S:this,C:(G,K)=>G(...K)}))}destroy(){this._sendBuffers.size!==0&&log$2.info("destroying balancer with pending calls",void 0,{F:__dxlog_file3$2,L:80,S:this,C:($,I)=>$(...I)}),this._sendBuffers.clear(),this._framer.destroy()}_processIncomingMessage($){const{channelId:I,dataLength:U,chunk:q}=decodeChunk($,G=>!this._receiveBuffers.has(G));if(!this._receiveBuffers.has(I))q.length<U?this._receiveBuffers.set(I,{buffer:export_Buffer.from(q),msgLength:U}):this.incomingData.emit(q);else{const G=this._receiveBuffers.get(I);if(G.buffer=export_Buffer.concat([G.buffer,q]),G.buffer.length<G.msgLength)return;const K=G.buffer;this._receiveBuffers.delete(I),this.incomingData.emit(K)}}_getNextCallerId(){if(this._sendBuffers.has(this._sysChannelId))return this._sysChannelId;const $=this._lastCallerIndex;return this._lastCallerIndex=(this._lastCallerIndex+1)%this._channels.length,this._channels[$]}_enqueueChunk($,I,U){if(!this._channels.includes(U))throw new Error(`Unknown channel ${U}`);this._sendBuffers.has(U)||this._sendBuffers.set(U,[]);const q=this._sendBuffers.get(U),G=[];for(let K=0;K<$.length;K+=MAX_CHUNK_SIZE)G.push($.subarray(K,K+MAX_CHUNK_SIZE));G.forEach((K,Y)=>{const J=encodeChunk({chunk:K,channelId:U,dataLength:Y===0?$.length:void 0});q.push({msg:J,trigger:Y===G.length-1?I:void 0})})}_getNextChunk(){let $;for(;this._sendBuffers.size>0;){const I=this._getNextCallerId(),U=this._sendBuffers.get(I);if(U&&($=U.shift(),!!$))return U.length===0&&this._sendBuffers.delete(I),$}return null}async _sendChunks(){var I,U;if(this._sending)return;this._sending=!0;let $;for($=this._getNextChunk();$;){this._framer.writable||(log$2("PAUSE for drain",void 0,{F:__dxlog_file3$2,L:179,S:this,C:(q,G)=>q(...G)}),await this._framer.drain.waitForCount(1),log$2("RESUME for drain",void 0,{F:__dxlog_file3$2,L:181,S:this,C:(q,G)=>q(...G)}));try{await this._framer.port.send($.msg),(I=$.trigger)==null||I.wake()}catch(q){log$2("Error sending chunk",{err:q},{F:__dxlog_file3$2,L:187,S:this,C:(G,K)=>G(...K)}),(U=$.trigger)==null||U.throw(q)}$=this._getNextChunk()}invariant(this._sendBuffers.size===0,"sendBuffers not empty",{F:__dxlog_file3$2,L:192,S:this,A:["this._sendBuffers.size === 0","'sendBuffers not empty'"]}),this._sending=!1}},encodeChunk=({channelId:$,dataLength:I,chunk:U})=>{const q=varint.encodingLength($),G=I?varint.encodingLength(I):0,K=export_Buffer.allocUnsafe(q+G+U.length);return varint.encode($,K),I&&varint.encode(I,K,q),K.set(U,q+G),K},decodeChunk=($,I)=>{const U=varint.decode($);let q,G=varint.decode.bytes;I(U)&&(q=varint.decode($,G),G+=varint.decode.bytes);const K=$.subarray(G);return{channelId:U,dataLength:q,chunk:K}};function _ts_decorate$3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts",Command=protocols.schema.getCodecForType("dxos.mesh.muxer.Command"),DEFAULT_SEND_COMMAND_TIMEOUT=6e4,DESTROY_COMMAND_SEND_TIMEOUT=5e3,STATS_INTERVAL=1e3,MAX_SAFE_FRAME_SIZE=1e6,SYSTEM_CHANNEL_ID=0,GRACEFUL_CLOSE_TIMEOUT=3e3,Muxer=class{constructor(){this._balancer=new Balancer(SYSTEM_CHANNEL_ID),this._channelsByLocalId=new Map,this._channelsByTag=new Map,this._ctx=new Context,this._nextId=1,this._closing=!1,this._destroying=!1,this._disposed=!1,this._lastStats=void 0,this._lastChannelStats=new Map,this.afterClosed=new Event$1,this.statsUpdated=new Event$1,this.stream=this._balancer.stream,this._balancer.incomingData.on(async $=>{await this._handleCommand(Command.decode($))})}setSessionId($){this._sessionId=$}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}async createStream($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:151,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});const q=new readableBrowserExports.Duplex({write:(G,K,Y)=>{this._sendData(U,G).then(()=>Y()).catch(Y)},read:()=>{}});U.push=G=>{U.stats.bytesReceived+=G.length,q.push(G)},U.destroy=G=>{G&&q.listeners("error").length>0?q.destroy(G):q.destroy()};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(G){throw this._destroyChannel(U,G),G}return q}async createPort($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:211,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});let q=[],G;U.push=Y=>{U.stats.bytesReceived+=Y.length,G?G(Y):q.push(Y)};const K={send:async(Y,J)=>{await this._sendData(U,Y,J)},subscribe:Y=>{invariant(!G,"Only one subscriber is allowed",{F:__dxlog_file4$2,L:233,S:this,A:["!callback","'Only one subscriber is allowed'"]}),G=Y;for(const J of q)Y(J);q=[]}};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(Y){throw this._destroyChannel(U,Y),Y}return K}async close($){if(this._destroying){log$2("already destroying, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:266,S:this,C:(I,U)=>I(...U)});return}if(this._closing){log$2("already closing, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:270,S:this,C:(I,U)=>I(...U)});return}this._closing=!0,await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID,DESTROY_COMMAND_SEND_TIMEOUT).catch(async I=>{log$2("error sending close command",{err:I},{F:__dxlog_file4$2,L:285,S:this,C:(U,q)=>U(...q)}),await this._dispose(I)}),await asyncTimeout(this._dispose($),GRACEFUL_CLOSE_TIMEOUT,new protocols.TimeoutError("gracefully closing muxer"))}async destroy($){if(this._destroying){log$2("already destroying, ignoring destroy request",void 0,{F:__dxlog_file4$2,L:298,S:this,C:(I,U)=>I(...U)});return}this._destroying=!0,this._ctx.dispose(),this._closing?(log$2("destroy cancelling graceful close",void 0,{F:__dxlog_file4$2,L:304,S:this,C:(I,U)=>I(...U)}),this._closing=!1):await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID).catch(async I=>{log$2("error sending courtesy close command",{err:I},{F:__dxlog_file4$2,L:317,S:this,C:(U,q)=>U(...q)})}),this._dispose($).catch(I=>{log$2("error disposing after destroy",{err:I},{F:__dxlog_file4$2,L:322,S:this,C:(U,q)=>U(...q)})})}async _dispose($){var I;if(this._disposed){log$2("already destroyed, ignoring dispose request",void 0,{F:__dxlog_file4$2,L:330,S:this,C:(U,q)=>U(...q)});return}this._ctx.dispose(),await this._balancer.destroy();for(const U of this._channelsByTag.values())(I=U.destroy)==null||I.call(U,$);this._disposed=!0,await this._emitStats(),this.afterClosed.emit($),this._channelsByLocalId.clear(),this._channelsByTag.clear()}async _handleCommand($){if(this._disposed){log$2.warn("Received command after disposed",{cmd:$},{F:__dxlog_file4$2,L:353,S:this,C:(I,U)=>I(...U)});return}if($.close){this._closing?log$2("received close from peer, already closing",void 0,{F:__dxlog_file4$2,L:362,S:this,C:(I,U)=>I(...U)}):(log$2("received peer close, initiating my own graceful close",void 0,{F:__dxlog_file4$2,L:359,S:this,C:(I,U)=>I(...U)}),await this.close(new Error("received peer close")));return}if($.openChannel){const I=this._getOrCreateStream({tag:$.openChannel.tag,contentType:$.openChannel.contentType});I.remoteId=$.openChannel.id;for(const U of I.buffer)await this._sendCommand({data:{channelId:I.remoteId,data:U}},I.id);I.buffer=[]}else if($.data){const I=this._channelsByLocalId.get($.data.channelId)??failUndefined();if(!I.push){log$2.warn("Received data for channel before it was opened",{tag:I.tag},{F:__dxlog_file4$2,L:391,S:this,C:(U,q)=>U(...q)});return}I.push($.data.data)}}async _sendCommand($,I=-1,U=DEFAULT_SEND_COMMAND_TIMEOUT){if(this._disposed){log$2.info("ignoring sendCommand after disposed",{cmd:$},{F:__dxlog_file4$2,L:400,S:this,C:(q,G)=>q(...G)});return}try{const q=new Trigger;this._balancer.pushData(Command.encode($),q,I),await q.wait({timeout:U})}catch(q){await this.destroy(q)}}_getOrCreateStream($){this._channelsByTag.size===0&&scheduleTaskInterval(this._ctx,async()=>this._emitStats(),STATS_INTERVAL);let I=this._channelsByTag.get($.tag);return I||(I={id:this._nextId++,remoteId:null,tag:$.tag,contentType:$.contentType,buffer:[],push:null,destroy:null,stats:{bytesSent:0,bytesReceived:0}},this._channelsByTag.set(I.tag,I),this._channelsByLocalId.set(I.id,I),this._balancer.addChannel(I.id)),I}async _sendData($,I,U){if(I.length>MAX_SAFE_FRAME_SIZE&&log$2.warn("frame size exceeds maximum safe value",{size:I.length,threshold:MAX_SAFE_FRAME_SIZE},{F:__dxlog_file4$2,L:441,S:this,C:(q,G)=>q(...G)}),$.stats.bytesSent+=I.length,$.remoteId===null){$.buffer.push(I);return}await this._sendCommand({data:{channelId:$.remoteId,data:I}},$.id,U)}_destroyChannel($,I){$.destroy&&$.destroy(I),this._channelsByLocalId.delete($.id),this._channelsByTag.delete($.tag)}async _emitStats(){if(this._disposed||this._destroying){if(!this._lastStats)return;const K=this._lastStats;this._lastStats=void 0,K.readBufferSize=0,K.writeBufferSize=0;for(const Y of K.channels)Y.writeBufferSize=0;this.statsUpdated.emit(K),this._lastChannelStats.clear();return}const $=this._balancer.bytesSent,I=this._balancer.bytesReceived,U=Date.now(),q=this._lastStats?(U-this._lastStats.timestamp)/1e3:0,G=(K,Y)=>Y?{bytesSentRate:q?(K.bytesSent-Y.bytesSent)/q:void 0,bytesReceivedRate:q?(K.bytesReceived-Y.bytesReceived)/q:void 0}:{};this._lastStats={timestamp:U,channels:Array.from(this._channelsByTag.values()).map(K=>{const Y={id:K.id,tag:K.tag,contentType:K.contentType,writeBufferSize:K.buffer.length,bytesSent:K.stats.bytesSent,bytesReceived:K.stats.bytesReceived,...G(K.stats,this._lastChannelStats.get(K.id))};return this._lastChannelStats.set(K.id,Y),Y}),bytesSent:$,bytesReceived:I,...G({bytesSent:$,bytesReceived:I},this._lastStats),readBufferSize:this._balancer.stream.readableLength,writeBufferSize:this._balancer.stream.writableLength},this.statsUpdated.emit(this._lastStats)}};_ts_decorate$3([logInfo],Muxer.prototype,"sessionIdString",null);function _ts_decorate2$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$1="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/teleport.ts",CONTROL_HEARTBEAT_INTERVAL=1e4,CONTROL_HEARTBEAT_TIMEOUT=6e4,Teleport=class{constructor({initiator:$,localPeerId:I,remotePeerId:U}){this._ctx=new Context({onError:q=>{this.destroy(q).catch(()=>{log$2.error("Error during destroy",q,{F:__dxlog_file5$1,L:39,S:this,C:(G,K)=>G(...K)})})}}),this._muxer=new Muxer,this._extensions=new Map,this._remoteExtensions=new Set,this._open=!1,this._destroying=!1,this._aborting=!1,invariant(typeof $=="boolean",void 0,{F:__dxlog_file5$1,L:56,S:this,A:["typeof initiator === 'boolean'",""]}),invariant(PublicKey.isPublicKey(I),void 0,{F:__dxlog_file5$1,L:57,S:this,A:["PublicKey.isPublicKey(localPeerId)",""]}),invariant(PublicKey.isPublicKey(U),void 0,{F:__dxlog_file5$1,L:58,S:this,A:["PublicKey.isPublicKey(remotePeerId)",""]}),this.initiator=$,this.localPeerId=I,this.remotePeerId=U,this._control=new ControlExtension({heartbeatInterval:CONTROL_HEARTBEAT_INTERVAL,heartbeatTimeout:CONTROL_HEARTBEAT_TIMEOUT,onTimeout:()=>{this._destroying||this._aborting||(log$2.info("abort teleport due to onTimeout in ControlExtension",void 0,{F:__dxlog_file5$1,L:71,S:this,C:(q,G)=>q(...G)}),this.abort(new protocols.TimeoutError("control extension")).catch(q=>log$2.catch(q,void 0,{F:__dxlog_file5$1,L:72,S:this,C:(G,K)=>G(...K)})))}},this.localPeerId,this.remotePeerId),this._control.onExtensionRegistered.set(async q=>{if(log$2("remote extension",{name:q},{F:__dxlog_file5$1,L:80,S:this,C:(G,K)=>G(...K)}),invariant(!this._remoteExtensions.has(q),"Remote extension already exists",{F:__dxlog_file5$1,L:81,S:this,A:["!this._remoteExtensions.has(name)","'Remote extension already exists'"]}),this._remoteExtensions.add(q),this._extensions.has(q))try{await this._openExtension(q)}catch(G){await this.destroy(G)}}),this._muxer.stream.on("close",async()=>{if(this._destroying||this._aborting){log$2("destroy teleport due to muxer stream close, skipping due to already destroying/aborting",void 0,{F:__dxlog_file5$1,L:97,S:this,C:(q,G)=>q(...G)});return}await this.destroy()}),this._muxer.stream.on("error",async q=>{await this.destroy(q)}),this._muxer.statsUpdated.on(q=>{log$2.trace("dxos.mesh.teleport.stats",{localPeerId:I,remotePeerId:U,bytesSent:q.bytesSent,bytesSentRate:q.bytesSentRate,bytesReceived:q.bytesReceived,bytesReceivedRate:q.bytesReceivedRate,channels:q.channels},{F:__dxlog_file5$1,L:110,S:this,C:(G,K)=>G(...K)})})}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}get stream(){return this._muxer.stream}get stats(){return this._muxer.statsUpdated}async open($=PublicKey.random()){this._sessionId=$,log$2("open",void 0,{F:__dxlog_file5$1,L:144,S:this,C:(I,U)=>I(...U)}),this._setExtension("dxos.mesh.teleport.control",this._control),await this._openExtension("dxos.mesh.teleport.control"),this._open=!0,this._muxer.setSessionId($)}async close($){await this.destroy($)}async abort($){if(!(this._aborting||this._destroying)&&(this._aborting=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onAbort($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:173,S:this,C:(q,G)=>q(...G)})}await this._muxer.destroy($)}}async destroy($){if(!(this._destroying||this._aborting)&&(this._destroying=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onClose($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:197,S:this,C:(q,G)=>q(...G)})}await this._muxer.close()}}addExtension($,I){if(!this._open)throw new Error("Not open");log$2("addExtension",{name:$},{F:__dxlog_file5$1,L:209,S:this,C:(U,q)=>U(...q)}),this._setExtension($,I),scheduleTask(this._ctx,async()=>{try{await this._control.registerExtension($)}catch(U){if(U instanceof protocols.RpcClosedError)return;throw U}}),this._remoteExtensions.has($)&&scheduleTask(this._ctx,async()=>{await this._openExtension($)})}_setExtension($,I){invariant(!$.includes("/"),"Invalid extension name",{F:__dxlog_file5$1,L:233,S:this,A:["!extensionName.includes('/')","'Invalid extension name'"]}),invariant(!this._extensions.has($),"Extension already exists",{F:__dxlog_file5$1,L:234,S:this,A:["!this._extensions.has(extensionName)","'Extension already exists'"]}),this._extensions.set($,I)}async _openExtension($){log$2("open extension",{extensionName:$},{F:__dxlog_file5$1,L:239,S:this,C:(q,G)=>q(...G)});const I=this._extensions.get($)??failUndefined(),U={initiator:this.initiator,localPeerId:this.localPeerId,remotePeerId:this.remotePeerId,createPort:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:247,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createPort(`${$}/${q}`,G)),createStream:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:251,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createStream(`${$}/${q}`,G)),close:q=>{runInContextAsync(this._ctx,async()=>{await this.close(q)})}};await I.onOpen(U),log$2("extension opened",{extensionName:$},{F:__dxlog_file5$1,L:262,S:this,C:(q,G)=>q(...G)})}};_ts_decorate2$2([logInfo],Teleport.prototype,"sessionIdString",null),_ts_decorate2$2([synchronized],Teleport.prototype,"abort",null),_ts_decorate2$2([synchronized],Teleport.prototype,"destroy",null);var __require=($=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy($,{get:(I,U)=>(typeof require<"u"?require:I)[U]}):$)(function($){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')});function _ts_decorate$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$3="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection.ts",STARTING_SIGNALLING_DELAY=10,TRANSPORT_CONNECTION_TIMEOUT=1e4,TRANSPORT_STATS_INTERVAL=5e3,MAX_SIGNALLING_DELAY=300,ConnectionState;(function($){$.CREATED="CREATED",$.INITIAL="INITIAL",$.CONNECTING="CONNECTING",$.CONNECTED="CONNECTED",$.CLOSING="CLOSING",$.CLOSED="CLOSED",$.ABORTING="ABORTING",$.ABORTED="ABORTED"})(ConnectionState||(ConnectionState={}));var Connection=class{constructor($,I,U,q,G,K,Y,J,X){this.topic=$,this.ownId=I,this.remoteId=U,this.sessionId=q,this.initiator=G,this._signalMessaging=K,this._protocol=Y,this._transportFactory=J,this._callbacks=X,this._ctx=new Context,this.connectedTimeoutContext=new Context,this._state="CREATED",this._incomingSignalBuffer=[],this._outgoingSignalBuffer=[],this.stateChanged=new Event$1,this.errors=new ErrorStream,this._instanceId=PublicKey.random().toHex(),this.transportStats=new Event$1,this._signalSendTask=new DeferredTask(this._ctx,async()=>{await this._flushSignalBuffer()}),this._signallingDelay=STARTING_SIGNALLING_DELAY,log$2.trace("dxos.mesh.connection.construct",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:134,S:this,C:(Z,Q)=>Z(...Q)})}get sessionIdString(){return this.sessionId.truncate()}get state(){return this._state}get transport(){return this._transport}get protocol(){return this._protocol}async openConnection(){invariant(this._state==="INITIAL","Invalid state.",{F:__dxlog_file$3,L:164,S:this,A:["this._state === ConnectionState.INITIAL","'Invalid state.'"]}),log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file$3,L:165,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.connection.open",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:166,S:this,C:($,I)=>$(...I)}),this._changeState("CONNECTING"),this._protocol.open(this.sessionId).catch($=>{this.errors.raise($)}),this._protocol.stream.on("close",()=>{log$2("protocol stream closed",void 0,{F:__dxlog_file$3,L:183,S:this,C:($,I)=>$(...I)}),this.close(new protocols.ProtocolError("protocol stream closed")).catch($=>this.errors.raise($))}),scheduleTask(this.connectedTimeoutContext,async()=>{log$2.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect, aborting`,void 0,{F:__dxlog_file$3,L:190,S:this,C:($,I)=>$(...I)}),await this.abort(new protocols.TimeoutError(`${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect`)).catch($=>this.errors.raise($))},TRANSPORT_CONNECTION_TIMEOUT),invariant(!this._transport,void 0,{F:__dxlog_file$3,L:198,S:this,A:["!this._transport",""]}),this._transport=this._transportFactory.createTransport({initiator:this.initiator,stream:this._protocol.stream,sendSignal:async $=>this._sendSignal($),sessionId:this.sessionId}),await this._transport.open(),this._transport.connected.once(async()=>{var $,I;this._changeState("CONNECTED"),await this.connectedTimeoutContext.dispose(),(I=($=this._callbacks)==null?void 0:$.onConnected)==null||I.call($),scheduleTaskInterval(this._ctx,async()=>this._emitTransportStats(),TRANSPORT_STATS_INTERVAL)}),this._transport.closed.once(()=>{this._transport=void 0,log$2("abort triggered by transport close",void 0,{F:__dxlog_file$3,L:218,S:this,C:($,I)=>$(...I)}),this.abort().catch($=>this.errors.raise($))}),this._transport.errors.handle(async $=>{log$2("transport error:",{err:$},{F:__dxlog_file$3,L:223,S:this,C:(I,U)=>I(...U)}),this.closeReason||(this.closeReason=$==null?void 0:$.message),$ instanceof protocols.ConnectionResetError?(log$2.info("aborting due to transport ConnectionResetError",void 0,{F:__dxlog_file$3,L:230,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.ConnectivityError?(log$2.info("aborting due to transport ConnectivityError",void 0,{F:__dxlog_file$3,L:233,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.UnknownProtocolError&&log$2.warn("unsure what to do with UnknownProtocolError, will keep on truckin",{err:$},{F:__dxlog_file$3,L:236,S:this,C:(I,U)=>I(...U)}),this._state!=="CLOSED"&&this._state!=="CLOSING"&&(await this.connectedTimeoutContext.dispose(),this.errors.raise($))});for(const $ of this._incomingSignalBuffer)this._transport.onSignal($);this._incomingSignalBuffer=[],log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file$3,L:252,S:this,C:($,I)=>$(...I)})}async abort($){var I,U,q;if(log$2("aborting...",{err:$},{F:__dxlog_file$3,L:259,S:this,C:(G,K)=>G(...K)}),this._state==="CLOSED"||this._state==="ABORTED"){log$2(`abort ignored: already ${this._state}`,this.closeReason,{F:__dxlog_file$3,L:261,S:this,C:(G,K)=>G(...K)});return}await this.connectedTimeoutContext.dispose(),this._changeState("ABORTING"),this.closeReason||(this.closeReason=$==null?void 0:$.message),await this._ctx.dispose();try{log$2("aborting protocol... ",void 0,{F:__dxlog_file$3,L:275,S:this,C:(G,K)=>G(...K)}),await this._protocol.abort()}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:278,S:this,C:(K,Y)=>K(...Y)})}try{await((I=this._transport)==null?void 0:I.close())}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:285,S:this,C:(K,Y)=>K(...Y)})}try{(q=(U=this._callbacks)==null?void 0:U.onClosed)==null||q.call(U,$)}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:291,S:this,C:(K,Y)=>K(...Y)})}this._changeState("ABORTED")}async close($){var U,q,G,K;if(this.closeReason?this.closeReason+=`; ${$==null?void 0:$.message}`:this.closeReason=$==null?void 0:$.message,this._state==="CLOSED"||this._state==="ABORTING"||this._state==="ABORTED")return;const I=this._state;if(this._changeState("CLOSING"),await this.connectedTimeoutContext.dispose(),await this._ctx.dispose(),log$2("closing...",{peerId:this.ownId},{F:__dxlog_file$3,L:316,S:this,C:(Y,J)=>Y(...J)}),I==="CONNECTED"){try{await this._protocol.close()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:323,S:this,C:(J,X)=>J(...X)})}try{await((U=this._transport)==null?void 0:U.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:330,S:this,C:(J,X)=>J(...X)})}}else{log$2.info(`graceful close requested when we were in ${I} state? aborting`,void 0,{F:__dxlog_file$3,L:333,S:this,C:(Y,J)=>Y(...J)});try{await this._protocol.abort()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:337,S:this,C:(J,X)=>J(...X)})}try{await((q=this._transport)==null?void 0:q.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:342,S:this,C:(J,X)=>J(...X)})}}log$2("closed",{peerId:this.ownId},{F:__dxlog_file$3,L:346,S:this,C:(Y,J)=>Y(...J)}),this._changeState("CLOSED"),(K=(G=this._callbacks)==null?void 0:G.onClosed)==null||K.call(G,$)}_sendSignal($){this._outgoingSignalBuffer.push($),this._signalSendTask.schedule()}async _flushSignalBuffer(){var $;if(this._outgoingSignalBuffer.length!==0)try{await cancelWithContext(this._ctx,sleep(this._signallingDelay)),this._signallingDelay=Math.min(this._signallingDelay*2,MAX_SIGNALLING_DELAY);const I=[...this._outgoingSignalBuffer];this._outgoingSignalBuffer.length=0,await this._signalMessaging.signal({author:this.ownId,recipient:this.remoteId,sessionId:this.sessionId,topic:this.topic,data:{signalBatch:{signals:I}}})}catch(I){if(I instanceof protocols.CancelledError||I instanceof Error&&(($=I.message)!=null&&$.includes("CANCELLED")))return;log$2.info("signal message failed to deliver",{err:I},{F:__dxlog_file$3,L:384,S:this,C:(U,q)=>U(...q)}),await this.close(new protocols.ConnectivityError("signal message failed to deliver",I))}}async signal($){var U,q;if(invariant($.sessionId,void 0,{F:__dxlog_file$3,L:393,S:this,A:["msg.sessionId",""]}),!$.sessionId.equals(this.sessionId)){log$2("dropping signal for incorrect session id",void 0,{F:__dxlog_file$3,L:395,S:this,C:(G,K)=>G(...K)});return}invariant($.data.signal||$.data.signalBatch,void 0,{F:__dxlog_file$3,L:398,S:this,A:["msg.data.signal || msg.data.signalBatch",""]}),invariant((U=$.author)==null?void 0:U.equals(this.remoteId),void 0,{F:__dxlog_file$3,L:399,S:this,A:["msg.author?.equals(this.remoteId)",""]}),invariant((q=$.recipient)==null?void 0:q.equals(this.ownId),void 0,{F:__dxlog_file$3,L:400,S:this,A:["msg.recipient?.equals(this.ownId)",""]});const I=$.data.signalBatch?$.data.signalBatch.signals??[]:[$.data.signal];for(const G of I)G&&(["CREATED","INITIAL"].includes(this.state)?(log$2("buffered signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:409,S:this,C:(K,Y)=>K(...Y)}),this._incomingSignalBuffer.push(G)):(invariant(this._transport,"Connection not ready to accept signals.",{F:__dxlog_file$3,L:412,S:this,A:["this._transport","'Connection not ready to accept signals.'"]}),log$2("received signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:413,S:this,C:(K,Y)=>K(...Y)}),await this._transport.onSignal(G)))}initiate(){this._changeState("INITIAL")}_changeState($){log$2("stateChanged",{from:this._state,to:$,peerId:this.ownId},{F:__dxlog_file$3,L:424,S:this,C:(I,U)=>I(...U)}),invariant($!==this._state,"Already in this state.",{F:__dxlog_file$3,L:425,S:this,A:["state !== this._state","'Already in this state.'"]}),this._state=$,this.stateChanged.emit($)}async _emitTransportStats(){var I;const $=await((I=this.transport)==null?void 0:I.getStats());$&&this.transportStats.emit($)}};_ts_decorate$2([logInfo],Connection.prototype,"sessionIdString",null),_ts_decorate$2([synchronized],Connection.prototype,"abort",null),_ts_decorate$2([synchronized],Connection.prototype,"close",null);var __dxlog_file2$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts",SwarmMessage=protocols.schema.getCodecForType("dxos.mesh.swarm.SwarmMessage"),SwarmMessenger=class{constructor({sendMessage:$,onSignal:I,onOffer:U,topic:q}){this._ctx=new Context,this._offerRecords=new ComplexMap(G=>G.toHex()),this._sendMessage=$,this._onSignal=I,this._onOffer=U,this._topic=q}async receiveMessage({author:$,recipient:I,payload:U}){var G,K,Y,J;if(U.type_url!=="dxos.mesh.swarm.SwarmMessage")return;const q=SwarmMessage.decode(U.value);this._topic.equals(q.topic)&&(log$2("received",{from:$,to:I,msg:q},{F:__dxlog_file2$1,L:69,S:this,C:(X,Z)=>X(...Z)}),(G=q.data)!=null&&G.offer?await this._handleOffer({author:$,recipient:I,message:q}):(K=q.data)!=null&&K.answer?await this._resolveAnswers(q):(Y=q.data)!=null&&Y.signal?await this._handleSignal({author:$,recipient:I,message:q}):(J=q.data)!=null&&J.signalBatch?await this._handleSignal({author:$,recipient:I,message:q}):log$2.warn("unknown message",{message:q},{F:__dxlog_file2$1,L:80,S:this,C:(X,Z)=>X(...Z)}))}async signal($){var I,U;invariant(((I=$.data)==null?void 0:I.signal)||((U=$.data)==null?void 0:U.signalBatch),"Invalid message",{F:__dxlog_file2$1,L:85,S:this,A:["message.data?.signal || message.data?.signalBatch","'Invalid message'"]}),await this._sendReliableMessage({author:$.author,recipient:$.recipient,message:$})}async offer($){const I={...$,messageId:PublicKey.random()};return new Promise((U,q)=>{this._offerRecords.set(I.messageId,{resolve:U}),this._sendReliableMessage({author:$.author,recipient:$.recipient,message:I}).catch(G=>q(G))})}async _sendReliableMessage({author:$,recipient:I,message:U}){const q={...U,messageId:U.messageId??PublicKey.random()};log$2("sending",{from:$,to:I,msg:q},{F:__dxlog_file2$1,L:123,S:this,C:(G,K)=>G(...K)}),await this._sendMessage({author:$,recipient:I,payload:{type_url:"dxos.mesh.swarm.SwarmMessage",value:SwarmMessage.encode(q)}})}async _resolveAnswers($){var U,q,G;invariant((q=(U=$.data)==null?void 0:U.answer)==null?void 0:q.offerMessageId,"No offerMessageId",{F:__dxlog_file2$1,L:135,S:this,A:["message.data?.answer?.offerMessageId","'No offerMessageId'"]});const I=this._offerRecords.get($.data.answer.offerMessageId);I&&(this._offerRecords.delete($.data.answer.offerMessageId),invariant((G=$.data)==null?void 0:G.answer,"No answer",{F:__dxlog_file2$1,L:139,S:this,A:["message.data?.answer","'No answer'"]}),log$2("resolving",{answer:$.data.answer},{F:__dxlog_file2$1,L:140,S:this,C:(K,Y)=>K(...Y)}),I.resolve($.data.answer))}async _handleOffer({author:$,recipient:I,message:U}){invariant(U.data.offer,"No offer",{F:__dxlog_file2$1,L:154,S:this,A:["message.data.offer","'No offer'"]});const q={author:$,recipient:I,...U,data:{offer:U.data.offer}},G=await this._onOffer(q);G.offerMessageId=U.messageId;try{await this._sendReliableMessage({author:I,recipient:$,message:{topic:U.topic,sessionId:U.sessionId,data:{answer:G}}})}catch(K){K instanceof protocols.TimeoutError?log$2.info("timeout sending answer to offer",{err:K},{F:__dxlog_file2$1,L:175,S:this,C:(Y,J)=>Y(...J)}):log$2.info("error sending answer to offer",{err:K},{F:__dxlog_file2$1,L:177,S:this,C:(Y,J)=>Y(...J)})}}async _handleSignal({author:$,recipient:I,message:U}){invariant(U.messageId,void 0,{F:__dxlog_file2$1,L:191,S:this,A:["message.messageId",""]}),invariant(U.data.signal||U.data.signalBatch,"Invalid message",{F:__dxlog_file2$1,L:192,S:this,A:["message.data.signal || message.data.signalBatch","'Invalid message'"]});const q={author:$,recipient:I,...U,data:{signal:U.data.signal,signalBatch:U.data.signalBatch}};await this._onSignal(q)}};function _ts_decorate2$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file3$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts",ConnectionDisplacedError=class extends protocols.SystemError{constructor(){super("Connection displaced by remote initiator.")}},CONNECTION_COUNTS_STABLE_AFTER=5e3,Peer=class{constructor($,I,U,q,G,K,Y,J){this.id=$,this.topic=I,this.localPeerId=U,this._signalMessaging=q,this._protocolProvider=G,this._transportFactory=K,this._connectionLimiter=Y,this._callbacks=J,this._availableAfter=0,this.availableToConnect=!0,this._ctx=new Context,this.advertizing=!1,this.initiating=!1,this.connectionDisplaced=new Event$1}async onOffer($){var U;const I=$.author;if(this.connection&&![ConnectionState.CREATED,ConnectionState.INITIAL,ConnectionState.CONNECTING].includes(this.connection.state))return log$2.info(`received offer when connection already in ${this.connection.state} state`,void 0,{F:__dxlog_file3$1,L:114,S:this,C:(q,G)=>q(...G)}),{accept:!1};if(this.connection||this.initiating)if(I.toHex()<this.localPeerId.toHex())log$2("close local connection",{localPeerId:this.id,topic:this.topic,remotePeerId:this.localPeerId,sessionId:(U=this.connection)==null?void 0:U.sessionId},{F:__dxlog_file3$1,L:123,S:this,C:(q,G)=>q(...G)}),this.connection&&await this.closeConnection(new ConnectionDisplacedError);else return{accept:!1};if(await this._callbacks.onOffer(I)&&!this.connection){invariant($.sessionId,void 0,{F:__dxlog_file3$1,L:143,S:this,A:["message.sessionId",""]});const q=this._createConnection(!1,$.sessionId);try{await this._connectionLimiter.connecting($.sessionId),q.initiate(),await q.openConnection()}catch(G){G instanceof protocols.CancelledError||log$2.info("connection error",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,err:G},{F:__dxlog_file3$1,L:153,S:this,C:(K,Y)=>K(...Y)}),await this.closeConnection(G)}return{accept:!0}}return{accept:!1}}async initiateConnection(){invariant(!this.initiating,"Initiation in progress.",{F:__dxlog_file3$1,L:170,S:this,A:["!this.initiating","'Initiation in progress.'"]}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3$1,L:171,S:this,A:["!this.connection","'Already connected.'"]});const $=PublicKey.random();log$2("initiating...",{id:this.id,topic:this.topic,peerId:this.id,sessionId:$},{F:__dxlog_file3$1,L:173,S:this,C:(q,G)=>q(...G)});const I=this._createConnection(!0,$);this.initiating=!0;let U;try{if(await this._connectionLimiter.connecting($),I.initiate(),U=await this._signalMessaging.offer({author:this.localPeerId,recipient:this.id,sessionId:$,topic:this.topic,data:{offer:{}}}),log$2("received",{answer:U,topic:this.topic,ownId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:190,S:this,C:(q,G)=>q(...G)}),I.state!==ConnectionState.INITIAL){log$2("ignoring response",void 0,{F:__dxlog_file3$1,L:192,S:this,C:(q,G)=>q(...G)});return}}catch(q){throw log$2("initiation error: send offer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:196,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{if(!U.accept){this._callbacks.onRejected();return}}catch(q){throw log$2("initiation error: accept answer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:209,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{log$2("opening connection as initiator",void 0,{F:__dxlog_file3$1,L:222,S:this,C:(q,G)=>q(...G)}),await I.openConnection(),this._callbacks.onAccepted()}catch(q){throw log$2("initiation error: open connection",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3$1,L:226,S:this,C:(G,K)=>G(...K)}),log$2.warn("closing connection due to unhandled error on openConnection",{err:q},{F:__dxlog_file3$1,L:233,S:this,C:(G,K)=>G(...K)}),await this.closeConnection(q),q}finally{this.initiating=!1}}_createConnection($,I){var q;log$2("creating connection",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,sessionId:I},{F:__dxlog_file3$1,L:247,S:this,C:(G,K)=>G(...K)}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3$1,L:254,S:this,A:["!this.connection","'Already connected.'"]});const U=new Connection(this.topic,this.localPeerId,this.id,I,$,this._signalMessaging,this._protocolProvider({initiator:$,localPeerId:this.localPeerId,remotePeerId:this.id,topic:this.topic}),this._transportFactory,{onConnected:()=>{this.availableToConnect=!0,this._lastConnectionTime=Date.now(),this._callbacks.onConnected(),this._connectionLimiter.doneConnecting(I),log$2.trace("dxos.mesh.connection.connected",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3$1,L:273,S:this,C:(G,K)=>G(...K)})},onClosed:G=>{log$2("connection closed",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$},{F:__dxlog_file3$1,L:282,S:this,C:(K,Y)=>K(...Y)}),this._connectionLimiter.doneConnecting(I),invariant(this.connection===U,"Connection mismatch (race condition).",{F:__dxlog_file3$1,L:287,S:this,A:["this.connection === connection","'Connection mismatch (race condition).'"]}),log$2.trace("dxos.mesh.connection.closed",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3$1,L:289,S:this,C:(K,Y)=>K(...Y)}),G instanceof ConnectionDisplacedError?this.connectionDisplaced.emit(this.connection):(this._lastConnectionTime&&this._lastConnectionTime+CONNECTION_COUNTS_STABLE_AFTER<Date.now()?this._availableAfter=0:(this.availableToConnect=!1,this._availableAfter=increaseInterval(this._availableAfter)),this._callbacks.onDisconnected(),scheduleTask(this._connectionCtx,()=>{this.availableToConnect=!0,this._callbacks.onPeerAvailable()},this._availableAfter)),this.connection=void 0}});return this._callbacks.onInitiated(U),(q=this._connectionCtx)==null||q.dispose(),this._connectionCtx=this._ctx.derive(),U.errors.handle(G=>{log$2.info("connection error, closing",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,err:G},{F:__dxlog_file3$1,L:329,S:this,C:(K,Y)=>K(...Y)}),log$2.trace("dxos.mesh.connection.error",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$,err:G},{F:__dxlog_file3$1,L:336,S:this,C:(K,Y)=>K(...Y)}),this.closeConnection(G)}),this.connection=U,U}async closeConnection($){if(!this.connection)return;const I=this.connection;log$2("closing...",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3$1,L:361,S:this,C:(U,q)=>U(...q)}),await I.close($),log$2("closed",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3$1,L:367,S:this,C:(U,q)=>U(...q)})}async onSignal($){if(!this.connection){log$2("dropping signal message for non-existent connection",{message:$},{F:__dxlog_file3$1,L:372,S:this,C:(I,U)=>I(...U)});return}await this.connection.signal($)}async destroy($){var I;await this._ctx.dispose(),log$2("Destroying peer",{peerId:this.id,topic:this.topic},{F:__dxlog_file3$1,L:382,S:this,C:(U,q)=>U(...q)}),await((I=this==null?void 0:this.connection)==null?void 0:I.close($))}};_ts_decorate2$1([synchronized],Peer.prototype,"destroy",null);var increaseInterval=$=>$===0?50:$<500?500:$<1e3?1e3:$<5e3?5e3:1e4;function _ts_decorate3$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts",INITIATION_DELAY=100,getClassName=$=>Object.getPrototypeOf($).constructor.name,Swarm=class{constructor($,I,U,q,G,K,Y,J,X=INITIATION_DELAY){this._topic=$,this._ownPeerId=I,this._topology=U,this._protocolProvider=q,this._messenger=G,this._transportFactory=K,this._label=Y,this._connectionLimiter=J,this._initiationDelay=X,this._ctx=new Context,this._listeningHandle=void 0,this._peers=new ComplexMap(PublicKey.hash),this._instanceId=PublicKey.random().toHex(),this.connectionAdded=new Event$1,this.disconnected=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.begin({id:this._instanceId,data:{topic:this._topic.toHex(),peerId:this._ownPeerId.toHex()}}),{F:__dxlog_file4$1,L:89,S:this,C:(Z,Q)=>Z(...Q)}),log$2("creating swarm",{peerId:I},{F:__dxlog_file4$1,L:93,S:this,C:(Z,Q)=>Z(...Q)}),U.init(this._getSwarmController()),this._swarmMessenger=new SwarmMessenger({sendMessage:async Z=>await this._messenger.sendMessage(Z),onSignal:async Z=>await this.onSignal(Z),onOffer:async Z=>await this.onOffer(Z),topic:this._topic}),log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file4$1,L:102,S:this,C:(Z,Q)=>Z(...Q)})}get connections(){return Array.from(this._peers.values()).map($=>$.connection).filter(isNotNullOrUndefined)}get ownPeerId(){return this._ownPeerId}get label(){return this._label}get topic(){return this._topic}async open(){invariant(!this._listeningHandle,void 0,{F:__dxlog_file4$1,L:129,S:this,A:["!this._listeningHandle",""]}),this._listeningHandle=await this._messenger.listen({peerId:this._ownPeerId,payloadType:"dxos.mesh.swarm.SwarmMessage",onMessage:async $=>{await this._swarmMessenger.receiveMessage($).catch(I=>log$2.info("Error while receiving message",{err:I},{F:__dxlog_file4$1,L:137,S:this,C:(U,q)=>U(...q)}))}})}async destroy(){var $;log$2("destroying...",void 0,{F:__dxlog_file4$1,L:143,S:this,C:(I,U)=>I(...U)}),await(($=this._listeningHandle)==null?void 0:$.unsubscribe()),this._listeningHandle=void 0,await this._ctx.dispose(),await this._topology.destroy(),await Promise.all(Array.from(this._peers.keys()).map(I=>this._destroyPeer(I,"swarm destroyed"))),log$2("destroyed",void 0,{F:__dxlog_file4$1,L:150,S:this,C:(I,U)=>I(...U)})}async setTopology($){invariant(!this._ctx.disposed,"Swarm is offline",{F:__dxlog_file4$1,L:154,S:this,A:["!this._ctx.disposed","'Swarm is offline'"]}),$!==this._topology&&(log$2("setting topology",{previous:getClassName(this._topology),topology:getClassName($)},{F:__dxlog_file4$1,L:158,S:this,C:(I,U)=>I(...U)}),await this._topology.destroy(),this._topology=$,this._topology.init(this._getSwarmController()),this._topology.update())}onSwarmEvent($){var I;if(log$2("swarm event",{swarmEvent:$},{F:__dxlog_file4$1,L:171,S:this,C:(U,q)=>U(...q)}),this._ctx.disposed){log$2("swarm event ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:174,S:this,C:(U,q)=>U(...q)});return}if($.peerAvailable){const U=PublicKey.from($.peerAvailable.peer);if(log$2("new peer",{peerId:U},{F:__dxlog_file4$1,L:180,S:this,C:(q,G)=>q(...G)}),!U.equals(this._ownPeerId)){const q=this._getOrCreatePeer(U);q.advertizing=!0}}else if($.peerLeft){const U=this._peers.get(PublicKey.from($.peerLeft.peer));U?(U.advertizing=!1,((I=U.connection)==null?void 0:I.state)!==ConnectionState.CONNECTED&&this._destroyPeer(U.id,"peer left").catch(q=>log$2.catch(q,void 0,{F:__dxlog_file4$1,L:191,S:this,C:(G,K)=>G(...K)}))):log$2("received peerLeft but no peer found",{peer:$.peerLeft.peer},{F:__dxlog_file4$1,L:194,S:this,C:(q,G)=>q(...G)})}this._topology.update()}async onOffer($){var q,G;if(log$2("offer",{message:$},{F:__dxlog_file4$1,L:203,S:this,C:(K,Y)=>K(...Y)}),this._ctx.disposed)return log$2("ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:205,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(invariant($.author,void 0,{F:__dxlog_file4$1,L:210,S:this,A:["message.author",""]}),!((q=$.recipient)!=null&&q.equals(this._ownPeerId)))return log$2("rejecting offer with incorrect peerId",{message:$},{F:__dxlog_file4$1,L:212,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(!((G=$.topic)!=null&&G.equals(this._topic)))return log$2("rejecting offer with incorrect topic",{message:$},{F:__dxlog_file4$1,L:216,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};const U=await this._getOrCreatePeer($.author).onOffer($);return this._topology.update(),U}async onSignal($){var U,q;if(log$2("signal",{message:$},{F:__dxlog_file4$1,L:227,S:this,C:(G,K)=>G(...K)}),this._ctx.disposed){log$2.info("ignored for offline swarm",void 0,{F:__dxlog_file4$1,L:229,S:this,C:(G,K)=>G(...K)});return}invariant((U=$.recipient)==null?void 0:U.equals(this._ownPeerId),`Invalid signal peer id expected=${this.ownPeerId}, actual=${$.recipient}`,{F:__dxlog_file4$1,L:232,S:this,A:["message.recipient?.equals(this._ownPeerId)","`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"]}),invariant((q=$.topic)==null?void 0:q.equals(this._topic),void 0,{F:__dxlog_file4$1,L:236,S:this,A:["message.topic?.equals(this._topic)",""]}),invariant($.author,void 0,{F:__dxlog_file4$1,L:237,S:this,A:["message.author",""]}),await this._getOrCreatePeer($.author).onSignal($)}async goOffline(){await this._ctx.dispose(),await Promise.all([...this._peers.keys()].map($=>this._destroyPeer($,"goOffline")))}async goOnline(){this._ctx=new Context}_getOrCreatePeer($){let I=this._peers.get($);return I||(I=new Peer($,this._topic,this._ownPeerId,this._swarmMessenger,this._protocolProvider,this._transportFactory,this._connectionLimiter,{onInitiated:U=>{this.connectionAdded.emit(U)},onConnected:()=>{this.connected.emit($)},onDisconnected:async()=>{I.advertizing||await this._destroyPeer(I.id,"peer disconnected"),this.disconnected.emit($),this._topology.update()},onRejected:()=>{this._peers.has($)&&(log$2("peer rejected connection",{peerId:$},{F:__dxlog_file4$1,L:286,S:this,C:(U,q)=>U(...q)}),this._destroyPeer($,"peer rejected connection"))},onAccepted:()=>{this._topology.update()},onOffer:U=>this._topology.onOffer(U),onPeerAvailable:()=>{this._topology.update()}}),this._peers.set($,I)),I}async _destroyPeer($,I){invariant(this._peers.has($),void 0,{F:__dxlog_file4$1,L:308,S:this,A:["this._peers.has(peerId)",""]}),await this._peers.get($).destroy(new Error(I)),this._peers.delete($)}_getSwarmController(){return{getState:()=>({ownPeerId:this._ownPeerId,connected:Array.from(this._peers.values()).filter($=>$.connection).map($=>$.id),candidates:Array.from(this._peers.values()).filter($=>!$.connection&&$.advertizing&&$.availableToConnect).map($=>$.id)}),connect:$=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{try{await this._initiateConnection($)}catch(I){log$2("initiation error",I,{F:__dxlog_file4$1,L:334,S:this,C:(U,q)=>U(...q)})}})},disconnect:async $=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{await this._closeConnection($),this._topology.update()})}}}async _initiateConnection($){const I=this._ctx;if($.toHex()<this._ownPeerId.toHex()&&(log$2("initiation delay",{remoteId:$},{F:__dxlog_file4$1,L:361,S:this,C:(q,G)=>q(...G)}),await sleep(this._initiationDelay)),I.disposed)return;const U=this._getOrCreatePeer($);U.connection||(log$2("initiating connection...",{remoteId:$},{F:__dxlog_file4$1,L:375,S:this,C:(q,G)=>q(...G)}),await U.initiateConnection(),this._topology.update(),log$2("initiated",{remoteId:$},{F:__dxlog_file4$1,L:378,S:this,C:(q,G)=>q(...G)}))}async _closeConnection($){const I=this._peers.get($);I&&await I.closeConnection()}};_ts_decorate3$1([logInfo],Swarm.prototype,"_instanceId",void 0),_ts_decorate3$1([logInfo],Swarm.prototype,"ownPeerId",null),_ts_decorate3$1([logInfo],Swarm.prototype,"topic",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onSwarmEvent",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onOffer",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOffline",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOnline",null);var EventType;(function($){$.CONNECTION_STATE_CHANGED="CONNECTION_STATE_CHANGED",$.PROTOCOL_ERROR="PROTOCOL_ERROR",$.PROTOCOL_EXTENSIONS_INITIALIZED="PROTOCOL_EXTENSIONS_INITIALIZED",$.PROTOCOL_EXTENSIONS_HANDSHAKE="PROTOCOL_EXTENSIONS_HANDSHAKE",$.PROTOCOL_HANDSHAKE="PROTOCOL_HANDSHAKE"})(EventType||(EventType={}));function _ts_decorate4$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file11="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts",MEMORY_TRANSPORT_DELAY=1,createStreamDelay=$=>new readableBrowserExports.Transform({objectMode:!0,transform:(I,U,q)=>{setTimeout(()=>q(null,I),$)}}),MemoryTransport=(Zn=class{constructor(I){this._options=I,this._instanceId=PublicKey.random(),this._remote=new Trigger,this._outgoingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._incomingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._closed=!1,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,invariant(!Zn._connections.has(this._instanceId),"Duplicate memory connection",{F:__dxlog_file11,L:64,S:this,A:["!MemoryTransport._connections.has(this._instanceId)","'Duplicate memory connection'"]}),Zn._connections.set(this._instanceId,this)}get isOpen(){return!this._closed}async open(){if(log$2("opening...",void 0,{F:__dxlog_file11,L:74,S:this,C:(I,U)=>I(...U)}),this._options.initiator){log$2("sending signal",void 0,{F:__dxlog_file11,L:78,S:this,C:(I,U)=>I(...U)});try{await this._options.sendSignal({payload:{transportId:this._instanceId.toHex()}})}catch(I){this._closed||this.errors.raise(toError(I))}}else this._remote.wait({timeout:this._options.timeout??1e3}).then(I=>{if(!this._closed){if(this._remoteInstanceId=I,this._remoteConnection=Zn._connections.get(this._remoteInstanceId),!this._remoteConnection){this._closed=!0,this.closed.emit();return}invariant(!this._remoteConnection._remoteConnection,`Remote already connected: ${this._remoteInstanceId}`,{F:__dxlog_file11,L:104,S:this,A:["!this._remoteConnection._remoteConnection","`Remote already connected: ${this._remoteInstanceId}`"]}),this._remoteConnection._remoteConnection=this,this._remoteConnection._remoteInstanceId=this._instanceId,log$2("connected",void 0,{F:__dxlog_file11,L:108,S:this,C:(U,q)=>U(...q)}),this._options.stream.pipe(this._outgoingDelay).pipe(this._remoteConnection._options.stream).pipe(this._incomingDelay).pipe(this._options.stream),this.connected.emit(),this._remoteConnection.connected.emit()}}).catch(I=>{this._closed||this.errors.raise(I)})}async close(){log$2("closing...",void 0,{F:__dxlog_file11,L:129,S:this,C:(I,U)=>I(...U)}),this._closed=!0,Zn._connections.delete(this._instanceId),this._remoteConnection&&(this._remoteConnection._closed=!0,Zn._connections.delete(this._remoteInstanceId),this._options.stream.unpipe(this._incomingDelay),this._incomingDelay.unpipe(this._remoteConnection._options.stream),this._remoteConnection._options.stream.unpipe(this._outgoingDelay),this._outgoingDelay.unpipe(this._options.stream),this._options.stream.unpipe(this._outgoingDelay),this._remoteConnection.closed.emit(),this._remoteConnection._remoteConnection=void 0,this._remoteConnection=void 0),this.closed.emit(),log$2("closed",void 0,{F:__dxlog_file11,L:157,S:this,C:(I,U)=>I(...U)})}async onSignal({payload:I}){if(log$2("received signal",{payload:I},{F:__dxlog_file11,L:161,S:this,C:(q,G)=>q(...G)}),!(I!=null&&I.transportId))return;const U=I.transportId;if(U){const q=PublicKey.fromHex(U);this._remote.wake(q)}}async getDetails(){return this._instanceId.toHex()}async getStats(){return{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0}}},Zn._connections=new ComplexMap(PublicKey.hash),Zn);_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_instanceId",void 0),_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_remoteInstanceId",void 0);var toError=$=>$ instanceof Error?$:new Error(String($)),TransportKind;(function($){$.SIMPLE_PEER="SIMPLE_PEER",$.SIMPLE_PEER_PROXY="SIMPLE_PEER_PROXY",$.LIBDATACHANNEL="LIBDATACHANNEL",$.MEMORY="MEMORY",$.TCP="TCP"})(TransportKind||(TransportKind={}));var wrtc=null;try{wrtc=__require("@koush/wrtc")}catch{}function _ts_decorate5$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file15="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts",DATACHANNEL_LABEL="dxos.mesh.transport",MAX_BUFFERED_AMOUNT=64*1024,MAX_MESSAGE_SIZE=64*1024,LibDataChannelTransport=(rr=class{constructor(I){this._options=I,this._closed=!1,this._connected=!1,this._writeCallback=null,this._readyForCandidates=new Trigger,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream}get isOpen(){return!!this._peer&&!this._closed}async open(){this._closed&&this.errors.raise(new Error("connection already closed"));const{RTCPeerConnection:I}=(await importESM("node-datachannel/polyfill")).default;this._options.webrtcConfig?this._options.webrtcConfig.iceServers=this._options.webrtcConfig.iceServers??[]:this._options.webrtcConfig={iceServers:[]},this._peer=new I(this._options.webrtcConfig),this._peer.onicecandidateerror=U=>{log$2.error("peer.onicecandidateerror",{event:U},{F:__dxlog_file15,L:77,S:this,C:(q,G)=>q(...G)})},this._peer.onconnectionstatechange=U=>{var q;log$2.debug("peer.onconnectionstatechange",{event:U,peerConnectionState:(q=this._peer)==null?void 0:q.connectionState,transportConnectionState:this._connected},{F:__dxlog_file15,L:81,S:this,C:(G,K)=>G(...K)})},this._peer.onicecandidate=async U=>{if(log$2.debug("peer.onicecandidate",{event:U},{F:__dxlog_file15,L:91,S:this,C:(q,G)=>q(...G)}),U.candidate)try{await this._options.sendSignal({payload:{data:{type:"candidate",candidate:{candidate:U.candidate.candidate,sdpMLineIndex:U.candidate.sdpMLineIndex??0,sdpMid:U.candidate.sdpMid??0}}}})}catch(q){log$2.info("signaling error",{err:q},{F:__dxlog_file15,L:108,S:this,C:(G,K)=>G(...K)})}},this._options.initiator?(invariant(this._peer,"not open",{F:__dxlog_file15,L:114,S:this,A:["this._peer","'not open'"]}),this._peer.createOffer().then(async U=>{var q;this._closed||(((q=this._peer)==null?void 0:q.connectionState)!=="connecting"&&(log$2.error("peer not connecting",{peer:this._peer},{F:__dxlog_file15,L:125,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"))),log$2.debug("creating offer",{peer:this._peer,offer:U},{F:__dxlog_file15,L:129,S:this,C:(G,K)=>G(...K)}),await this._peer.setLocalDescription(U),await this._options.sendSignal({payload:{data:{type:U.type,sdp:U.sdp}}}))}).catch(U=>{this.errors.raise(U)}),this._handleChannel(this._peer.createDataChannel(DATACHANNEL_LABEL)),log$2.debug("created data channel",void 0,{F:__dxlog_file15,L:139,S:this,C:(U,q)=>U(...q)}),this._peer.ondatachannel=()=>{this.errors.raise(new Error("unexpected ondatachannel event for initiator"))}):this._peer.ondatachannel=U=>{log$2.debug("peer.ondatachannel (non-initiator)",{event:U},{F:__dxlog_file15,L:145,S:this,C:(q,G)=>q(...G)}),U.channel.label!==DATACHANNEL_LABEL&&this.errors.raise(new Error(`unexpected channel label ${U.channel.label}`)),this._handleChannel(U.channel)},rr._instanceCount++}async close(){await this._close(),--rr._instanceCount===0&&(await importESM("node-datachannel")).cleanup()}async _close(){var I;if(!this._closed){await this._disconnectStreams();try{(I=this._peer)==null||I.close()}catch(U){this.errors.raise(U)}this._peer=void 0,this._closed=!0,this.closed.emit()}}_handleChannel(I){this._channel=I,this._channel.onopen=()=>{log$2.debug("channel.onopen",void 0,{F:__dxlog_file15,L:190,S:this,C:(q,G)=>q(...G)});const U=new stream.Duplex({read:()=>{},write:async(q,G,K)=>{q.length>MAX_MESSAGE_SIZE&&this.errors.raise(new Error(`message too large: ${q.length} > ${MAX_MESSAGE_SIZE}`));try{I.send(q)}catch(Y){this.errors.raise(Y),await this._close()}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._writeCallback!==null&&log$2.error("consumer trying to write before we are ready for more data",void 0,{F:__dxlog_file15,L:207,S:this,C:(Y,J)=>Y(...J)}),this._writeCallback=K):K()}});U.pipe(this._options.stream).pipe(U),this._stream=U,this._connected=!0,this.connected.emit()},this._channel.onclose=async U=>{log$2.info("channel.onclose",{err:U},{F:__dxlog_file15,L:223,S:this,C:(q,G)=>q(...G)}),await this._close()},this._channel.onerror=async U=>{this.errors.raise(new Error("channel error: "+U.toString())),await this._close()},this._channel.onbufferedamountlow=()=>{const U=this._writeCallback;this._writeCallback=null,U==null||U()},this._channel.onmessage=U=>{let q=U.data;q instanceof ArrayBuffer&&(q=export_Buffer.from(q)),this._stream.push(q)}}async onSignal(I){invariant(this._peer,"not open",{F:__dxlog_file15,L:249,S:this,A:["this._peer","'not open'"]});try{const U=I.payload.data;switch(U.type){case"offer":{if(this._peer.connectionState!=="new"){log$2.error("received offer but peer not in state new",{peer:this._peer},{F:__dxlog_file15,L:256,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));break}try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp});const q=await this._peer.createAnswer();await this._peer.setLocalDescription(q),await this._options.sendSignal({payload:{data:{type:q.type,sdp:q.sdp}}}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle offer from signalling server",{err:q},{F:__dxlog_file15,L:268,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling offer"))}break}case"answer":try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle answer from signalling server",{err:q},{F:__dxlog_file15,L:279,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling answer"))}break;case"candidate":await this._readyForCandidates.wait(),await this._peer.addIceCandidate({candidate:U.candidate.candidate});break;default:log$2.error("unhandled signal type",{type:U.type,signal:I},{F:__dxlog_file15,L:290,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error(`unhandled signal type ${U.type}`))}}catch(U){log$2.catch(U,void 0,{F:__dxlog_file15,L:294,S:this,C:(q,G)=>q(...G)})}}async getDetails(){const I=await this._getStats(),U=I==null?void 0:I.remoteCandidate;return U?U.candidateType==="relay"?`${U.ip}:${U.port} relay for ${U.relatedAddress}:${U.relatedPort}`:`${U.ip}:${U.port} ${U.candidateType}`:"unavailable"}async getStats(){const I=await this._getStats();return I?{bytesSent:I.transport.bytesSent,bytesReceived:I.transport.bytesReceived,packetsSent:0,packetsReceived:0,rawStats:I.raw}:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rawStats:{}}}async _getStats(){invariant(this._peer,"not open",{F:__dxlog_file15,L:334,S:this,A:["this._peer","'not open'"]});const I=await this._peer.getStats(),U=Array.from(I.entries()),q=U.filter(J=>J[1].type==="transport")[0][1],G=U.filter(J=>J[0]===q.selectedCandidatePairId);let K,Y;return G.length>0&&(K=G[0][1],Y=U.filter(J=>J[0]===K.remoteCandidateId)[0][1]),{transport:q,selectedCandidatePair:K,remoteCandidate:Y,raw:Object.fromEntries(I)}}async _disconnectStreams(){var I,U,q,G;(G=(q=(U=(I=this._options.stream).unpipe)==null?void 0:U.call(I,this._stream))==null?void 0:q.unpipe)==null||G.call(q,this._options.stream)}},rr._instanceCount=0,rr);_ts_decorate5$1([synchronized],LibDataChannelTransport.prototype,"_close",null);var importESM=Function("path","return import(path)"),uaParser={exports:{}};(function($,I){(function(U,q){var G="1.0.35",K="",Y="?",J="function",X="undefined",Z="object",Q="string",ee="major",te="model",ne="name",ie="type",oe="vendor",ce="version",fe="architecture",se="console",de="mobile",ue="tablet",pe="smarttv",ve="wearable",me="embedded",be=350,_e="Amazon",Se="Apple",xe="ASUS",ke="BlackBerry",De="Browser",Be="Chrome",Ve="Edge",nt="Firefox",ot="Google",ft="Huawei",it="LG",ut="Microsoft",et="Motorola",Ue="Opera",We="Samsung",tt="Sharp",vt="Sony",je="Xiaomi",ze="Zebra",Ae="Facebook",Re="Chromium OS",Ce="Mac OS",ge=function(St,Ut){var le={};for(var re in St)Ut[re]&&Ut[re].length%2===0?le[re]=Ut[re].concat(St[re]):le[re]=St[re];return le},ye=function(St){for(var Ut={},le=0;le<St.length;le++)Ut[St[le].toUpperCase()]=St[le];return Ut},Me=function(St,Ut){return typeof St===Q?Ke(Ut).indexOf(Ke(St))!==-1:!1},Ke=function(St){return St.toLowerCase()},st=function(St){return typeof St===Q?St.replace(/[^\d\.]/g,K).split(".")[0]:q},dt=function(St,Ut){if(typeof St===Q)return St=St.replace(/^\s\s*/,K),typeof Ut===X?St:St.substring(0,be)},$t=function(St,Ut){for(var le=0,re,ae,he,we,Ee,Le;le<Ut.length&&!Ee;){var bt=Ut[le],Lt=Ut[le+1];for(re=ae=0;re<bt.length&&!Ee&&bt[re];)if(Ee=bt[re++].exec(St),Ee)for(he=0;he<Lt.length;he++)Le=Ee[++ae],we=Lt[he],typeof we===Z&&we.length>0?we.length===2?typeof we[1]==J?this[we[0]]=we[1].call(this,Le):this[we[0]]=we[1]:we.length===3?typeof we[1]===J&&!(we[1].exec&&we[1].test)?this[we[0]]=Le?we[1].call(this,Le,we[2]):q:this[we[0]]=Le?Le.replace(we[1],we[2]):q:we.length===4&&(this[we[0]]=Le?we[3].call(this,Le.replace(we[1],we[2])):q):this[we]=Le||q;le+=2}},Et=function(St,Ut){for(var le in Ut)if(typeof Ut[le]===Z&&Ut[le].length>0){for(var re=0;re<Ut[le].length;re++)if(Me(Ut[le][re],St))return le===Y?q:le}else if(Me(Ut[le],St))return le===Y?q:le;return St},rt={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},jt={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Gt={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[ce,[ne,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[ce,[ne,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[ne,ce],[/opios[\/ ]+([\w\.]+)/i],[ce,[ne,Ue+" Mini"]],[/\bopr\/([\w\.]+)/i],[ce,[ne,Ue]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[ne,ce],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[ce,[ne,"UC"+De]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[ce,[ne,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[ce,[ne,"WeChat"]],[/konqueror\/([\w\.]+)/i],[ce,[ne,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[ce,[ne,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[ce,[ne,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[ne,/(.+)/,"$1 Secure "+De],ce],[/\bfocus\/([\w\.]+)/i],[ce,[ne,nt+" Focus"]],[/\bopt\/([\w\.]+)/i],[ce,[ne,Ue+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[ce,[ne,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[ce,[ne,"Dolphin"]],[/coast\/([\w\.]+)/i],[ce,[ne,Ue+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[ce,[ne,"MIUI "+De]],[/fxios\/([-\w\.]+)/i],[ce,[ne,nt]],[/\bqihu|(qi?ho?o?|360)browser/i],[[ne,"360 "+De]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[ne,/(.+)/,"$1 "+De],ce],[/(comodo_dragon)\/([\w\.]+)/i],[[ne,/_/g," "],ce],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[ne,ce],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[ne],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[ne,Ae],ce],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[ne,ce],[/\bgsa\/([\w\.]+) .*safari\//i],[ce,[ne,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[ce,[ne,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[ce,[ne,Be+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[ne,Be+" WebView"],ce],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[ce,[ne,"Android "+De]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[ne,ce],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[ce,[ne,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[ce,ne],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[ne,[ce,Et,rt]],[/(webkit|khtml)\/([\w\.]+)/i],[ne,ce],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[ne,"Netscape"],ce],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[ce,[ne,nt+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[ne,ce],[/(cobalt)\/([\w\.]+)/i],[ne,[ce,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[fe,"amd64"]],[/(ia32(?=;))/i],[[fe,Ke]],[/((?:i[346]|x)86)[;\)]/i],[[fe,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[fe,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[fe,"armhf"]],[/windows (ce|mobile); ppc;/i],[[fe,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[fe,/ower/,K,Ke]],[/(sun4\w)[;\)]/i],[[fe,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[fe,Ke]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[te,[oe,We],[ie,ue]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[te,[oe,We],[ie,de]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[te,[oe,Se],[ie,de]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[te,[oe,Se],[ie,ue]],[/(macintosh);/i],[te,[oe,Se]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[te,[oe,tt],[ie,de]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[te,[oe,ft],[ie,ue]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[te,[oe,ft],[ie,de]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,de]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,ue]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[te,[oe,"OPPO"],[ie,de]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[te,[oe,"Vivo"],[ie,de]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[te,[oe,"Realme"],[ie,de]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[te,[oe,et],[ie,de]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[te,[oe,et],[ie,ue]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[te,[oe,it],[ie,ue]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[te,[oe,it],[ie,de]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[te,[oe,"Lenovo"],[ie,ue]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[te,/_/g," "],[oe,"Nokia"],[ie,de]],[/(pixel c)\b/i],[te,[oe,ot],[ie,ue]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[te,[oe,ot],[ie,de]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[te,[oe,vt],[ie,de]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[te,"Xperia Tablet"],[oe,vt],[ie,ue]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[te,[oe,"OnePlus"],[ie,de]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[te,[oe,_e],[ie,ue]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[te,/(.+)/g,"Fire Phone $1"],[oe,_e],[ie,de]],[/(playbook);[-\w\),; ]+(rim)/i],[te,oe,[ie,ue]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[te,[oe,ke],[ie,de]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[te,[oe,xe],[ie,ue]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[te,[oe,xe],[ie,de]],[/(nexus 9)/i],[te,[oe,"HTC"],[ie,ue]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[oe,[te,/_/g," "],[ie,de]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[te,[oe,"Acer"],[ie,ue]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[te,[oe,"Meizu"],[ie,de]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[oe,te,[ie,de]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[oe,te,[ie,ue]],[/(surface duo)/i],[te,[oe,ut],[ie,ue]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[te,[oe,"Fairphone"],[ie,de]],[/(u304aa)/i],[te,[oe,"AT&T"],[ie,de]],[/\bsie-(\w*)/i],[te,[oe,"Siemens"],[ie,de]],[/\b(rct\w+) b/i],[te,[oe,"RCA"],[ie,ue]],[/\b(venue[\d ]{2,7}) b/i],[te,[oe,"Dell"],[ie,ue]],[/\b(q(?:mv|ta)\w+) b/i],[te,[oe,"Verizon"],[ie,ue]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[te,[oe,"Barnes & Noble"],[ie,ue]],[/\b(tm\d{3}\w+) b/i],[te,[oe,"NuVision"],[ie,ue]],[/\b(k88) b/i],[te,[oe,"ZTE"],[ie,ue]],[/\b(nx\d{3}j) b/i],[te,[oe,"ZTE"],[ie,de]],[/\b(gen\d{3}) b.+49h/i],[te,[oe,"Swiss"],[ie,de]],[/\b(zur\d{3}) b/i],[te,[oe,"Swiss"],[ie,ue]],[/\b((zeki)?tb.*\b) b/i],[te,[oe,"Zeki"],[ie,ue]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[oe,"Dragon Touch"],te,[ie,ue]],[/\b(ns-?\w{0,9}) b/i],[te,[oe,"Insignia"],[ie,ue]],[/\b((nxa|next)-?\w{0,9}) b/i],[te,[oe,"NextBook"],[ie,ue]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[oe,"Voice"],te,[ie,de]],[/\b(lvtel\-)?(v1[12]) b/i],[[oe,"LvTel"],te,[ie,de]],[/\b(ph-1) /i],[te,[oe,"Essential"],[ie,de]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[te,[oe,"Envizen"],[ie,ue]],[/\b(trio[-\w\. ]+) b/i],[te,[oe,"MachSpeed"],[ie,ue]],[/\btu_(1491) b/i],[te,[oe,"Rotor"],[ie,ue]],[/(shield[\w ]+) b/i],[te,[oe,"Nvidia"],[ie,ue]],[/(sprint) (\w+)/i],[oe,te,[ie,de]],[/(kin\.[onetw]{3})/i],[[te,/\./g," "],[oe,ut],[ie,de]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[te,[oe,ze],[ie,ue]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[te,[oe,ze],[ie,de]],[/smart-tv.+(samsung)/i],[oe,[ie,pe]],[/hbbtv.+maple;(\d+)/i],[[te,/^/,"SmartTV"],[oe,We],[ie,pe]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[oe,it],[ie,pe]],[/(apple) ?tv/i],[oe,[te,Se+" TV"],[ie,pe]],[/crkey/i],[[te,Be+"cast"],[oe,ot],[ie,pe]],[/droid.+aft(\w)( bui|\))/i],[te,[oe,_e],[ie,pe]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[te,[oe,tt],[ie,pe]],[/(bravia[\w ]+)( bui|\))/i],[te,[oe,vt],[ie,pe]],[/(mitv-\w{5}) bui/i],[te,[oe,je],[ie,pe]],[/Hbbtv.*(technisat) (.*);/i],[oe,te,[ie,pe]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[oe,dt],[te,dt],[ie,pe]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[ie,pe]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[oe,te,[ie,se]],[/droid.+; (shield) bui/i],[te,[oe,"Nvidia"],[ie,se]],[/(playstation [345portablevi]+)/i],[te,[oe,vt],[ie,se]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[te,[oe,ut],[ie,se]],[/((pebble))app/i],[oe,te,[ie,ve]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[te,[oe,Se],[ie,ve]],[/droid.+; (glass) \d/i],[te,[oe,ot],[ie,ve]],[/droid.+; (wt63?0{2,3})\)/i],[te,[oe,ze],[ie,ve]],[/(quest( 2| pro)?)/i],[te,[oe,Ae],[ie,ve]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[oe,[ie,me]],[/(aeobc)\b/i],[te,[oe,_e],[ie,me]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[te,[ie,de]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[te,[ie,ue]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[ie,ue]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[ie,de]],[/(android[-\w\. ]{0,9});.+buil/i],[te,[oe,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[ce,[ne,Ve+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[ce,[ne,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[ne,ce],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[ce,ne]],os:[[/microsoft (windows) (vista|xp)/i],[ne,ce],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[ne,[ce,Et,jt]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[ne,"Windows"],[ce,Et,jt]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[ce,/_/g,"."],[ne,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[ne,Ce],[ce,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[ce,ne],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[ne,ce],[/\(bb(10);/i],[ce,[ne,ke]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[ce,[ne,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[ce,[ne,nt+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[ce,[ne,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[ce,[ne,"watchOS"]],[/crkey\/([\d\.]+)/i],[ce,[ne,Be+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[ne,Re],ce],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[ne,ce],[/(sunos) ?([\w\.\d]*)/i],[[ne,"Solaris"],ce],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[ne,ce]]},At=function(St,Ut){if(typeof St===Z&&(Ut=St,St=q),!(this instanceof At))return new At(St,Ut).getResult();var le=typeof U!==X&&U.navigator?U.navigator:q,re=St||(le&&le.userAgent?le.userAgent:K),ae=le&&le.userAgentData?le.userAgentData:q,he=Ut?ge(Gt,Ut):Gt,we=le&&le.userAgent==re;return this.getBrowser=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.browser),Ee[ee]=st(Ee[ce]),we&&le&&le.brave&&typeof le.brave.isBrave==J&&(Ee[ne]="Brave"),Ee},this.getCPU=function(){var Ee={};return Ee[fe]=q,$t.call(Ee,re,he.cpu),Ee},this.getDevice=function(){var Ee={};return Ee[oe]=q,Ee[te]=q,Ee[ie]=q,$t.call(Ee,re,he.device),we&&!Ee[ie]&&ae&&ae.mobile&&(Ee[ie]=de),we&&Ee[te]=="Macintosh"&&le&&typeof le.standalone!==X&&le.maxTouchPoints&&le.maxTouchPoints>2&&(Ee[te]="iPad",Ee[ie]=ue),Ee},this.getEngine=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.engine),Ee},this.getOS=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.os),we&&!Ee[ne]&&ae&&ae.platform!="Unknown"&&(Ee[ne]=ae.platform.replace(/chrome os/i,Re).replace(/macos/i,Ce)),Ee},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return re},this.setUA=function(Ee){return re=typeof Ee===Q&&Ee.length>be?dt(Ee,be):Ee,this},this.setUA(re),this};At.VERSION=G,At.BROWSER=ye([ne,ce,ee]),At.CPU=ye([fe]),At.DEVICE=ye([te,oe,ie,se,de,pe,ue,ve,me]),At.ENGINE=At.OS=ye([ne,ce]),$.exports&&(I=$.exports=At),I.UAParser=At;var zt=typeof U!==X&&(U.jQuery||U.Zepto);if(zt&&!zt.ua){var nn=new At;zt.ua=nn.getResult(),zt.ua.get=function(){return nn.getUA()},zt.ua.set=function(St){nn.setUA(St);var Ut=nn.getResult();for(var le in Ut)zt.ua[le]=Ut[le]}}})(typeof window=="object"?window:commonjsGlobal)})(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,__dxlog_file$2="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/iframe.ts",browser,os$1;if(typeof navigator<"u"){const $=new uaParserExports.UAParser(navigator.userAgent);browser=$.getBrowser().name,os$1=$.getOS().name}var sendToIFrame=($,I,U)=>{if(!$.contentWindow){log$2("IFrame content window missing",{origin:I},{F:__dxlog_file$2,L:24,S:void 0,C:(q,G)=>q(...G)});return}browser==="Chrome"&&os$1==="iOS"?$.contentWindow.postMessage(U,I):$.contentWindow.postMessage(U,I,[U.payload])},sendToParentWindow=($,I)=>{browser==="Chrome"&&os$1==="iOS"?window.parent.postMessage(I,$):window.parent.postMessage(I,$,[I.payload])},createIFramePort=({channel:$,iframe:I,origin:U,onOrigin:q})=>({send:async G=>{if(!U){log$2("no origin set",{channel:$},{F:__dxlog_file$2,L:62,S:void 0,C:(J,X)=>J(...X)});return}log$2("sending",{channel:$,data:G.length},{F:__dxlog_file$2,L:66,S:void 0,C:(J,X)=>J(...X)});const K=G.buffer.slice(G.byteOffset,G.byteOffset+G.byteLength),Y={channel:$,payload:K};I?sendToIFrame(I,U,Y):sendToParentWindow(U,Y)},subscribe:G=>{const K=Y=>{if(!I&&Y.source!==window.parent)return;if(I&&Y.source!==I.contentWindow)return;const X=Y.data&&typeof Y.data=="object"&&"channel"in Y.data&&"payload"in Y.data?Y.data:void 0;(X==null?void 0:X.channel)===$&&(U||(U=Y.origin,q==null||q(U)),log$2("received",X,{F:__dxlog_file$2,L:98,S:void 0,C:(Z,Q)=>Z(...Q)}),G(new Uint8Array(X.payload)))};return window.addEventListener("message",K),()=>window.removeEventListener("message",K)}}),createIFrame=($,I,{hidden:U=!0,allow:q}={})=>{const G=()=>{const K=document.createElement("iframe");return K.id=I,K.src=$,U&&K.setAttribute("style","display: none;"),q&&K.setAttribute("allow",q),document.body.appendChild(K),K};return document.getElementById(I)??G()},__dxlog_file2="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/worker.ts",createWorkerPort=({port:$,channel:I,subscribe:U})=>({send:async q=>{const G=q.buffer.slice(q.byteOffset,q.byteOffset+q.byteLength);$.postMessage({channel:I,payload:G},[G])},subscribe:U??(q=>{const G=K=>{const Y=K.data;I&&Y.channel!==I||(log$2.debug("Recieved message",Y,{F:__dxlog_file2,L:46,S:void 0,C:(J,X)=>J(...X)}),q(new Uint8Array(Y.payload)))};return $.onmessage=G,()=>{$.onmessage=null}})});function _ts_decorate$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$1="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/agent.ts",getUnixSocket=($,I="unix")=>`${I}://`+clientProtocol.getProfilePath(clientProtocol.DX_RUNTIME,$,"agent.sock"),AgentClientServiceProvider=class{constructor($){this._profile=$,this.closed=new Event$1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._client.rpc}async open(){const{WebsocketRpcClient:$}=await Promise.resolve().then(()=>index);this._client=new $({url:getUnixSocket(this._profile,"ws+unix"),requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{}}),await this._client.open()}async close(){var $;try{await(($=this._client)==null?void 0:$.close())}catch(I){log$2.warn("Failed to close",I,{F:__dxlog_file$1,L:69,S:this,C:(U,q)=>U(...q)})}}};AgentClientServiceProvider=_ts_decorate$1([trace.resource({annotation:clientServices.ClientServicesProviderResource})],AgentClientServiceProvider);function _ts_decorate2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var LocalClientServices=class{constructor($){this.closed=new Event$1,this._ctx=new Context,this.signalMetadataTags={runtime:"local-client-services"},this._isOpen=!1,this._params=$,typeof window>"u"?this.signalMetadataTags.origin="undefined":globalThis.__args?(this.signalMetadataTags.runtime="native",this.signalMetadataTags.origin=window.location.origin):this.signalMetadataTags.origin=window.location.origin}get descriptors(){return clientProtocol.clientServiceBundle}get services(){var $;return(($=this._host)==null?void 0:$.services)??{}}get host(){return this._host}async open(){if(this._isOpen)return;const{ClientServicesHost:$}=await import("@dxos/client-services");this._host=new $({...this._params,callbacks:{...this._params.callbacks,onReset:async()=>{var I,U;this.closed.emit(void 0),await((U=(I=this._params.callbacks)==null?void 0:I.onReset)==null?void 0:U.call(I))}}}),await this._host.open(this._ctx),this._isOpen=!0,setIdentityTags({identityService:this._host.services.IdentityService,devicesService:this._host.services.DevicesService,setTag:(I,U)=>{this.signalMetadataTags[I]=U}})}async close(){var $;this._isOpen&&(await(($=this._host)==null?void 0:$.close()),this._isOpen=!1)}};_ts_decorate2([trace.info()],LocalClientServices.prototype,"_isOpen",void 0),_ts_decorate2([synchronized],LocalClientServices.prototype,"open",null),_ts_decorate2([synchronized],LocalClientServices.prototype,"close",null),LocalClientServices=_ts_decorate2([trace.resource({annotation:clientServices.ClientServicesProviderResource})],LocalClientServices);var IFrameManager=class{constructor({source:$,onOpen:I,onMessage:U}){this._source=$,this._onOpen=I,this._onMessage=U,this._messageHandler=this._messageHandler.bind(this)}get source(){return this._source}get iframe(){return this._iframe}async open(){var I;if(this._iframe)return;window.addEventListener("message",this._messageHandler);const $=`__DXOS_CLIENT_${PublicKey.random().toHex()}__`;this._iframe=createIFrame(this._source.toString(),$,{allow:"clipboard-read; clipboard-write"}),await((I=this._onOpen)==null?void 0:I.call(this))}async close(){var $;window.removeEventListener("message",this._messageHandler),($=this._iframe)==null||$.remove(),this._iframe=void 0}async _messageHandler($){var I;(I=this._onMessage)==null||I.call(this,$)}},__dxlog_file3="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/shell-manager.ts",shellStyles=Object.entries({display:"none",position:"fixed",top:0,left:0,width:"100vw",height:"100vh",border:0,"z-index":60}).reduce(($,[I,U])=>`${$}${I}: ${U};`,""),ShellManager=class{constructor($,I=clientProtocol.DEFAULT_SHELL_CHANNEL){this._iframeManager=$,this._channel=I,this.contextUpdate=new Event$1,this._display=ShellDisplay.NONE}get display(){return this._display}async setLayout($){var I;log$2("set layout",$,{F:__dxlog_file3,L:50,S:this,C:(U,q)=>U(...q)}),this._display=ShellDisplay.FULLSCREEN,this.contextUpdate.emit({display:this._display}),await((I=this._shellRpc)==null?void 0:I.rpc.ShellService.setLayout($))}async open(){if(this._shellRpc)return;await this._iframeManager.open();const $=this._iframeManager.iframe;$.setAttribute("style",shellStyles),$.setAttribute("name","dxos-shell"),$.setAttribute("data-testid","dxos-shell"),this.contextUpdate.on(({display:q,reload:G})=>{G&&window.location.reload(),$.style.display=q===ShellDisplay.NONE?"none":"",q===ShellDisplay.NONE&&$.blur()});const I=this._iframeManager.source.origin==="null"?this._iframeManager.source.toString().split("/").slice(0,3).join("/"):this._iframeManager.source.origin,U=createIFramePort({origin:I,channel:this._channel,iframe:this._iframeManager.iframe});this._shellRpc=createProtoRpcPeer({requested:clientProtocol.shellServiceBundle,exposed:clientProtocol.appServiceBundle,handlers:{AppService:{setContext:async q=>{log$2("set context",q,{F:__dxlog_file3,L:97,S:this,C:(G,K)=>G(...K)}),q.display&&(this._display=q.display),this.contextUpdate.emit(q)}}},port:U}),await this._shellRpc.open()}async close(){var $;this._shellRpc&&(await(($=this._shellRpc)==null?void 0:$.close()),this._shellRpc=void 0)}};function _ts_decorate3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var IFrameClientServicesHost=class{constructor({host:$,source:I=clientProtocol.DEFAULT_VAULT_URL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT}){this.closed=new Event$1,this._host=$,this._source=I,this._vault=U,this._timeout=q;const G=new Trigger;this._iframeManager=new IFrameManager({source:new URL(this._source,window.location.origin),onOpen:async()=>{var K,Y,J;await asyncTimeout(G.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(J=(Y=(K=this._iframeManager)==null?void 0:K.iframe)==null?void 0:Y.contentWindow)==null||J.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin)},onMessage:K=>{var X,Z,Q;const{channel:Y,payload:J}=K.data;if(Y===this._vault){if(J==="loaded")G.wake();else if(J==="client"){const ee=new MessageChannel,te=createBundledRpcServer({services:this._host.descriptors,handlers:this._host.services,port:createWorkerPort({port:ee.port1})});(Q=(Z=(X=this._iframeManager)==null?void 0:X.iframe)==null?void 0:Z.contentWindow)==null||Q.postMessage({channel:this._vault,payload:{command:"port",port:ee.port2}},this._iframeManager.source.origin,[ee.port2]),te.open()}}}}),this._shellManager=new ShellManager(this._iframeManager)}get descriptors(){return this._host.descriptors}get services(){return this._host.services}async open(){await this._host.open(new Context),await this._shellManager.open()}async close(){await this._shellManager.close(),await this._iframeManager.close(),await this._host.close(new Context)}};IFrameClientServicesHost=_ts_decorate3([trace.resource()],IFrameClientServicesHost);function _ts_decorate4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/service-proxy.ts",ClientServicesProxy=class{constructor($,I=3e4){this._port=$,this._timeout=I,this.closed=new Event$1}get proxy(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file4,L:30,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file4,L:39,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy.rpc}async open(){this._proxy||(this._proxy=createProtoRpcPeer({requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{},port:this._port}),await asyncTimeout(this._proxy.open(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Failed to establish dxrpc connection",{timeout:this._timeout})))}async close(){this._proxy&&(await this._proxy.close(),this._proxy=void 0)}};ClientServicesProxy=_ts_decorate4([trace.resource({annotation:clientServices.ClientServicesProviderResource})],ClientServicesProxy);function _ts_decorate5($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/iframe-service-proxy.ts",IFrameClientServicesProxy=class{constructor({source:$=clientProtocol.DEFAULT_VAULT_URL,shell:I=clientProtocol.DEFAULT_SHELL_CHANNEL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT,logFilter:G="error,warn"}={}){this.closed=new Event$1,this._instanceId=PublicKey.random().toHex(),this._source=$,this._shell=I,this._vault=U,this._logFilter=parseFilter(G),this._timeout=q;const K=new Trigger,Y=new Trigger;this._iframeManager=new IFrameManager({source:new URL(typeof this._shell=="string"?this._source:`${this._source}#disableshell`,window.location.origin),onOpen:async()=>{var X,Z;await asyncTimeout(K.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(Z=(X=this._iframeManager.iframe)==null?void 0:X.contentWindow)==null||Z.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin);const J=await asyncTimeout(Y.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to provide MessagePort"));this._appPort=createWorkerPort({port:J})},onMessage:async J=>{const{channel:X,payload:Z}=J.data;X===this._vault&&(Z==="loaded"?K.wake():(Z==null?void 0:Z.command)==="init"&&Y.wake(Z.port))}}),typeof this._shell=="string"&&(this._shellManager=new ShellManager(this._iframeManager))}get proxy(){return this._clientServicesProxy.proxy}get descriptors(){return this._clientServicesProxy.descriptors}get services(){return this._clientServicesProxy.services}async open(){var $;this._clientServicesProxy||(log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file5,L:141,S:this,C:(I,U)=>I(...U)}),await this._iframeManager.open(),this._clientServicesProxy=new ClientServicesProxy(this._appPort),await this._clientServicesProxy.open(),this._loggingStream=this._clientServicesProxy.services.LoggingService.queryLogs({filters:this._logFilter}),this._loggingStream.subscribe(I=>{switch(I.level){case LogLevel.DEBUG:log$2.debug(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:153,S:this,C:(U,q)=>U(...q)});break;case LogLevel.INFO:log$2.info(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:156,S:this,C:(U,q)=>U(...q)});break;case LogLevel.WARN:log$2.warn(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:159,S:this,C:(U,q)=>U(...q)});break;case LogLevel.ERROR:log$2.error(`[vault] ${I.message}`,I.context,{F:__dxlog_file5,L:162,S:this,C:(U,q)=>U(...q)});break}}),await(($=this._shellManager)==null?void 0:$.open()))}async close(){var $,I,U;await(($=this._shellManager)==null?void 0:$.close()),await this._iframeManager.close(),await((I=this._loggingStream)==null?void 0:I.close()),await((U=this._clientServicesProxy)==null?void 0:U.close()),this._clientServicesProxy=void 0,log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file5,L:176,S:this,C:(q,G)=>q(...G)})}};IFrameClientServicesProxy=_ts_decorate5([trace.resource()],IFrameClientServicesProxy);function _ts_decorate6($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file7="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/worker-client-services.ts",WorkerClientServices=class{constructor({config:$,createWorker:I,logFilter:U="error,warn",observabilityGroup:q,signalTelemetryEnabled:G}){this.closed=new Event$1,this.joinedSpace=new Event$1,this._isOpen=!1,this._config=$,this._createWorker=I,this._logFilter=parseFilter(U),this._observabilityGroup=q,this._signalTelemetryEnabled=G??!1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._services.services}get runtime(){return this._runtime}async open(){if(this._isOpen)return;log$2("opening...",void 0,{F:__dxlog_file7,L:87,S:this,C:(K,Y)=>K(...Y)});const{SharedWorkerConnection:$}=await import("@dxos/client-services"),I=new Trigger,U=this._createWorker();U.port.postMessage({dxlog:localStorage.getItem("dxlog")}),U.port.onmessage=K=>{const{command:Y,payload:J}=K.data;Y==="init"&&I.wake(J)};const{systemPort:q,appPort:G}=await I.wait();this._runtime=new $({config:this._config,systemPort:createWorkerPort({port:q})}),await this._runtime.open({origin:location.origin,observabilityGroup:this._observabilityGroup,signalTelemetryEnabled:this._signalTelemetryEnabled}),this._services=new ClientServicesProxy(createWorkerPort({port:G})),await this._services.open(),navigator.locks.request(LOCK_KEY,()=>{log$2("terminated",void 0,{F:__dxlog_file7,L:114,S:this,C:(K,Y)=>K(...Y)}),this._isOpen&&this.closed.emit(new Error("Shared worker terminated."))}),this._loggingStream=this._services.services.LoggingService.queryLogs({filters:this._logFilter}),this._loggingStream.subscribe(K=>{switch(K.level){case LogLevel.DEBUG:log$2.debug(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.INFO:log$2.info(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.WARN:log$2.warn(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.ERROR:log$2.error(K.message,K.context,mapLogMeta(K.meta));break}}),log$2("opened",void 0,{F:__dxlog_file7,L:140,S:this,C:(K,Y)=>K(...Y)}),this._isOpen=!0}async close(){var $;this._isOpen&&(log$2("closing...",void 0,{F:__dxlog_file7,L:150,S:this,C:(I,U)=>I(...U)}),await(($=this._loggingStream)==null?void 0:$.close()),await this._runtime.close(),await this._services.close(),log$2("closed",void 0,{F:__dxlog_file7,L:155,S:this,C:(I,U)=>I(...U)}),this._isOpen=!1)}};_ts_decorate6([trace.info()],WorkerClientServices.prototype,"_isOpen",void 0),_ts_decorate6([synchronized],WorkerClientServices.prototype,"open",null),_ts_decorate6([synchronized],WorkerClientServices.prototype,"close",null),WorkerClientServices=_ts_decorate6([trace.resource()],WorkerClientServices);var mapLogMeta=$=>$&&{F:$.file,L:$.line,S:$.scope},i$1=Symbol.for("preact-signals");function t(){if(s$1>1)s$1--;else{for(var $,I=!1;h$1!==void 0;){var U=h$1;for(h$1=void 0,f++;U!==void 0;){var q=U.o;if(U.o=void 0,U.f&=-3,!(8&U.f)&&c(U))try{U.c()}catch(G){I||($=G,I=!0)}U=q}}if(f=0,s$1--,I)throw $}}var o=void 0,h$1=void 0,s$1=0,f=0,v$1=0;function e($){if(o!==void 0){var I=$.n;if(I===void 0||I.t!==o)return I={i:0,S:$,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:I},o.s!==void 0&&(o.s.n=I),o.s=I,$.n=I,32&o.f&&$.S(I),I;if(I.i===-1)return I.i=0,I.n!==void 0&&(I.n.p=I.p,I.p!==void 0&&(I.p.n=I.n),I.p=o.s,I.n=void 0,o.s.n=I,o.s=I),I}}function u($){this.v=$,this.i=0,this.n=void 0,this.t=void 0}u.prototype.brand=i$1,u.prototype.h=function(){return!0},u.prototype.S=function($){this.t!==$&&$.e===void 0&&($.x=this.t,this.t!==void 0&&(this.t.e=$),this.t=$)},u.prototype.U=function($){if(this.t!==void 0){var I=$.e,U=$.x;I!==void 0&&(I.x=U,$.e=void 0),U!==void 0&&(U.e=I,$.x=void 0),$===this.t&&(this.t=U)}},u.prototype.subscribe=function($){var I=this;return E(function(){var U=I.value,q=o;o=void 0;try{$(U)}finally{o=q}})},u.prototype.valueOf=function(){return this.value},u.prototype.toString=function(){return this.value+""},u.prototype.toJSON=function(){return this.value},u.prototype.peek=function(){var $=o;o=void 0;try{return this.value}finally{o=$}},Object.defineProperty(u.prototype,"value",{get:function(){var $=e(this);return $!==void 0&&($.i=this.i),this.v},set:function($){if($!==this.v){if(f>100)throw new Error("Cycle detected");this.v=$,this.i++,v$1++,s$1++;try{for(var I=this.t;I!==void 0;I=I.x)I.t.N()}finally{t()}}}});function c($){for(var I=$.s;I!==void 0;I=I.n)if(I.S.i!==I.i||!I.S.h()||I.S.i!==I.i)return!0;return!1}function a($){for(var I=$.s;I!==void 0;I=I.n){var U=I.S.n;if(U!==void 0&&(I.r=U),I.S.n=I,I.i=-1,I.n===void 0){$.s=I;break}}}function l($){for(var I=$.s,U=void 0;I!==void 0;){var q=I.p;I.i===-1?(I.S.U(I),q!==void 0&&(q.n=I.n),I.n!==void 0&&(I.n.p=q)):U=I,I.S.n=I.r,I.r!==void 0&&(I.r=void 0),I=q}$.s=U}function y($){u.call(this,void 0),this.x=$,this.s=void 0,this.g=v$1-1,this.f=4}(y.prototype=new u).h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===v$1))return!0;if(this.g=v$1,this.f|=1,this.i>0&&!c(this))return this.f&=-2,!0;var $=o;try{a(this),o=this;var I=this.x();(16&this.f||this.v!==I||this.i===0)&&(this.v=I,this.f&=-17,this.i++)}catch(U){this.v=U,this.f|=16,this.i++}return o=$,l(this),this.f&=-2,!0},y.prototype.S=function($){if(this.t===void 0){this.f|=36;for(var I=this.s;I!==void 0;I=I.n)I.S.S(I)}u.prototype.S.call(this,$)},y.prototype.U=function($){if(this.t!==void 0&&(u.prototype.U.call(this,$),this.t===void 0)){this.f&=-33;for(var I=this.s;I!==void 0;I=I.n)I.S.U(I)}},y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var $=this.t;$!==void 0;$=$.x)$.t.N()}},Object.defineProperty(y.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var $=e(this);if(this.h(),$!==void 0&&($.i=this.i),16&this.f)throw this.v;return this.v}});function _($){var I=$.u;if($.u=void 0,typeof I=="function"){s$1++;var U=o;o=void 0;try{I()}catch(q){throw $.f&=-2,$.f|=8,g($),q}finally{o=U,t()}}}function g($){for(var I=$.s;I!==void 0;I=I.n)I.S.U(I);$.x=void 0,$.s=void 0,_($)}function p$1($){if(o!==this)throw new Error("Out-of-order effect");l(this),o=$,this.f&=-2,8&this.f&&g(this),t()}function b$1($){this.x=$,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32}b$1.prototype.c=function(){var $=this.S();try{if(8&this.f||this.x===void 0)return;var I=this.x();typeof I=="function"&&(this.u=I)}finally{$()}},b$1.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,_(this),a(this),s$1++;var $=o;return o=this,p$1.bind(this,$)},b$1.prototype.N=function(){2&this.f||(this.f|=2,this.o=h$1,h$1=this)},b$1.prototype.d=function(){this.f|=8,1&this.f||g(this)};function E($){var I=new b$1($);try{I.c()}catch(U){throw I.d(),U}return I.d.bind(I)}var shim={exports:{}},useSyncExternalStoreShim_production_min={};/**
|
|
922
|
+
${X.getStack()}`,Y(Q)):Y()};return this._outgoingRequests.set(q,new PendingRpcRequest(J,Z,!0)),this._sendMessage({request:{id:q,method:$,payload:I,stream:!0}}).catch(Q=>{Y(Q)}),()=>{this._sendMessage({streamClose:{id:q}}).catch(Q=>{log$2.catch(Q,void 0,{F:__dxlog_file$5,L:465,S:this,C:(ee,te)=>ee(...te)})})}})}async _sendMessage($,I){log$2("sending message",{type:Object.keys($)[0]},{F:__dxlog_file$5,L:472,S:this,C:(U,q)=>U(...q)}),await this._params.port.send(RpcMessage.encode($,{preserveAny:!0}),I)}async _callHandler($){try{invariant(typeof $.id=="number",void 0,{F:__dxlog_file$5,L:478,S:this,A:["typeof req.id === 'number'",""]}),invariant($.payload,void 0,{F:__dxlog_file$5,L:479,S:this,A:["req.payload",""]}),invariant($.method,void 0,{F:__dxlog_file$5,L:480,S:this,A:["req.method",""]});const I=await this._params.callHandler($.method,$.payload);return{id:$.id,payload:I}}catch(I){return{id:$.id,error:protocols.encodeError(I)}}}_callStreamHandler($,I){try{invariant(this._params.streamHandler,"Requests with streaming responses are not supported.",{F:__dxlog_file$5,L:497,S:this,A:["this._params.streamHandler","'Requests with streaming responses are not supported.'"]}),invariant(typeof $.id=="number",void 0,{F:__dxlog_file$5,L:498,S:this,A:["typeof req.id === 'number'",""]}),invariant($.payload,void 0,{F:__dxlog_file$5,L:499,S:this,A:["req.payload",""]}),invariant($.method,void 0,{F:__dxlog_file$5,L:500,S:this,A:["req.method",""]});const U=this._params.streamHandler($.method,$.payload);U.onReady(()=>{I({id:$.id,streamReady:!0})}),U.subscribe(q=>{I({id:$.id,payload:q})},q=>{I(q?{id:$.id,error:protocols.encodeError(q)}:{id:$.id,close:!0})}),this._localStreams.set($.id,U)}catch(U){I({id:$.id,error:protocols.encodeError(U)})}}};_ts_decorate$5([synchronized],RpcPeer.prototype,"open",null);var throwIfNotOpen=$=>{switch($){case"OPENED":return;case"INITIAL":throw new protocols.RpcNotOpenError;case"CLOSED":throw new protocols.RpcClosedError}},__dxlog_file2$5="/home/runner/work/dxos/dxos/packages/core/mesh/rpc/src/service.ts",ProtoRpcPeer=class{constructor($,I){this.rpc=$,this._peer=I}async open(){await this._peer.open()}async close(){await this._peer.close()}async abort(){await this._peer.abort()}},createProtoRpcPeer=({requested:$,exposed:I,handlers:U,encodingOptions:q,...G})=>{const K={};if(I){invariant(U,void 0,{F:__dxlog_file2$5,L:93,S:void 0,A:["handlers",""]});for(const X of Object.keys(I)){const Z=I[X].serviceProto.fullName.slice(1),Q=U[X];K[Z]=I[X].createServer(Q,q)}}const Y=new RpcPeer({...G,callHandler:(X,Z)=>{const[Q,ee]=parseMethodName(X);if(!K[Q])throw new Error(`Service not supported: ${Q}`);return K[Q].call(ee,Z)},streamHandler:(X,Z)=>{const[Q,ee]=parseMethodName(X);if(!K[Q])throw new Error(`Service not supported: ${Q}`);return K[Q].callStream(ee,Z)}}),J={};if($)for(const X of Object.keys($)){const Z=$[X].serviceProto.fullName.slice(1);J[X]=$[X].createClient({call:(Q,ee,te)=>Y.call(`${Z}.${Q}`,ee,te),callStream:(Q,ee,te)=>Y.callStream(`${Z}.${Q}`,ee,te)},q)}return new ProtoRpcPeer(J,Y)},parseMethodName=$=>{const I=$.lastIndexOf("."),U=$.slice(0,I),q=$.slice(I+1);if(U.length===0||q.length===0)throw new Error(`Invalid method: ${$}`);return[U,q]},createBundledRpcServer=({services:$,handlers:I,...U})=>{const q={};for(const G of Object.keys($)){const K=$[G].serviceProto.fullName.slice(1);q[K]=$[G].createServer(I[G])}return new RpcPeer({...U,callHandler:(G,K)=>{const[Y,J]=parseMethodName(G);if(!q[Y])throw new Error(`Service not supported: ${Y}`);return q[Y].call(J,K)},streamHandler:(G,K)=>{const[Y,J]=parseMethodName(G);if(!q[Y])throw new Error(`Service not supported: ${Y}`);return q[Y].callStream(J,K)}})};protocols.schema.getCodecForType("dxos.mesh.messaging.ReliablePayload"),protocols.schema.getCodecForType("dxos.mesh.messaging.Acknowledgement");var __dxlog_file2$4="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-rpc-client.ts",SIGNAL_KEEPALIVE_INTERVAL=1e4,SignalRPCClient=class{constructor({url:$,callbacks:I={}}){this._connectTrigger=new Trigger,this._closed=!1,this._closeComplete=new Trigger;const U=PublicKey.random().toHex();log$2.trace("dxos.mesh.signal-rpc-client.constructor",protocols.trace.begin({id:U}),{F:__dxlog_file2$4,L:55,S:this,C:(q,G)=>q(...G)}),this._url=$,this._callbacks=I,this._socket=new WebSocket3(this._url),this._rpc=createProtoRpcPeer({requested:{Signal:protocols.schema.getService("dxos.mesh.signal.Signal")},noHandshake:!0,port:{send:q=>{if(!this._closed)try{this._socket.send(q)}catch(G){log$2.warn("send error",G,{F:__dxlog_file2$4,L:74,S:this,C:(K,Y)=>K(...Y)})}},subscribe:q=>{this._socket.onmessage=async G=>{typeof Blob<"u"&&G.data instanceof Blob?q(export_Buffer.from(await G.data.arrayBuffer())):q(G.data)}}},encodingOptions:{preserveAny:!0}}),this._socket.onopen=async()=>{var q,G,K,Y;try{await this._rpc.open(),log$2(`RPC open ${this._url}`,void 0,{F:__dxlog_file2$4,L:95,S:this,C:(J,X)=>J(...X)}),(G=(q=this._callbacks).onConnected)==null||G.call(q),this._connectTrigger.wake(),this._keepaliveCtx=new Context,scheduleTaskInterval(this._keepaliveCtx,async()=>{var J;(J=this._socket)==null||J.send("__ping__")},SIGNAL_KEEPALIVE_INTERVAL)}catch(J){(Y=(K=this._callbacks).onError)==null||Y.call(K,J)}},this._socket.onclose=async()=>{var q,G;log$2(`Disconnected ${this._url}`,void 0,{F:__dxlog_file2$4,L:116,S:this,C:(K,Y)=>K(...Y)}),(G=(q=this._callbacks).onDisconnected)==null||G.call(q),this._closeComplete.wake(),await this.close()},this._socket.onerror=async q=>{var G,K,Y;if(!this._closed){(K=(G=this._callbacks).onError)==null||K.call(G,q.error??new Error(q.message)),this._connectTrigger.reset();try{await((Y=this._rpc)==null?void 0:Y.close())}catch(J){log$2.catch(J,void 0,{F:__dxlog_file2$4,L:134,S:this,C:(X,Z)=>X(...Z)})}this._closed=!0,log$2.warn(q.message??"Socket error",{url:this._url},{F:__dxlog_file2$4,L:138,S:this,C:(J,X)=>J(...X)})}},log$2.trace("dxos.mesh.signal-rpc-client.constructor",protocols.trace.end({id:U}),{F:__dxlog_file2$4,L:141,S:this,C:(q,G)=>q(...G)})}async close(){var $,I,U,q;await(($=this._keepaliveCtx)==null?void 0:$.dispose()),this._closed=!0;try{await((I=this._rpc)==null?void 0:I.close()),(((U=this._socket)==null?void 0:U.readyState)===WebSocket3.OPEN||((q=this._socket)==null?void 0:q.readyState)===WebSocket3.CONNECTING)&&this._socket.close(),await this._closeComplete.wait({timeout:1e3})}catch(G){log$2.warn("close error",G,{F:__dxlog_file2$4,L:156,S:this,C:(K,Y)=>K(...Y)})}}async join({topic:$,peerId:I}){var q,G;log$2("join",{topic:$,peerId:I},{F:__dxlog_file2$4,L:161,S:this,C:(K,Y)=>K(...Y)}),await this._connectTrigger.wait(),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$4,L:163,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$4,L:164,S:this,A:["this._rpc","'Rpc is not initialized'"]});const U=this._rpc.rpc.Signal.join({swarm:$.asUint8Array(),peer:I.asUint8Array(),metadata:(G=(q=this._callbacks)==null?void 0:q.getMetadata)==null?void 0:G.call(q)});return await U.waitUntilReady(),U}async receiveMessages($){log$2("receiveMessages",{peerId:$},{F:__dxlog_file2$4,L:175,S:this,C:(U,q)=>U(...q)}),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$4,L:176,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),await this._connectTrigger.wait(),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$4,L:178,S:this,A:["this._rpc","'Rpc is not initialized'"]});const I=this._rpc.rpc.Signal.receiveMessages({peer:$.asUint8Array()});return await I.waitUntilReady(),I}async sendMessage({author:$,recipient:I,payload:U}){var q,G;log$2("sendMessage",{author:$,recipient:I,payload:U},{F:__dxlog_file2$4,L:187,S:this,C:(K,Y)=>K(...Y)}),invariant(!this._closed,"SignalRPCClient is closed",{F:__dxlog_file2$4,L:188,S:this,A:["!this._closed","'SignalRPCClient is closed'"]}),await this._connectTrigger.wait(),invariant(this._rpc,"Rpc is not initialized",{F:__dxlog_file2$4,L:190,S:this,A:["this._rpc","'Rpc is not initialized'"]}),await this._rpc.rpc.Signal.sendMessage({author:$.asUint8Array(),recipient:I.asUint8Array(),payload:U,metadata:(G=(q=this._callbacks)==null?void 0:q.getMetadata)==null?void 0:G.call(q)})}},__dxlog_file3$2="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-client/signal-client.ts",DEFAULT_RECONNECT_TIMEOUT=100,MAX_RECONNECT_TIMEOUT=5e3,ERROR_RECONCILE_DELAY=1e3,RECONCILE_INTERVAL=5e3,SignalClient=class{constructor($,I,U,q){if(this._host=$,this._onMessage=I,this._onSwarmEvent=U,this._getMetadata=q,this._state=SignalState.CLOSED,this._reconnectAfter=DEFAULT_RECONNECT_TIMEOUT,this._connectionStarted=new Date,this._lastStateChange=new Date,this._clientReady=new Trigger,this.statusChanged=new Event$1,this.commandTrace=new Event$1,this._swarmStreams=new ComplexMap(({topic:G,peerId:K})=>G.toHex()+K.toHex()),this._joinedTopics=new ComplexSet(({topic:G,peerId:K})=>G.toHex()+K.toHex()),this._messageStreams=new ComplexMap(G=>G.toHex()),this._subscribedMessages=new ComplexSet(({peerId:G})=>G.toHex()),this._reconciled=new Event$1,this._instanceId=PublicKey.random().toHex(),this._performance={sentMessages:0,receivedMessages:0,reconnectCounter:0,joinCounter:0,leaveCounter:0},!this._host.startsWith("wss://")&&!this._host.startsWith("ws://"))throw new Error(`Signal server requires a websocket URL. Provided: ${this._host}`)}open(){log$2.trace("dxos.mesh.signal-client.open",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file3$2,L:136,S:this,C:($,I)=>$(...I)}),![SignalState.CONNECTED,SignalState.CONNECTING].includes(this._state)&&(this._ctx=new Context({onError:$=>{var I;this._state===SignalState.CLOSED||(I=this._ctx)!=null&&I.disposed||(this._state===SignalState.CONNECTED&&log$2.warn("SignalClient error:",$,{F:__dxlog_file3$2,L:148,S:this,C:(U,q)=>U(...q)}),this._scheduleReconcileAfterError())}}),this._reconcileTask=new DeferredTask(this._ctx,async()=>{await this._reconcileSwarmSubscriptions(),await this._reconcileMessageSubscriptions(),this._reconciled.emit()}),scheduleTaskInterval(this._ctx,async()=>{this._state===SignalState.CONNECTED&&this._reconcileTask.schedule()},RECONCILE_INTERVAL),this._reconnectTask=new DeferredTask(this._ctx,async()=>{await this._reconnect()}),this._setState(SignalState.CONNECTING),this._createClient(),log$2.trace("dxos.mesh.signal-client.open",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file3$2,L:177,S:this,C:($,I)=>$(...I)}))}async close(){var $,I;log$2("closing...",void 0,{F:__dxlog_file3$2,L:181,S:this,C:(U,q)=>U(...q)}),![SignalState.CLOSED].includes(this._state)&&(await(($=this._ctx)==null?void 0:$.dispose()),this._clientReady.reset(),await((I=this._client)==null?void 0:I.close()),this._client=void 0,this._setState(SignalState.CLOSED),log$2("closed",void 0,{F:__dxlog_file3$2,L:192,S:this,C:(U,q)=>U(...q)}))}getStatus(){var $;return{host:this._host,state:this._state,error:($=this._lastError)==null?void 0:$.message,reconnectIn:this._reconnectAfter,connectionStarted:this._connectionStarted,lastStateChange:this._lastStateChange}}async join({topic:$,peerId:I}){log$2("joining",{topic:$,peerId:I},{F:__dxlog_file3$2,L:207,S:this,C:(U,q)=>U(...q)}),this._performance.joinCounter++,this._joinedTopics.add({topic:$,peerId:I}),this._reconcileTask.schedule()}async leave({topic:$,peerId:I}){var U;this._performance.leaveCounter++,log$2("leaving",{topic:$,peerId:I},{F:__dxlog_file3$2,L:215,S:this,C:(q,G)=>q(...G)}),(U=this._swarmStreams.get({topic:$,peerId:I}))==null||U.close(),this._swarmStreams.delete({topic:$,peerId:I}),this._joinedTopics.delete({topic:$,peerId:I})}async sendMessage($){this._performance.sentMessages++,await this._clientReady.wait(),invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$2,L:224,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]}),await this._client.sendMessage($)}async subscribeMessages($){log$2("subscribing to messages",{peerId:$},{F:__dxlog_file3$2,L:229,S:this,C:(I,U)=>I(...U)}),this._subscribedMessages.add({peerId:$}),this._reconcileTask.schedule()}async unsubscribeMessages($){var I;log$2("unsubscribing from messages",{peerId:$},{F:__dxlog_file3$2,L:235,S:this,C:(U,q)=>U(...q)}),this._subscribedMessages.delete({peerId:$}),(I=this._messageStreams.get($))==null||I.close(),this._messageStreams.delete($)}_scheduleReconcileAfterError(){scheduleTask(this._ctx,()=>{this._reconcileTask.schedule()},ERROR_RECONCILE_DELAY)}_setState($){this._state=$,this._lastStateChange=new Date,log$2("signal state changed",{status:this.getStatus()},{F:__dxlog_file3$2,L:254,S:this,C:(I,U)=>I(...U)}),this.statusChanged.emit(this.getStatus())}_createClient(){log$2("creating client",{host:this._host,state:this._state},{F:__dxlog_file3$2,L:259,S:this,C:($,I)=>$(...I)}),invariant(!this._client,"Client already created",{F:__dxlog_file3$2,L:260,S:this,A:["!this._client","'Client already created'"]}),this._connectionStarted=new Date,this._connectionCtx=this._ctx.derive(),this._connectionCtx.onDispose(async()=>{log$2("connection context disposed",void 0,{F:__dxlog_file3$2,L:267,S:this,C:($,I)=>$(...I)}),await Promise.all(Array.from(this._swarmStreams.values()).map($=>$.close())),await Promise.all(Array.from(this._messageStreams.values()).map($=>$.close())),this._swarmStreams.clear(),this._messageStreams.clear()});try{this._client=new SignalRPCClient({url:this._host,callbacks:{onConnected:()=>{log$2("socket connected",void 0,{F:__dxlog_file3$2,L:279,S:this,C:($,I)=>$(...I)}),this._lastError=void 0,this._reconnectAfter=DEFAULT_RECONNECT_TIMEOUT,this._setState(SignalState.CONNECTED),this._clientReady.wake(),this._reconcileTask.schedule()},onDisconnected:()=>{if(log$2("socket disconnected",{state:this._state},{F:__dxlog_file3$2,L:288,S:this,C:($,I)=>$(...I)}),this._state===SignalState.ERROR){this._setState(SignalState.DISCONNECTED);return}this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._setState(SignalState.DISCONNECTED),this._reconnectTask.schedule()},onError:$=>{log$2("socket error",{error:$,state:this._state},{F:__dxlog_file3$2,L:303,S:this,C:(I,U)=>I(...U)}),this._lastError=$,this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._setState(SignalState.ERROR),this._reconnectTask.schedule()},getMetadata:this._getMetadata}})}catch($){this._state!==SignalState.CONNECTED&&this._state!==SignalState.CONNECTING&&this._incrementReconnectTimeout(),this._lastError=$,this._setState(SignalState.DISCONNECTED),this._reconnectTask.schedule()}}_incrementReconnectTimeout(){this._reconnectAfter*=2,this._reconnectAfter=Math.min(this._reconnectAfter,MAX_RECONNECT_TIMEOUT)}async _reconnect(){var $,I;if(log$2(`reconnecting in ${this._reconnectAfter}ms`,{state:this._state},{F:__dxlog_file3$2,L:331,S:this,C:(U,q)=>U(...q)}),this._performance.reconnectCounter++,this._state===SignalState.RECONNECTING){log$2.warn("Signal api already reconnecting.",void 0,{F:__dxlog_file3$2,L:335,S:this,C:(U,q)=>U(...q)});return}this._state!==SignalState.CLOSED&&(this._clientReady.reset(),await(($=this._connectionCtx)==null?void 0:$.dispose()),(I=this._client)==null||I.close().catch(()=>{}),this._client=void 0,await cancelWithContext(this._ctx,sleep(this._reconnectAfter)),this._setState(SignalState.RECONNECTING),this._createClient())}async _reconcileSwarmSubscriptions(){var I;await asyncTimeout(cancelWithContext(this._connectionCtx,this._clientReady.wait()),5e3);const $=this._client;invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$2,L:360,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]});for(const{topic:U,peerId:q}of this._swarmStreams.keys())this._joinedTopics.has({topic:U,peerId:q})||((I=this._swarmStreams.get({topic:U,peerId:q}))==null||I.close(),this._swarmStreams.delete({topic:U,peerId:q}));for(const{topic:U,peerId:q}of this._joinedTopics.values()){if(this._swarmStreams.has({topic:U,peerId:q}))continue;const G=await asyncTimeout(cancelWithContext(this._connectionCtx,$.join({topic:U,peerId:q})),5e3);G.subscribe(async K=>{log$2("swarm event",{swarmEvent:K},{F:__dxlog_file3$2,L:387,S:this,C:(Y,J)=>Y(...J)}),await this._onSwarmEvent({topic:U,swarmEvent:K})}),this._swarmStreams.set({topic:U,peerId:q},G)}}async _reconcileMessageSubscriptions(){var I;await asyncTimeout(cancelWithContext(this._connectionCtx,this._clientReady.wait()),5e3);const $=this._client;invariant(this._state===SignalState.CONNECTED,"Not connected to Signal Server",{F:__dxlog_file3$2,L:400,S:this,A:["this._state === SignalState.CONNECTED","'Not connected to Signal Server'"]});for(const U of this._messageStreams.keys())this._subscribedMessages.has({peerId:U})||((I=this._messageStreams.get(U))==null||I.close(),this._messageStreams.delete(U));for(const{peerId:U}of this._subscribedMessages.values()){if(this._messageStreams.has(U))continue;const q=await asyncTimeout(cancelWithContext(this._connectionCtx,$.receiveMessages(U)),5e3);q.subscribe(async G=>{this._performance.receivedMessages++,await this._onMessage({author:PublicKey.from(G.author),recipient:PublicKey.from(G.recipient),payload:G.payload})}),this._messageStreams.set(U,q)}}};function _ts_decorate$4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$2="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/websocket-signal-manager.ts",MAX_SERVER_FAILURES=5,WSS_SIGNAL_SERVER_REBOOT_DELAY=3e3,WebsocketSignalManager=class{constructor($,I){this._hosts=$,this._getMetadata=I,this._servers=new Map,this._opened=!1,this.failureCount=new Map,this.statusChanged=new Event$1,this.commandTrace=new Event$1,this.swarmEvent=new Event$1,this.onMessage=new Event$1,this._instanceId=PublicKey.random().toHex(),log$2("Created WebsocketSignalManager",{hosts:this._hosts},{F:__dxlog_file5$2,L:49,S:this,C:(U,q)=>U(...q)});for(const U of this._hosts){if(this._servers.has(U.server))continue;const q=new SignalClient(U.server,async G=>this.onMessage.emit(G),async G=>this.swarmEvent.emit(G),this._getMetadata);q.statusChanged.on(()=>this.statusChanged.emit(this.getStatus())),this._servers.set(U.server,q),this.failureCount.set(U.server,0),q.commandTrace.on(G=>this.commandTrace.emit(G))}}async open(){this._opened||(log$2("open signal manager",{hosts:this._hosts},{F:__dxlog_file5$2,L:73,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.websocket-signal-manager.open",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file5$2,L:74,S:this,C:($,I)=>$(...I)}),this._initContext(),[...this._servers.values()].forEach($=>$.open()),this._opened=!0,log$2.trace("dxos.mesh.websocket-signal-manager.open",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file5$2,L:81,S:this,C:($,I)=>$(...I)}))}async close(){this._opened&&(this._opened=!1,await this._ctx.dispose(),await Promise.all(Array.from(this._servers.values()).map($=>$.close())))}async restartServer($){log$2("Restarting server",{serverName:$},{F:__dxlog_file5$2,L:97,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"server already closed",{F:__dxlog_file5$2,L:98,S:this,A:["this._opened","'server already closed'"]});const I=this._servers.get($);invariant(I,"server not found",{F:__dxlog_file5$2,L:101,S:this,A:["server","'server not found'"]}),await I.close(),await sleep(WSS_SIGNAL_SERVER_REBOOT_DELAY),await I.open()}getStatus(){return Array.from(this._servers.values()).map($=>$.getStatus())}async join({topic:$,peerId:I}){log$2("Join",{topic:$,peerId:I},{F:__dxlog_file5$2,L:114,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:115,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(U=>U.join({topic:$,peerId:I}))}async leave({topic:$,peerId:I}){log$2("leaving",{topic:$,peerId:I},{F:__dxlog_file5$2,L:121,S:this,C:(U,q)=>U(...q)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:122,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(U=>U.leave({topic:$,peerId:I}))}async sendMessage({author:$,recipient:I,payload:U}){log$2(`Signal ${I.truncate()}`,void 0,{F:__dxlog_file5$2,L:136,S:this,C:(q,G)=>q(...G)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:137,S:this,A:["this._opened","'Closed'"]}),this._forEachServer(async(q,G)=>{q.sendMessage({author:$,recipient:I,payload:U}).catch(K=>{K instanceof protocols.RateLimitExceededError?log$2.info("WSS rate limit exceeded",{err:K},{F:__dxlog_file5$2,L:142,S:this,C:(Y,J)=>Y(...J)}):K instanceof protocols.TimeoutError||K.constructor.name==="TimeoutError"?(log$2.info("WSS sendMessage timeout",{err:K},{F:__dxlog_file5$2,L:144,S:this,C:(Y,J)=>Y(...J)}),this.checkServerFailure(G)):(log$2.info(`error sending to ${G}`,{err:K},{F:__dxlog_file5$2,L:147,S:this,C:(Y,J)=>Y(...J)}),this.checkServerFailure(G))})})}async checkServerFailure($){const I=this.failureCount.get($)??0;if(I>MAX_SERVER_FAILURES){log$2.warn(`Too many failures sending to ${$} (${I} > ${MAX_SERVER_FAILURES}), restarting`,void 0,{F:__dxlog_file5$2,L:158,S:this,C:(U,q)=>U(...q)}),await this.restartServer($),this.failureCount.set($,0);return}this.failureCount.set($,(this.failureCount.get($)??0)+1)}async subscribeMessages($){log$2(`Subscribed for message stream peerId=${$}`,void 0,{F:__dxlog_file5$2,L:167,S:this,C:(I,U)=>I(...U)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:168,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(async I=>I.subscribeMessages($))}async unsubscribeMessages($){log$2(`Subscribed for message stream peerId=${$}`,void 0,{F:__dxlog_file5$2,L:174,S:this,C:(I,U)=>I(...U)}),invariant(this._opened,"Closed",{F:__dxlog_file5$2,L:175,S:this,A:["this._opened","'Closed'"]}),await this._forEachServer(async I=>I.unsubscribeMessages($))}_initContext(){this._ctx=new Context({onError:$=>log$2.catch($,void 0,{F:__dxlog_file5$2,L:182,S:this,C:(I,U)=>I(...U)})})}async _forEachServer($){return Promise.all(Array.from(this._servers.entries()).map(([I,U])=>$(U,I)))}};_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"open",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"close",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"join",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"leave",null),_ts_decorate$4([synchronized],WebsocketSignalManager.prototype,"checkServerFailure",null);var __dxlog_file6$1="/home/runner/work/dxos/dxos/packages/core/mesh/messaging/src/signal-manager/utils.ts",setIdentityTags=({identityService:$,devicesService:I,setTag:U})=>{$.queryIdentity().subscribe(q=>{var G;if(!((G=q==null?void 0:q.identity)!=null&&G.identityKey)){log$2("empty response from identity service",{idqr:q},{F:__dxlog_file6$1,L:21,S:void 0,C:(K,Y)=>K(...Y)});return}U("identityKey",q.identity.identityKey.truncate())}),I.queryDevices().subscribe(q=>{if(!q||!q.devices||q.devices.length===0){log$2("empty response from device service",{device:q},{F:__dxlog_file6$1,L:30,S:void 0,C:(K,Y)=>K(...Y)});return}invariant(q,"empty response from device service",{F:__dxlog_file6$1,L:33,S:void 0,A:["dqr","'empty response from device service'"]});const G=q.devices.find(K=>K.kind===DeviceKind.CURRENT);if(!G){log$2("no current device",{device:q},{F:__dxlog_file6$1,L:37,S:void 0,C:(K,Y)=>K(...Y)});return}U("deviceKey",G.deviceKey.truncate())})};function dist($,I){if($.length!==I.length)throw new Error("Inputs should have the same length");for(var U=Buffer.allocUnsafe($.length),q=0;q<$.length;q++)U[q]=$[q]^I[q];return U}dist.compare=function $(I,U){if(I.length!==U.length)throw new Error("Inputs should have the same length");for(var q=0;q<I.length;q++)if(I[q]!==U[q])return I[q]<U[q]?-1:1;return 0},dist.gt=function $(I,U){return dist.compare(I,U)===1},dist.lt=function $(I,U){return dist.compare(I,U)===-1},dist.eq=function $(I,U){return dist.compare(I,U)===0};var browser$2={exports:{}},ms,hasRequiredMs;function requireMs(){if(hasRequiredMs)return ms;hasRequiredMs=1;var $=1e3,I=$*60,U=I*60,q=U*24,G=q*7,K=q*365.25;ms=function(Q,ee){ee=ee||{};var te=typeof Q;if(te==="string"&&Q.length>0)return Y(Q);if(te==="number"&&isFinite(Q))return ee.long?X(Q):J(Q);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(Q))};function Y(Q){if(Q=String(Q),!(Q.length>100)){var ee=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(Q);if(ee){var te=parseFloat(ee[1]),ne=(ee[2]||"ms").toLowerCase();switch(ne){case"years":case"year":case"yrs":case"yr":case"y":return te*K;case"weeks":case"week":case"w":return te*G;case"days":case"day":case"d":return te*q;case"hours":case"hour":case"hrs":case"hr":case"h":return te*U;case"minutes":case"minute":case"mins":case"min":case"m":return te*I;case"seconds":case"second":case"secs":case"sec":case"s":return te*$;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return te;default:return}}}}function J(Q){var ee=Math.abs(Q);return ee>=q?Math.round(Q/q)+"d":ee>=U?Math.round(Q/U)+"h":ee>=I?Math.round(Q/I)+"m":ee>=$?Math.round(Q/$)+"s":Q+"ms"}function X(Q){var ee=Math.abs(Q);return ee>=q?Z(Q,ee,q,"day"):ee>=U?Z(Q,ee,U,"hour"):ee>=I?Z(Q,ee,I,"minute"):ee>=$?Z(Q,ee,$,"second"):Q+" ms"}function Z(Q,ee,te,ne){var ie=ee>=te*1.5;return Math.round(Q/te)+" "+ne+(ie?"s":"")}return ms}function setup($){U.debug=U,U.default=U,U.coerce=X,U.disable=K,U.enable=G,U.enabled=Y,U.humanize=requireMs(),U.destroy=Z,Object.keys($).forEach(Q=>{U[Q]=$[Q]}),U.names=[],U.skips=[],U.formatters={};function I(Q){let ee=0;for(let te=0;te<Q.length;te++)ee=(ee<<5)-ee+Q.charCodeAt(te),ee|=0;return U.colors[Math.abs(ee)%U.colors.length]}U.selectColor=I;function U(Q){let ee,te=null,ne,ie;function oe(...ce){if(!oe.enabled)return;const fe=oe,se=Number(new Date),de=se-(ee||se);fe.diff=de,fe.prev=ee,fe.curr=se,ee=se,ce[0]=U.coerce(ce[0]),typeof ce[0]!="string"&&ce.unshift("%O");let ue=0;ce[0]=ce[0].replace(/%([a-zA-Z%])/g,(ve,me)=>{if(ve==="%%")return"%";ue++;const be=U.formatters[me];if(typeof be=="function"){const _e=ce[ue];ve=be.call(fe,_e),ce.splice(ue,1),ue--}return ve}),U.formatArgs.call(fe,ce),(fe.log||U.log).apply(fe,ce)}return oe.namespace=Q,oe.useColors=U.useColors(),oe.color=U.selectColor(Q),oe.extend=q,oe.destroy=U.destroy,Object.defineProperty(oe,"enabled",{enumerable:!0,configurable:!1,get:()=>te!==null?te:(ne!==U.namespaces&&(ne=U.namespaces,ie=U.enabled(Q)),ie),set:ce=>{te=ce}}),typeof U.init=="function"&&U.init(oe),oe}function q(Q,ee){const te=U(this.namespace+(typeof ee>"u"?":":ee)+Q);return te.log=this.log,te}function G(Q){U.save(Q),U.namespaces=Q,U.names=[],U.skips=[];let ee;const te=(typeof Q=="string"?Q:"").split(/[\s,]+/),ne=te.length;for(ee=0;ee<ne;ee++)te[ee]&&(Q=te[ee].replace(/\*/g,".*?"),Q[0]==="-"?U.skips.push(new RegExp("^"+Q.slice(1)+"$")):U.names.push(new RegExp("^"+Q+"$")))}function K(){const Q=[...U.names.map(J),...U.skips.map(J).map(ee=>"-"+ee)].join(",");return U.enable(""),Q}function Y(Q){if(Q[Q.length-1]==="*")return!0;let ee,te;for(ee=0,te=U.skips.length;ee<te;ee++)if(U.skips[ee].test(Q))return!1;for(ee=0,te=U.names.length;ee<te;ee++)if(U.names[ee].test(Q))return!0;return!1}function J(Q){return Q.toString().substring(2,Q.toString().length-2).replace(/\.\*\?$/,"*")}function X(Q){return Q instanceof Error?Q.stack||Q.message:Q}function Z(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return U.enable(U.load()),U}var common=setup;(function($,I){I.formatArgs=q,I.save=G,I.load=K,I.useColors=U,I.storage=Y(),I.destroy=(()=>{let X=!1;return()=>{X||(X=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),I.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function U(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function q(X){if(X[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+X[0]+(this.useColors?"%c ":" ")+"+"+$.exports.humanize(this.diff),!this.useColors)return;const Z="color: "+this.color;X.splice(1,0,Z,"color: inherit");let Q=0,ee=0;X[0].replace(/%[a-zA-Z%]/g,te=>{te!=="%%"&&(Q++,te==="%c"&&(ee=Q))}),X.splice(ee,0,Z)}I.log=console.debug||console.log||(()=>{});function G(X){try{X?I.storage.setItem("debug",X):I.storage.removeItem("debug")}catch{}}function K(){let X;try{X=I.storage.getItem("debug")}catch{}return!X&&typeof process<"u"&&"env"in process&&(X=process.env.DEBUG),X}function Y(){try{return localStorage}catch{}}$.exports=common(I);const{formatters:J}=$.exports;J.j=function(X){try{return JSON.stringify(X)}catch(Z){return"[UnexpectedJSONParseError]: "+Z.message}}})(browser$2,browser$2.exports);var browserExports$1=browser$2.exports,getBrowserRtc=function $(){if(typeof globalThis>"u")return null;var I={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return I.RTCPeerConnection?I:null},browser$1={exports:{}},MAX_BYTES=65536,MAX_UINT32=4294967295;function oldBrowser(){throw new Error(`Secure random number generation is not supported by this browser.
|
|
923
|
+
Use Chrome, Firefox or Internet Explorer 11`)}var Buffer$2=requireSafeBuffer().Buffer,crypto=commonjsGlobal.crypto||commonjsGlobal.msCrypto;crypto&&crypto.getRandomValues?browser$1.exports=randomBytes:browser$1.exports=oldBrowser;function randomBytes($,I){if($>MAX_UINT32)throw new RangeError("requested too many random bytes");var U=Buffer$2.allocUnsafe($);if($>0)if($>MAX_BYTES)for(var q=0;q<$;q+=MAX_BYTES)crypto.getRandomValues(U.slice(q,q+MAX_BYTES));else crypto.getRandomValues(U);return typeof I=="function"?process.nextTick(function(){I(null,U)}):U}var browserExports=browser$1.exports;/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */let promise;var queueMicrotask_1=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:commonjsGlobal):$=>(promise||(promise=Promise.resolve())).then($).catch(I=>setTimeout(()=>{throw I},0));function assign$3($,I){for(const U in I)Object.defineProperty($,U,{value:I[U],enumerable:!0,configurable:!0});return $}function createError($,I,U){if(!$||typeof $=="string")throw new TypeError("Please pass an Error to err-code");U||(U={}),typeof I=="object"&&(U=I,I=""),I&&(U.code=I);try{return assign$3($,U)}catch{U.message=$.message,U.stack=$.stack;const G=function(){};return G.prototype=Object.create(Object.getPrototypeOf($)),assign$3(new G,U)}}var errCode$1=createError;/*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */const debug=browserExports$1("simple-peer"),getBrowserRTC=getBrowserRtc,randombytes=browserExports,stream$1=readableBrowserExports,queueMicrotask$1=queueMicrotask_1,errCode=errCode$1,{Buffer:Buffer$1}=buffer,MAX_BUFFERED_AMOUNT$1=64*1024,ICECOMPLETE_TIMEOUT=5*1e3,CHANNEL_CLOSING_TIMEOUT=5*1e3;function filterTrickle($){return $.replace(/a=ice-options:trickle\s\n/g,"")}function warn$1($){console.warn($)}let Peer$1=class pr extends stream$1.Duplex{constructor(I){if(I=Object.assign({allowHalfOpen:!1},I),super(I),this._id=randombytes(4).toString("hex").slice(0,7),this._debug("new peer %o",I),this.channelName=I.initiator?I.channelName||randombytes(20).toString("hex"):null,this.initiator=I.initiator||!1,this.channelConfig=I.channelConfig||pr.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},pr.config,I.config),this.offerOptions=I.offerOptions||{},this.answerOptions=I.answerOptions||{},this.sdpTransform=I.sdpTransform||(U=>U),this.streams=I.streams||(I.stream?[I.stream]:[]),this.trickle=I.trickle!==void 0?I.trickle:!0,this.allowHalfTrickle=I.allowHalfTrickle!==void 0?I.allowHalfTrickle:!1,this.iceCompleteTimeout=I.iceCompleteTimeout||ICECOMPLETE_TIMEOUT,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=I.wrtc&&typeof I.wrtc=="object"?I.wrtc:getBrowserRTC(),!this._wrtc)throw errCode(typeof window>"u"?new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"):new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(U){this.destroy(errCode(U,"ERR_PC_CONSTRUCTOR"));return}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId=="number",this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=U=>{this._onIceCandidate(U)},typeof this._pc.peerIdentity=="object"&&this._pc.peerIdentity.catch(U=>{this.destroy(errCode(U,"ERR_PC_PEER_IDENTITY"))}),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=U=>{this._setupData(U)},this.streams&&this.streams.forEach(U=>{this.addStream(U)}),this._pc.ontrack=U=>{this._onTrack(U)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof I=="string")try{I=JSON.parse(I)}catch{I={}}this._debug("signal()"),I.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),I.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(I.transceiverRequest.kind,I.transceiverRequest.init)),I.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(I.candidate):this._pendingCandidates.push(I.candidate)),I.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(I)).then(()=>{this.destroyed||(this._pendingCandidates.forEach(U=>{this._addIceCandidate(U)}),this._pendingCandidates=[],this._pc.remoteDescription.type==="offer"&&this._createAnswer())}).catch(U=>{this.destroy(errCode(U,"ERR_SET_REMOTE_DESCRIPTION"))}),!I.sdp&&!I.candidate&&!I.renegotiate&&!I.transceiverRequest&&this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(I){const U=new this._wrtc.RTCIceCandidate(I);this._pc.addIceCandidate(U).catch(q=>{!U.address||U.address.endsWith(".local")?warn$1("Ignoring unsupported ICE candidate."):this.destroy(errCode(q,"ERR_ADD_ICE_CANDIDATE"))})}send(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(I)}}addTransceiver(I,U){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(I,U),this._needsNegotiation()}catch(q){this.destroy(errCode(q,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:I,init:U}})}}addStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),I.getTracks().forEach(U=>{this.addTrack(U,I)})}}addTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const q=this._senderMap.get(I)||new Map;let G=q.get(U);if(!G)G=this._pc.addTrack(I,U),q.set(U,G),this._senderMap.set(I,q),this._needsNegotiation();else throw G.removed?errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}replaceTrack(I,U,q){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const G=this._senderMap.get(I),K=G?G.get(q):null;if(!K)throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");U&&this._senderMap.set(U,G),K.replaceTrack!=null?K.replaceTrack(U):this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(I,U){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const q=this._senderMap.get(I),G=q?q.get(U):null;if(!G)throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{G.removed=!0,this._pc.removeTrack(G)}catch(K){K.name==="NS_ERROR_UNEXPECTED"?this._sendersAwaitingStable.push(G):this.destroy(errCode(K,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(I){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),I.getTracks().forEach(U=>{this.removeTrack(U,I)})}}_needsNegotiation(){this._debug("_needsNegotiation"),!this._batchedNegotiation&&(this._batchedNegotiation=!0,queueMicrotask$1(()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1}))}negotiate(){if(!this.destroying){if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout(()=>{this._createOffer()},0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(I){this._destroy(I,()=>{})}_destroy(I,U){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",I&&(I.message||I)),queueMicrotask$1(()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",I&&(I.message||I)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch{}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch{}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,I&&this.emit("error",I),this.emit("close"),U()}))}_setupData(I){if(!I.channel)return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=I.channel,this._channel.binaryType="arraybuffer",typeof this._channel.bufferedAmountLowThreshold=="number"&&(this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT$1),this.channelName=this._channel.label,this._channel.onmessage=q=>{this._onChannelMessage(q)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=q=>{const G=q.error instanceof Error?q.error:new Error(`Datachannel error: ${q.message} ${q.filename}:${q.lineno}:${q.colno}`);this.destroy(errCode(G,"ERR_DATA_CHANNEL"))};let U=!1;this._closingInterval=setInterval(()=>{this._channel&&this._channel.readyState==="closing"?(U&&this._onChannelClose(),U=!0):U=!1},CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(I,U,q){if(this.destroyed)return q(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(I)}catch(G){return this.destroy(errCode(G,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=q):q(null)}else this._debug("write before connect"),this._chunk=I,this._cb=q}_onFinish(){if(this.destroyed)return;const I=()=>{setTimeout(()=>this.destroy(),1e3)};this._connected?I():this.once("connect",I)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout(()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))},this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp})},q=()=>{this._debug("createOffer success"),!this.destroyed&&(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_OFFER"))})}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach(I=>{!I.mid&&I.sender.track&&!I.requested&&(I.requested=!0,this.addTransceiver(I.sender.track.kind))})}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then(I=>{if(this.destroyed)return;!this.trickle&&!this.allowHalfTrickle&&(I.sdp=filterTrickle(I.sdp)),I.sdp=this.sdpTransform(I.sdp);const U=()=>{if(this.destroyed)return;const K=this._pc.localDescription||I;this._debug("signal"),this.emit("signal",{type:K.type,sdp:K.sdp}),this.initiator||this._requestMissingTransceivers()},q=()=>{this.destroyed||(this.trickle||this._iceComplete?U():this.once("_iceComplete",U))},G=K=>{this.destroy(errCode(K,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(I).then(q).catch(G)}).catch(I=>{this.destroy(errCode(I,"ERR_CREATE_ANSWER"))})}_onConnectionStateChange(){this.destroyed||this._pc.connectionState==="failed"&&this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const I=this._pc.iceConnectionState,U=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",I,U),this.emit("iceStateChange",I,U),(I==="connected"||I==="completed")&&(this._pcReady=!0,this._maybeReady()),I==="failed"&&this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),I==="closed"&&this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(I){const U=q=>(Object.prototype.toString.call(q.values)==="[object Array]"&&q.values.forEach(G=>{Object.assign(q,G)}),q);this._pc.getStats.length===0||this._isReactNativeWebrtc?this._pc.getStats().then(q=>{const G=[];q.forEach(K=>{G.push(U(K))}),I(null,G)},q=>I(q)):this._pc.getStats.length>0?this._pc.getStats(q=>{if(this.destroyed)return;const G=[];q.result().forEach(K=>{const Y={};K.names().forEach(J=>{Y[J]=K.stat(J)}),Y.id=K.id,Y.type=K.type,Y.timestamp=K.timestamp,G.push(U(Y))}),I(null,G)},q=>I(q)):I(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const I=()=>{this.destroyed||this.getStats((U,q)=>{if(this.destroyed)return;U&&(q=[]);const G={},K={},Y={};let J=!1;q.forEach(Z=>{(Z.type==="remotecandidate"||Z.type==="remote-candidate")&&(G[Z.id]=Z),(Z.type==="localcandidate"||Z.type==="local-candidate")&&(K[Z.id]=Z),(Z.type==="candidatepair"||Z.type==="candidate-pair")&&(Y[Z.id]=Z)});const X=Z=>{J=!0;let Q=K[Z.localCandidateId];Q&&(Q.ip||Q.address)?(this.localAddress=Q.ip||Q.address,this.localPort=Number(Q.port)):Q&&Q.ipAddress?(this.localAddress=Q.ipAddress,this.localPort=Number(Q.portNumber)):typeof Z.googLocalAddress=="string"&&(Q=Z.googLocalAddress.split(":"),this.localAddress=Q[0],this.localPort=Number(Q[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let ee=G[Z.remoteCandidateId];ee&&(ee.ip||ee.address)?(this.remoteAddress=ee.ip||ee.address,this.remotePort=Number(ee.port)):ee&&ee.ipAddress?(this.remoteAddress=ee.ipAddress,this.remotePort=Number(ee.portNumber)):typeof Z.googRemoteAddress=="string"&&(ee=Z.googRemoteAddress.split(":"),this.remoteAddress=ee[0],this.remotePort=Number(ee[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(q.forEach(Z=>{Z.type==="transport"&&Z.selectedCandidatePairId&&X(Y[Z.selectedCandidatePairId]),(Z.type==="googCandidatePair"&&Z.googActiveConnection==="true"||(Z.type==="candidatepair"||Z.type==="candidate-pair")&&Z.selected)&&X(Z)}),!J&&(!Object.keys(Y).length||Object.keys(K).length)){setTimeout(I,100);return}else this._connecting=!1,this._connected=!0;if(this._chunk){try{this.send(this._chunk)}catch(Q){return this.destroy(errCode(Q,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const Z=this._cb;this._cb=null,Z(null)}typeof this._channel.bufferedAmountLowThreshold!="number"&&(this._interval=setInterval(()=>this._onInterval(),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")})};I()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT$1||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||(this._pc.signalingState==="stable"&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach(I=>{this._pc.removeTrack(I),this._queuedNegotiation=!0}),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(I){this.destroyed||(I.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:I.candidate.candidate,sdpMLineIndex:I.candidate.sdpMLineIndex,sdpMid:I.candidate.sdpMid}}):!I.candidate&&!this._iceComplete&&(this._iceComplete=!0,this.emit("_iceComplete")),I.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(I){if(this.destroyed)return;let U=I.data;U instanceof ArrayBuffer&&(U=Buffer$1.from(U)),this.push(U)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const I=this._cb;this._cb=null,I(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(I){this.destroyed||I.streams.forEach(U=>{this._debug("on track"),this.emit("track",I.track,U),this._remoteTracks.push({track:I.track,stream:U}),!this._remoteStreams.some(q=>q.id===U.id)&&(this._remoteStreams.push(U),queueMicrotask$1(()=>{this._debug("on stream"),this.emit("stream",U)}))})}_debug(){const I=[].slice.call(arguments);I[0]="["+this._id+"] "+I[0],debug.apply(null,I)}};Peer$1.WEBRTC_SUPPORT=!!getBrowserRTC(),Peer$1.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},Peer$1.channelConfig={};var ConnectionState$1;(function($){$[$.INVALID=0]="INVALID",$[$.CONNECTING=1]="CONNECTING",$[$.CONNECTED=2]="CONNECTED",$[$.CLOSED=3]="CLOSED"})(ConnectionState$1||(ConnectionState$1={}));var emitterComponent=Emitter$1;function Emitter$1($){if($)return mixin($)}function mixin($){for(var I in Emitter$1.prototype)$[I]=Emitter$1.prototype[I];return $}Emitter$1.prototype.on=Emitter$1.prototype.addEventListener=function($,I){return this._callbacks=this._callbacks||{},(this._callbacks[$]=this._callbacks[$]||[]).push(I),this},Emitter$1.prototype.once=function($,I){var U=this;this._callbacks=this._callbacks||{};function q(){U.off($,q),I.apply(this,arguments)}return q.fn=I,this.on($,q),this},Emitter$1.prototype.off=Emitter$1.prototype.removeListener=Emitter$1.prototype.removeAllListeners=Emitter$1.prototype.removeEventListener=function($,I){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var U=this._callbacks[$];if(!U)return this;if(arguments.length==1)return delete this._callbacks[$],this;for(var q,G=0;G<U.length;G++)if(q=U[G],q===I||q.fn===I){U.splice(G,1);break}return this},Emitter$1.prototype.emit=function($){this._callbacks=this._callbacks||{};var I=[].slice.call(arguments,1),U=this._callbacks[$];if(U){U=U.slice(0);for(var q=0,G=U.length;q<G;++q)U[q].apply(this,I)}return this},Emitter$1.prototype.listeners=function($){return this._callbacks=this._callbacks||{},this._callbacks[$]||[]},Emitter$1.prototype.hasListeners=function($){return!!this.listeners($).length};var Emitter=emitterComponent;function Stream(){Emitter.call(this)}Stream.prototype=new Emitter;var stream=Stream;Stream.Stream=Stream,Stream.prototype.pipe=function($,I){var U=this;function q(Q){$.writable&&$.write(Q)===!1&&U.pause&&U.pause()}U.on("data",q);function G(){U.readable&&U.resume&&U.resume()}$.on("drain",G),!$._isStdio&&(!I||I.end!==!1)&&(U.on("end",Y),U.on("close",J));var K=!1;function Y(){K||(K=!0,$.end())}function J(){K||(K=!0,typeof $.destroy=="function"&&$.destroy())}function X(Q){if(Z(),!this.hasListeners("error"))throw Q}U.on("error",X),$.on("error",X);function Z(){U.off("data",q),$.off("drain",G),U.off("end",Y),U.off("close",J),U.off("error",X),$.off("error",X),U.off("end",Z),U.off("close",Z),$.off("end",Z),$.off("close",Z)}return U.on("end",Z),U.on("close",Z),$.on("end",Z),$.on("close",Z),$.emit("pipe",U),$};var encode_1=encode,MSB$1=128,REST$1=127,MSBALL=~REST$1,INT=Math.pow(2,31);function encode($,I,U){if(Number.MAX_SAFE_INTEGER&&$>Number.MAX_SAFE_INTEGER)throw encode.bytes=0,new RangeError("Could not encode varint");I=I||[],U=U||0;for(var q=U;$>=INT;)I[U++]=$&255|MSB$1,$/=128;for(;$&MSBALL;)I[U++]=$&255|MSB$1,$>>>=7;return I[U]=$|0,encode.bytes=U-q+1,I}var decode=read,MSB=128,REST=127;function read($,q){var U=0,q=q||0,G=0,K=q,Y,J=$.length;do{if(K>=J||G>49)throw read.bytes=0,new RangeError("Could not decode varint");Y=$[K++],U+=G<28?(Y&REST)<<G:(Y&REST)*Math.pow(2,G),G+=7}while(Y>=MSB);return read.bytes=K-q,U}var N1=Math.pow(2,7),N2=Math.pow(2,14),N3=Math.pow(2,21),N4=Math.pow(2,28),N5=Math.pow(2,35),N6=Math.pow(2,42),N7=Math.pow(2,49),N8=Math.pow(2,56),N9=Math.pow(2,63),length=function($){return $<N1?1:$<N2?2:$<N3?3:$<N4?4:$<N5?5:$<N6?6:$<N7?7:$<N8?8:$<N9?9:10},varint={encode:encode_1,decode,encodingLength:length},__dxlog_file$4="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/control-extension.ts",HEARTBEAT_RTT_WARN_THRESH=1e4,ControlExtension=class{constructor($,I,U){this.opts=$,this.localPeerId=I,this.remotePeerId=U,this._ctx=new Context({onError:q=>{this._extensionContext.close(q)}}),this.onExtensionRegistered=new Callback}async registerExtension($){await this._rpc.rpc.Control.registerExtension({name:$})}async onOpen($){this._extensionContext=$,this._rpc=createProtoRpcPeer({requested:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},exposed:{Control:protocols.schema.getService("dxos.mesh.teleport.control.ControlService")},handlers:{Control:{registerExtension:async I=>{this.onExtensionRegistered.call(I.name)},heartbeat:async I=>(log$2("received heartbeat request",{ts:I.requestTimestamp,localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:66,S:this,C:(U,q)=>U(...q)}),{requestTimestamp:I.requestTimestamp})}},port:await $.createPort("rpc",{contentType:'application/x-protobuf; messageType="dxos.rpc.Message"'}),timeout:this.opts.heartbeatTimeout}),await this._rpc.open(),scheduleTaskInterval(this._ctx,async()=>{const I=new Date;try{const U=await asyncTimeout(this._rpc.rpc.Control.heartbeat({requestTimestamp:I}),this.opts.heartbeatTimeout),q=Date.now();U.requestTimestamp instanceof Date&&(q-U.requestTimestamp.getTime()>(HEARTBEAT_RTT_WARN_THRESH<this.opts.heartbeatTimeout?HEARTBEAT_RTT_WARN_THRESH:this.opts.heartbeatTimeout/2)?log$2.warn(`heartbeat RTT for Teleport > ${HEARTBEAT_RTT_WARN_THRESH/1e3}s`,{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:103,S:this,C:(G,K)=>G(...K)}):log$2("heartbeat RTT",{rtt:q-U.requestTimestamp.getTime(),localPeerId:this.localPeerId.truncate(),remotePeerId:this.remotePeerId.truncate()},{F:__dxlog_file$4,L:109,S:this,C:(G,K)=>G(...K)}))}catch(U){const q=Date.now();if(U instanceof protocols.RpcClosedError){log$2("ignoring RpcClosedError in heartbeat",void 0,{F:__dxlog_file$4,L:119,S:this,C:(G,K)=>G(...K)});return}U instanceof TimeoutError?(log$2("timeout waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:123,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U)):(log$2.info("other error waiting for heartbeat response",{err:U,delay:q-I.getTime()},{F:__dxlog_file$4,L:126,S:this,C:(G,K)=>G(...K)}),this.opts.onTimeout(U))}},this.opts.heartbeatInterval)}async onClose($){await this._ctx.dispose(),await this._rpc.close()}async onAbort($){await this._ctx.dispose(),await this._rpc.abort()}},__dxlog_file2$3="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/framer.ts",FRAME_LENGTH_SIZE=2,Framer=class{constructor(){this._messageCb=void 0,this._subscribeCb=void 0,this._buffer=void 0,this._sendCallbacks=[],this._bytesSent=0,this._bytesReceived=0,this._writable=!0,this.drain=new Event$1,this._stream=new readableBrowserExports.Duplex({objectMode:!1,read:()=>{this._processResponseQueue()},write:($,I,U)=>{invariant(!this._subscribeCb,"Internal Framer bug. Concurrent writes detected.",{F:__dxlog_file2$3,L:40,S:this,A:["!this._subscribeCb","'Internal Framer bug. Concurrent writes detected.'"]}),this._bytesReceived+=$.length,this._buffer&&this._buffer.length>0?this._buffer=export_Buffer.concat([this._buffer,$]):this._buffer=$,this._messageCb?(this._popFrames(),U()):this._subscribeCb=()=>{this._popFrames(),this._subscribeCb=void 0,U()}}}),this.port={send:$=>new Promise(I=>{const U=encodeFrame($);this._bytesSent+=U.length,this._writable=this._stream.push(U),this._writable?I():this._sendCallbacks.push(I)}),subscribe:$=>{var I;return invariant(!this._messageCb,"Rpc port already has a message listener.",{F:__dxlog_file2$3,L:79,S:this,A:["!this._messageCb","'Rpc port already has a message listener.'"]}),this._messageCb=$,(I=this._subscribeCb)==null||I.call(this),()=>{this._messageCb=void 0}}}}get stream(){return this._stream}get bytesSent(){return this._bytesSent}get bytesReceived(){return this._bytesReceived}get writable(){return this._writable}_processResponseQueue(){const $=this._sendCallbacks;this._sendCallbacks=[],this._writable=!0,this.drain.emit(),$.forEach(I=>I())}_popFrames(){let $=0;for(;$<this._buffer.length;){const I=decodeFrame(this._buffer,$);if(!I)break;$+=I.bytesConsumed,this._messageCb(I.payload)}$<this._buffer.length?this._buffer=this._buffer.subarray($):this._buffer=void 0}destroy(){this._stream.readableLength>0&&log$2.info("framer destroyed while there are still read bytes in the buffer.",void 0,{F:__dxlog_file2$3,L:140,S:this,C:($,I)=>$(...I)}),this._stream.writableLength>0&&log$2.warn("framer destroyed while there are still write bytes in the buffer.",void 0,{F:__dxlog_file2$3,L:143,S:this,C:($,I)=>$(...I)}),this._stream.destroy()}},decodeFrame=($,I)=>{if($.length<I+FRAME_LENGTH_SIZE)return;const U=$.readUInt16BE(I),q=FRAME_LENGTH_SIZE+U;return $.length<I+q?void 0:{payload:$.subarray(I+FRAME_LENGTH_SIZE,I+q),bytesConsumed:q}},encodeFrame=$=>{const I=export_Buffer.allocUnsafe(FRAME_LENGTH_SIZE+$.length);return I.writeUInt16BE($.length,0),I.set($,FRAME_LENGTH_SIZE),I},__dxlog_file3$1="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/balancer.ts",MAX_CHUNK_SIZE=8192,Balancer=class{constructor($){this._sysChannelId=$,this._lastCallerIndex=0,this._channels=[],this._framer=new Framer,this._sendBuffers=new Map,this._receiveBuffers=new Map,this._sending=!1,this.incomingData=new Event$1,this.stream=this._framer.stream,this._channels.push($),this._framer.port.subscribe(this._processIncomingMessage.bind(this))}get bytesSent(){return this._framer.bytesSent}get bytesReceived(){return this._framer.bytesReceived}get buffersCount(){return this._sendBuffers.size}addChannel($){this._channels.push($)}pushData($,I,U){this._enqueueChunk($,I,U),this._sendChunks().catch(q=>log$2.catch(q,void 0,{F:__dxlog_file3$1,L:75,S:this,C:(G,K)=>G(...K)}))}destroy(){this._sendBuffers.size!==0&&log$2.info("destroying balancer with pending calls",void 0,{F:__dxlog_file3$1,L:80,S:this,C:($,I)=>$(...I)}),this._sendBuffers.clear(),this._framer.destroy()}_processIncomingMessage($){const{channelId:I,dataLength:U,chunk:q}=decodeChunk($,G=>!this._receiveBuffers.has(G));if(!this._receiveBuffers.has(I))q.length<U?this._receiveBuffers.set(I,{buffer:export_Buffer.from(q),msgLength:U}):this.incomingData.emit(q);else{const G=this._receiveBuffers.get(I);if(G.buffer=export_Buffer.concat([G.buffer,q]),G.buffer.length<G.msgLength)return;const K=G.buffer;this._receiveBuffers.delete(I),this.incomingData.emit(K)}}_getNextCallerId(){if(this._sendBuffers.has(this._sysChannelId))return this._sysChannelId;const $=this._lastCallerIndex;return this._lastCallerIndex=(this._lastCallerIndex+1)%this._channels.length,this._channels[$]}_enqueueChunk($,I,U){if(!this._channels.includes(U))throw new Error(`Unknown channel ${U}`);this._sendBuffers.has(U)||this._sendBuffers.set(U,[]);const q=this._sendBuffers.get(U),G=[];for(let K=0;K<$.length;K+=MAX_CHUNK_SIZE)G.push($.subarray(K,K+MAX_CHUNK_SIZE));G.forEach((K,Y)=>{const J=encodeChunk({chunk:K,channelId:U,dataLength:Y===0?$.length:void 0});q.push({msg:J,trigger:Y===G.length-1?I:void 0})})}_getNextChunk(){let $;for(;this._sendBuffers.size>0;){const I=this._getNextCallerId(),U=this._sendBuffers.get(I);if(U&&($=U.shift(),!!$))return U.length===0&&this._sendBuffers.delete(I),$}return null}async _sendChunks(){var I,U;if(this._sending)return;this._sending=!0;let $;for($=this._getNextChunk();$;){this._framer.writable||(log$2("PAUSE for drain",void 0,{F:__dxlog_file3$1,L:179,S:this,C:(q,G)=>q(...G)}),await this._framer.drain.waitForCount(1),log$2("RESUME for drain",void 0,{F:__dxlog_file3$1,L:181,S:this,C:(q,G)=>q(...G)}));try{await this._framer.port.send($.msg),(I=$.trigger)==null||I.wake()}catch(q){log$2("Error sending chunk",{err:q},{F:__dxlog_file3$1,L:187,S:this,C:(G,K)=>G(...K)}),(U=$.trigger)==null||U.throw(q)}$=this._getNextChunk()}invariant(this._sendBuffers.size===0,"sendBuffers not empty",{F:__dxlog_file3$1,L:192,S:this,A:["this._sendBuffers.size === 0","'sendBuffers not empty'"]}),this._sending=!1}},encodeChunk=({channelId:$,dataLength:I,chunk:U})=>{const q=varint.encodingLength($),G=I?varint.encodingLength(I):0,K=export_Buffer.allocUnsafe(q+G+U.length);return varint.encode($,K),I&&varint.encode(I,K,q),K.set(U,q+G),K},decodeChunk=($,I)=>{const U=varint.decode($);let q,G=varint.decode.bytes;I(U)&&(q=varint.decode($,G),G+=varint.decode.bytes);const K=$.subarray(G);return{channelId:U,dataLength:q,chunk:K}};function _ts_decorate$3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$2="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts",Command=protocols.schema.getCodecForType("dxos.mesh.muxer.Command"),DEFAULT_SEND_COMMAND_TIMEOUT=6e4,DESTROY_COMMAND_SEND_TIMEOUT=5e3,STATS_INTERVAL=1e3,MAX_SAFE_FRAME_SIZE=1e6,SYSTEM_CHANNEL_ID=0,GRACEFUL_CLOSE_TIMEOUT=3e3,Muxer=class{constructor(){this._balancer=new Balancer(SYSTEM_CHANNEL_ID),this._channelsByLocalId=new Map,this._channelsByTag=new Map,this._ctx=new Context,this._nextId=1,this._closing=!1,this._destroying=!1,this._disposed=!1,this._lastStats=void 0,this._lastChannelStats=new Map,this.afterClosed=new Event$1,this.statsUpdated=new Event$1,this.stream=this._balancer.stream,this._balancer.incomingData.on(async $=>{await this._handleCommand(Command.decode($))})}setSessionId($){this._sessionId=$}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}async createStream($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:151,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});const q=new readableBrowserExports.Duplex({write:(G,K,Y)=>{this._sendData(U,G).then(()=>Y()).catch(Y)},read:()=>{}});U.push=G=>{U.stats.bytesReceived+=G.length,q.push(G)},U.destroy=G=>{G&&q.listeners("error").length>0?q.destroy(G):q.destroy()};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(G){throw this._destroyChannel(U,G),G}return q}async createPort($,I={}){const U=this._getOrCreateStream({tag:$,contentType:I.contentType});invariant(!U.push,`Channel already open: ${$}`,{F:__dxlog_file4$2,L:211,S:this,A:["!channel.push","`Channel already open: ${tag}`"]});let q=[],G;U.push=Y=>{U.stats.bytesReceived+=Y.length,G?G(Y):q.push(Y)};const K={send:async(Y,J)=>{await this._sendData(U,Y,J)},subscribe:Y=>{invariant(!G,"Only one subscriber is allowed",{F:__dxlog_file4$2,L:233,S:this,A:["!callback","'Only one subscriber is allowed'"]}),G=Y;for(const J of q)Y(J);q=[]}};try{await this._sendCommand({openChannel:{id:U.id,tag:U.tag,contentType:U.contentType}},SYSTEM_CHANNEL_ID)}catch(Y){throw this._destroyChannel(U,Y),Y}return K}async close($){if(this._destroying){log$2("already destroying, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:266,S:this,C:(I,U)=>I(...U)});return}if(this._closing){log$2("already closing, ignoring graceful close request",void 0,{F:__dxlog_file4$2,L:270,S:this,C:(I,U)=>I(...U)});return}this._closing=!0,await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID,DESTROY_COMMAND_SEND_TIMEOUT).catch(async I=>{log$2("error sending close command",{err:I},{F:__dxlog_file4$2,L:285,S:this,C:(U,q)=>U(...q)}),await this._dispose(I)}),await asyncTimeout(this._dispose($),GRACEFUL_CLOSE_TIMEOUT,new protocols.TimeoutError("gracefully closing muxer"))}async destroy($){if(this._destroying){log$2("already destroying, ignoring destroy request",void 0,{F:__dxlog_file4$2,L:298,S:this,C:(I,U)=>I(...U)});return}this._destroying=!0,this._ctx.dispose(),this._closing?(log$2("destroy cancelling graceful close",void 0,{F:__dxlog_file4$2,L:304,S:this,C:(I,U)=>I(...U)}),this._closing=!1):await this._sendCommand({close:{error:$==null?void 0:$.message}},SYSTEM_CHANNEL_ID).catch(async I=>{log$2("error sending courtesy close command",{err:I},{F:__dxlog_file4$2,L:317,S:this,C:(U,q)=>U(...q)})}),this._dispose($).catch(I=>{log$2("error disposing after destroy",{err:I},{F:__dxlog_file4$2,L:322,S:this,C:(U,q)=>U(...q)})})}async _dispose($){var I;if(this._disposed){log$2("already destroyed, ignoring dispose request",void 0,{F:__dxlog_file4$2,L:330,S:this,C:(U,q)=>U(...q)});return}this._ctx.dispose(),await this._balancer.destroy();for(const U of this._channelsByTag.values())(I=U.destroy)==null||I.call(U,$);this._disposed=!0,await this._emitStats(),this.afterClosed.emit($),this._channelsByLocalId.clear(),this._channelsByTag.clear()}async _handleCommand($){if(this._disposed){log$2.warn("Received command after disposed",{cmd:$},{F:__dxlog_file4$2,L:353,S:this,C:(I,U)=>I(...U)});return}if($.close){this._closing?log$2("received close from peer, already closing",void 0,{F:__dxlog_file4$2,L:362,S:this,C:(I,U)=>I(...U)}):(log$2("received peer close, initiating my own graceful close",void 0,{F:__dxlog_file4$2,L:359,S:this,C:(I,U)=>I(...U)}),await this.close(new Error("received peer close")));return}if($.openChannel){const I=this._getOrCreateStream({tag:$.openChannel.tag,contentType:$.openChannel.contentType});I.remoteId=$.openChannel.id;for(const U of I.buffer)await this._sendCommand({data:{channelId:I.remoteId,data:U}},I.id);I.buffer=[]}else if($.data){const I=this._channelsByLocalId.get($.data.channelId)??failUndefined();if(!I.push){log$2.warn("Received data for channel before it was opened",{tag:I.tag},{F:__dxlog_file4$2,L:391,S:this,C:(U,q)=>U(...q)});return}I.push($.data.data)}}async _sendCommand($,I=-1,U=DEFAULT_SEND_COMMAND_TIMEOUT){if(this._disposed){log$2.info("ignoring sendCommand after disposed",{cmd:$},{F:__dxlog_file4$2,L:400,S:this,C:(q,G)=>q(...G)});return}try{const q=new Trigger;this._balancer.pushData(Command.encode($),q,I),await q.wait({timeout:U})}catch(q){await this.destroy(q)}}_getOrCreateStream($){this._channelsByTag.size===0&&scheduleTaskInterval(this._ctx,async()=>this._emitStats(),STATS_INTERVAL);let I=this._channelsByTag.get($.tag);return I||(I={id:this._nextId++,remoteId:null,tag:$.tag,contentType:$.contentType,buffer:[],push:null,destroy:null,stats:{bytesSent:0,bytesReceived:0}},this._channelsByTag.set(I.tag,I),this._channelsByLocalId.set(I.id,I),this._balancer.addChannel(I.id)),I}async _sendData($,I,U){if(I.length>MAX_SAFE_FRAME_SIZE&&log$2.warn("frame size exceeds maximum safe value",{size:I.length,threshold:MAX_SAFE_FRAME_SIZE},{F:__dxlog_file4$2,L:441,S:this,C:(q,G)=>q(...G)}),$.stats.bytesSent+=I.length,$.remoteId===null){$.buffer.push(I);return}await this._sendCommand({data:{channelId:$.remoteId,data:I}},$.id,U)}_destroyChannel($,I){$.destroy&&$.destroy(I),this._channelsByLocalId.delete($.id),this._channelsByTag.delete($.tag)}async _emitStats(){if(this._disposed||this._destroying){if(!this._lastStats)return;const K=this._lastStats;this._lastStats=void 0,K.readBufferSize=0,K.writeBufferSize=0;for(const Y of K.channels)Y.writeBufferSize=0;this.statsUpdated.emit(K),this._lastChannelStats.clear();return}const $=this._balancer.bytesSent,I=this._balancer.bytesReceived,U=Date.now(),q=this._lastStats?(U-this._lastStats.timestamp)/1e3:0,G=(K,Y)=>Y?{bytesSentRate:q?(K.bytesSent-Y.bytesSent)/q:void 0,bytesReceivedRate:q?(K.bytesReceived-Y.bytesReceived)/q:void 0}:{};this._lastStats={timestamp:U,channels:Array.from(this._channelsByTag.values()).map(K=>{const Y={id:K.id,tag:K.tag,contentType:K.contentType,writeBufferSize:K.buffer.length,bytesSent:K.stats.bytesSent,bytesReceived:K.stats.bytesReceived,...G(K.stats,this._lastChannelStats.get(K.id))};return this._lastChannelStats.set(K.id,Y),Y}),bytesSent:$,bytesReceived:I,...G({bytesSent:$,bytesReceived:I},this._lastStats),readBufferSize:this._balancer.stream.readableLength,writeBufferSize:this._balancer.stream.writableLength},this.statsUpdated.emit(this._lastStats)}};_ts_decorate$3([logInfo],Muxer.prototype,"sessionIdString",null);function _ts_decorate2$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5$1="/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/teleport.ts",CONTROL_HEARTBEAT_INTERVAL=1e4,CONTROL_HEARTBEAT_TIMEOUT=6e4,Teleport=class{constructor({initiator:$,localPeerId:I,remotePeerId:U}){this._ctx=new Context({onError:q=>{this.destroy(q).catch(()=>{log$2.error("Error during destroy",q,{F:__dxlog_file5$1,L:39,S:this,C:(G,K)=>G(...K)})})}}),this._muxer=new Muxer,this._extensions=new Map,this._remoteExtensions=new Set,this._open=!1,this._destroying=!1,this._aborting=!1,invariant(typeof $=="boolean",void 0,{F:__dxlog_file5$1,L:56,S:this,A:["typeof initiator === 'boolean'",""]}),invariant(PublicKey.isPublicKey(I),void 0,{F:__dxlog_file5$1,L:57,S:this,A:["PublicKey.isPublicKey(localPeerId)",""]}),invariant(PublicKey.isPublicKey(U),void 0,{F:__dxlog_file5$1,L:58,S:this,A:["PublicKey.isPublicKey(remotePeerId)",""]}),this.initiator=$,this.localPeerId=I,this.remotePeerId=U,this._control=new ControlExtension({heartbeatInterval:CONTROL_HEARTBEAT_INTERVAL,heartbeatTimeout:CONTROL_HEARTBEAT_TIMEOUT,onTimeout:()=>{this._destroying||this._aborting||(log$2.info("abort teleport due to onTimeout in ControlExtension",void 0,{F:__dxlog_file5$1,L:71,S:this,C:(q,G)=>q(...G)}),this.abort(new protocols.TimeoutError("control extension")).catch(q=>log$2.catch(q,void 0,{F:__dxlog_file5$1,L:72,S:this,C:(G,K)=>G(...K)})))}},this.localPeerId,this.remotePeerId),this._control.onExtensionRegistered.set(async q=>{if(log$2("remote extension",{name:q},{F:__dxlog_file5$1,L:80,S:this,C:(G,K)=>G(...K)}),invariant(!this._remoteExtensions.has(q),"Remote extension already exists",{F:__dxlog_file5$1,L:81,S:this,A:["!this._remoteExtensions.has(name)","'Remote extension already exists'"]}),this._remoteExtensions.add(q),this._extensions.has(q))try{await this._openExtension(q)}catch(G){await this.destroy(G)}}),this._muxer.stream.on("close",async()=>{if(this._destroying||this._aborting){log$2("destroy teleport due to muxer stream close, skipping due to already destroying/aborting",void 0,{F:__dxlog_file5$1,L:97,S:this,C:(q,G)=>q(...G)});return}await this.destroy()}),this._muxer.stream.on("error",async q=>{await this.destroy(q)}),this._muxer.statsUpdated.on(q=>{log$2.trace("dxos.mesh.teleport.stats",{localPeerId:I,remotePeerId:U,bytesSent:q.bytesSent,bytesSentRate:q.bytesSentRate,bytesReceived:q.bytesReceived,bytesReceivedRate:q.bytesReceivedRate,channels:q.channels},{F:__dxlog_file5$1,L:110,S:this,C:(G,K)=>G(...K)})})}get sessionIdString(){return this._sessionId?this._sessionId.truncate():"none"}get stream(){return this._muxer.stream}get stats(){return this._muxer.statsUpdated}async open($=PublicKey.random()){this._sessionId=$,log$2("open",void 0,{F:__dxlog_file5$1,L:144,S:this,C:(I,U)=>I(...U)}),this._setExtension("dxos.mesh.teleport.control",this._control),await this._openExtension("dxos.mesh.teleport.control"),this._open=!0,this._muxer.setSessionId($)}async close($){await this.destroy($)}async abort($){if(!(this._aborting||this._destroying)&&(this._aborting=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onAbort($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:173,S:this,C:(q,G)=>q(...G)})}await this._muxer.destroy($)}}async destroy($){if(!(this._destroying||this._aborting)&&(this._destroying=!0,!this._ctx.disposed)){await this._ctx.dispose();for(const I of this._extensions.values())try{await I.onClose($)}catch(U){log$2.catch(U,void 0,{F:__dxlog_file5$1,L:197,S:this,C:(q,G)=>q(...G)})}await this._muxer.close()}}addExtension($,I){if(!this._open)throw new Error("Not open");log$2("addExtension",{name:$},{F:__dxlog_file5$1,L:209,S:this,C:(U,q)=>U(...q)}),this._setExtension($,I),scheduleTask(this._ctx,async()=>{try{await this._control.registerExtension($)}catch(U){if(U instanceof protocols.RpcClosedError)return;throw U}}),this._remoteExtensions.has($)&&scheduleTask(this._ctx,async()=>{await this._openExtension($)})}_setExtension($,I){invariant(!$.includes("/"),"Invalid extension name",{F:__dxlog_file5$1,L:233,S:this,A:["!extensionName.includes('/')","'Invalid extension name'"]}),invariant(!this._extensions.has($),"Extension already exists",{F:__dxlog_file5$1,L:234,S:this,A:["!this._extensions.has(extensionName)","'Extension already exists'"]}),this._extensions.set($,I)}async _openExtension($){log$2("open extension",{extensionName:$},{F:__dxlog_file5$1,L:239,S:this,C:(q,G)=>q(...G)});const I=this._extensions.get($)??failUndefined(),U={initiator:this.initiator,localPeerId:this.localPeerId,remotePeerId:this.remotePeerId,createPort:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:247,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createPort(`${$}/${q}`,G)),createStream:async(q,G)=>(invariant(!q.includes("/"),"Invalid channel name",{F:__dxlog_file5$1,L:251,S:this,A:["!channelName.includes('/')","'Invalid channel name'"]}),this._muxer.createStream(`${$}/${q}`,G)),close:q=>{runInContextAsync(this._ctx,async()=>{await this.close(q)})}};await I.onOpen(U),log$2("extension opened",{extensionName:$},{F:__dxlog_file5$1,L:262,S:this,C:(q,G)=>q(...G)})}};_ts_decorate2$2([logInfo],Teleport.prototype,"sessionIdString",null),_ts_decorate2$2([synchronized],Teleport.prototype,"abort",null),_ts_decorate2$2([synchronized],Teleport.prototype,"destroy",null);var __require=($=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy($,{get:(I,U)=>(typeof require<"u"?require:I)[U]}):$)(function($){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+$+'" is not supported')});function _ts_decorate$2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$3="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/connection.ts",STARTING_SIGNALLING_DELAY=10,TRANSPORT_CONNECTION_TIMEOUT=1e4,TRANSPORT_STATS_INTERVAL=5e3,MAX_SIGNALLING_DELAY=300,ConnectionState;(function($){$.CREATED="CREATED",$.INITIAL="INITIAL",$.CONNECTING="CONNECTING",$.CONNECTED="CONNECTED",$.CLOSING="CLOSING",$.CLOSED="CLOSED",$.ABORTING="ABORTING",$.ABORTED="ABORTED"})(ConnectionState||(ConnectionState={}));var Connection=class{constructor($,I,U,q,G,K,Y,J,X){this.topic=$,this.ownId=I,this.remoteId=U,this.sessionId=q,this.initiator=G,this._signalMessaging=K,this._protocol=Y,this._transportFactory=J,this._callbacks=X,this._ctx=new Context,this.connectedTimeoutContext=new Context,this._state="CREATED",this._incomingSignalBuffer=[],this._outgoingSignalBuffer=[],this.stateChanged=new Event$1,this.errors=new ErrorStream,this._instanceId=PublicKey.random().toHex(),this.transportStats=new Event$1,this._signalSendTask=new DeferredTask(this._ctx,async()=>{await this._flushSignalBuffer()}),this._signallingDelay=STARTING_SIGNALLING_DELAY,log$2.trace("dxos.mesh.connection.construct",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:134,S:this,C:(Z,Q)=>Z(...Q)})}get sessionIdString(){return this.sessionId.truncate()}get state(){return this._state}get transport(){return this._transport}get protocol(){return this._protocol}async openConnection(){invariant(this._state==="INITIAL","Invalid state.",{F:__dxlog_file$3,L:164,S:this,A:["this._state === ConnectionState.INITIAL","'Invalid state.'"]}),log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file$3,L:165,S:this,C:($,I)=>$(...I)}),log$2.trace("dxos.mesh.connection.open",{sessionId:this.sessionId,topic:this.topic,localPeerId:this.ownId,remotePeerId:this.remoteId,initiator:this.initiator},{F:__dxlog_file$3,L:166,S:this,C:($,I)=>$(...I)}),this._changeState("CONNECTING"),this._protocol.open(this.sessionId).catch($=>{this.errors.raise($)}),this._protocol.stream.on("close",()=>{log$2("protocol stream closed",void 0,{F:__dxlog_file$3,L:183,S:this,C:($,I)=>$(...I)}),this.close(new protocols.ProtocolError("protocol stream closed")).catch($=>this.errors.raise($))}),scheduleTask(this.connectedTimeoutContext,async()=>{log$2.info(`timeout waiting ${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect, aborting`,void 0,{F:__dxlog_file$3,L:190,S:this,C:($,I)=>$(...I)}),await this.abort(new protocols.TimeoutError(`${TRANSPORT_CONNECTION_TIMEOUT/1e3}s for transport to connect`)).catch($=>this.errors.raise($))},TRANSPORT_CONNECTION_TIMEOUT),invariant(!this._transport,void 0,{F:__dxlog_file$3,L:198,S:this,A:["!this._transport",""]}),this._transport=this._transportFactory.createTransport({initiator:this.initiator,stream:this._protocol.stream,sendSignal:async $=>this._sendSignal($),sessionId:this.sessionId}),await this._transport.open(),this._transport.connected.once(async()=>{var $,I;this._changeState("CONNECTED"),await this.connectedTimeoutContext.dispose(),(I=($=this._callbacks)==null?void 0:$.onConnected)==null||I.call($),scheduleTaskInterval(this._ctx,async()=>this._emitTransportStats(),TRANSPORT_STATS_INTERVAL)}),this._transport.closed.once(()=>{this._transport=void 0,log$2("abort triggered by transport close",void 0,{F:__dxlog_file$3,L:218,S:this,C:($,I)=>$(...I)}),this.abort().catch($=>this.errors.raise($))}),this._transport.errors.handle(async $=>{log$2("transport error:",{err:$},{F:__dxlog_file$3,L:223,S:this,C:(I,U)=>I(...U)}),this.closeReason||(this.closeReason=$==null?void 0:$.message),$ instanceof protocols.ConnectionResetError?(log$2.info("aborting due to transport ConnectionResetError",void 0,{F:__dxlog_file$3,L:230,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.ConnectivityError?(log$2.info("aborting due to transport ConnectivityError",void 0,{F:__dxlog_file$3,L:233,S:this,C:(I,U)=>I(...U)}),this.abort().catch(I=>this.errors.raise(I))):$ instanceof protocols.UnknownProtocolError&&log$2.warn("unsure what to do with UnknownProtocolError, will keep on truckin",{err:$},{F:__dxlog_file$3,L:236,S:this,C:(I,U)=>I(...U)}),this._state!=="CLOSED"&&this._state!=="CLOSING"&&(await this.connectedTimeoutContext.dispose(),this.errors.raise($))});for(const $ of this._incomingSignalBuffer)this._transport.onSignal($);this._incomingSignalBuffer=[],log$2.trace("dxos.mesh.connection.open-connection",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file$3,L:252,S:this,C:($,I)=>$(...I)})}async abort($){var I,U,q;if(log$2("aborting...",{err:$},{F:__dxlog_file$3,L:259,S:this,C:(G,K)=>G(...K)}),this._state==="CLOSED"||this._state==="ABORTED"){log$2(`abort ignored: already ${this._state}`,this.closeReason,{F:__dxlog_file$3,L:261,S:this,C:(G,K)=>G(...K)});return}await this.connectedTimeoutContext.dispose(),this._changeState("ABORTING"),this.closeReason||(this.closeReason=$==null?void 0:$.message),await this._ctx.dispose();try{log$2("aborting protocol... ",void 0,{F:__dxlog_file$3,L:275,S:this,C:(G,K)=>G(...K)}),await this._protocol.abort()}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:278,S:this,C:(K,Y)=>K(...Y)})}try{await((I=this._transport)==null?void 0:I.close())}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:285,S:this,C:(K,Y)=>K(...Y)})}try{(q=(U=this._callbacks)==null?void 0:U.onClosed)==null||q.call(U,$)}catch(G){log$2.catch(G,void 0,{F:__dxlog_file$3,L:291,S:this,C:(K,Y)=>K(...Y)})}this._changeState("ABORTED")}async close($){var U,q,G,K;if(this.closeReason?this.closeReason+=`; ${$==null?void 0:$.message}`:this.closeReason=$==null?void 0:$.message,this._state==="CLOSED"||this._state==="ABORTING"||this._state==="ABORTED")return;const I=this._state;if(this._changeState("CLOSING"),await this.connectedTimeoutContext.dispose(),await this._ctx.dispose(),log$2("closing...",{peerId:this.ownId},{F:__dxlog_file$3,L:316,S:this,C:(Y,J)=>Y(...J)}),I==="CONNECTED"){try{await this._protocol.close()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:323,S:this,C:(J,X)=>J(...X)})}try{await((U=this._transport)==null?void 0:U.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:330,S:this,C:(J,X)=>J(...X)})}}else{log$2.info(`graceful close requested when we were in ${I} state? aborting`,void 0,{F:__dxlog_file$3,L:333,S:this,C:(Y,J)=>Y(...J)});try{await this._protocol.abort()}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:337,S:this,C:(J,X)=>J(...X)})}try{await((q=this._transport)==null?void 0:q.close())}catch(Y){log$2.catch(Y,void 0,{F:__dxlog_file$3,L:342,S:this,C:(J,X)=>J(...X)})}}log$2("closed",{peerId:this.ownId},{F:__dxlog_file$3,L:346,S:this,C:(Y,J)=>Y(...J)}),this._changeState("CLOSED"),(K=(G=this._callbacks)==null?void 0:G.onClosed)==null||K.call(G,$)}_sendSignal($){this._outgoingSignalBuffer.push($),this._signalSendTask.schedule()}async _flushSignalBuffer(){var $;if(this._outgoingSignalBuffer.length!==0)try{await cancelWithContext(this._ctx,sleep(this._signallingDelay)),this._signallingDelay=Math.min(this._signallingDelay*2,MAX_SIGNALLING_DELAY);const I=[...this._outgoingSignalBuffer];this._outgoingSignalBuffer.length=0,await this._signalMessaging.signal({author:this.ownId,recipient:this.remoteId,sessionId:this.sessionId,topic:this.topic,data:{signalBatch:{signals:I}}})}catch(I){if(I instanceof protocols.CancelledError||I instanceof Error&&(($=I.message)!=null&&$.includes("CANCELLED")))return;log$2.info("signal message failed to deliver",{err:I},{F:__dxlog_file$3,L:384,S:this,C:(U,q)=>U(...q)}),await this.close(new protocols.ConnectivityError("signal message failed to deliver",I))}}async signal($){var U,q;if(invariant($.sessionId,void 0,{F:__dxlog_file$3,L:393,S:this,A:["msg.sessionId",""]}),!$.sessionId.equals(this.sessionId)){log$2("dropping signal for incorrect session id",void 0,{F:__dxlog_file$3,L:395,S:this,C:(G,K)=>G(...K)});return}invariant($.data.signal||$.data.signalBatch,void 0,{F:__dxlog_file$3,L:398,S:this,A:["msg.data.signal || msg.data.signalBatch",""]}),invariant((U=$.author)==null?void 0:U.equals(this.remoteId),void 0,{F:__dxlog_file$3,L:399,S:this,A:["msg.author?.equals(this.remoteId)",""]}),invariant((q=$.recipient)==null?void 0:q.equals(this.ownId),void 0,{F:__dxlog_file$3,L:400,S:this,A:["msg.recipient?.equals(this.ownId)",""]});const I=$.data.signalBatch?$.data.signalBatch.signals??[]:[$.data.signal];for(const G of I)G&&(["CREATED","INITIAL"].includes(this.state)?(log$2("buffered signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:409,S:this,C:(K,Y)=>K(...Y)}),this._incomingSignalBuffer.push(G)):(invariant(this._transport,"Connection not ready to accept signals.",{F:__dxlog_file$3,L:412,S:this,A:["this._transport","'Connection not ready to accept signals.'"]}),log$2("received signal",{peerId:this.ownId,remoteId:this.remoteId,msg:$.data},{F:__dxlog_file$3,L:413,S:this,C:(K,Y)=>K(...Y)}),await this._transport.onSignal(G)))}initiate(){this._changeState("INITIAL")}_changeState($){log$2("stateChanged",{from:this._state,to:$,peerId:this.ownId},{F:__dxlog_file$3,L:424,S:this,C:(I,U)=>I(...U)}),invariant($!==this._state,"Already in this state.",{F:__dxlog_file$3,L:425,S:this,A:["state !== this._state","'Already in this state.'"]}),this._state=$,this.stateChanged.emit($)}async _emitTransportStats(){var I;const $=await((I=this.transport)==null?void 0:I.getStats());$&&this.transportStats.emit($)}};_ts_decorate$2([logInfo],Connection.prototype,"sessionIdString",null),_ts_decorate$2([synchronized],Connection.prototype,"abort",null),_ts_decorate$2([synchronized],Connection.prototype,"close",null);var __dxlog_file2$2="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts",SwarmMessage=protocols.schema.getCodecForType("dxos.mesh.swarm.SwarmMessage"),SwarmMessenger=class{constructor({sendMessage:$,onSignal:I,onOffer:U,topic:q}){this._ctx=new Context,this._offerRecords=new ComplexMap(G=>G.toHex()),this._sendMessage=$,this._onSignal=I,this._onOffer=U,this._topic=q}async receiveMessage({author:$,recipient:I,payload:U}){var G,K,Y,J;if(U.type_url!=="dxos.mesh.swarm.SwarmMessage")return;const q=SwarmMessage.decode(U.value);this._topic.equals(q.topic)&&(log$2("received",{from:$,to:I,msg:q},{F:__dxlog_file2$2,L:69,S:this,C:(X,Z)=>X(...Z)}),(G=q.data)!=null&&G.offer?await this._handleOffer({author:$,recipient:I,message:q}):(K=q.data)!=null&&K.answer?await this._resolveAnswers(q):(Y=q.data)!=null&&Y.signal?await this._handleSignal({author:$,recipient:I,message:q}):(J=q.data)!=null&&J.signalBatch?await this._handleSignal({author:$,recipient:I,message:q}):log$2.warn("unknown message",{message:q},{F:__dxlog_file2$2,L:80,S:this,C:(X,Z)=>X(...Z)}))}async signal($){var I,U;invariant(((I=$.data)==null?void 0:I.signal)||((U=$.data)==null?void 0:U.signalBatch),"Invalid message",{F:__dxlog_file2$2,L:85,S:this,A:["message.data?.signal || message.data?.signalBatch","'Invalid message'"]}),await this._sendReliableMessage({author:$.author,recipient:$.recipient,message:$})}async offer($){const I={...$,messageId:PublicKey.random()};return new Promise((U,q)=>{this._offerRecords.set(I.messageId,{resolve:U}),this._sendReliableMessage({author:$.author,recipient:$.recipient,message:I}).catch(G=>q(G))})}async _sendReliableMessage({author:$,recipient:I,message:U}){const q={...U,messageId:U.messageId??PublicKey.random()};log$2("sending",{from:$,to:I,msg:q},{F:__dxlog_file2$2,L:123,S:this,C:(G,K)=>G(...K)}),await this._sendMessage({author:$,recipient:I,payload:{type_url:"dxos.mesh.swarm.SwarmMessage",value:SwarmMessage.encode(q)}})}async _resolveAnswers($){var U,q,G;invariant((q=(U=$.data)==null?void 0:U.answer)==null?void 0:q.offerMessageId,"No offerMessageId",{F:__dxlog_file2$2,L:135,S:this,A:["message.data?.answer?.offerMessageId","'No offerMessageId'"]});const I=this._offerRecords.get($.data.answer.offerMessageId);I&&(this._offerRecords.delete($.data.answer.offerMessageId),invariant((G=$.data)==null?void 0:G.answer,"No answer",{F:__dxlog_file2$2,L:139,S:this,A:["message.data?.answer","'No answer'"]}),log$2("resolving",{answer:$.data.answer},{F:__dxlog_file2$2,L:140,S:this,C:(K,Y)=>K(...Y)}),I.resolve($.data.answer))}async _handleOffer({author:$,recipient:I,message:U}){invariant(U.data.offer,"No offer",{F:__dxlog_file2$2,L:154,S:this,A:["message.data.offer","'No offer'"]});const q={author:$,recipient:I,...U,data:{offer:U.data.offer}},G=await this._onOffer(q);G.offerMessageId=U.messageId;try{await this._sendReliableMessage({author:I,recipient:$,message:{topic:U.topic,sessionId:U.sessionId,data:{answer:G}}})}catch(K){K instanceof protocols.TimeoutError?log$2.info("timeout sending answer to offer",{err:K},{F:__dxlog_file2$2,L:175,S:this,C:(Y,J)=>Y(...J)}):log$2.info("error sending answer to offer",{err:K},{F:__dxlog_file2$2,L:177,S:this,C:(Y,J)=>Y(...J)})}}async _handleSignal({author:$,recipient:I,message:U}){invariant(U.messageId,void 0,{F:__dxlog_file2$2,L:191,S:this,A:["message.messageId",""]}),invariant(U.data.signal||U.data.signalBatch,"Invalid message",{F:__dxlog_file2$2,L:192,S:this,A:["message.data.signal || message.data.signalBatch","'Invalid message'"]});const q={author:$,recipient:I,...U,data:{signal:U.data.signal,signalBatch:U.data.signalBatch}};await this._onSignal(q)}};function _ts_decorate2$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file3="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/peer.ts",ConnectionDisplacedError=class extends protocols.SystemError{constructor(){super("Connection displaced by remote initiator.")}},CONNECTION_COUNTS_STABLE_AFTER=5e3,Peer=class{constructor($,I,U,q,G,K,Y,J){this.id=$,this.topic=I,this.localPeerId=U,this._signalMessaging=q,this._protocolProvider=G,this._transportFactory=K,this._connectionLimiter=Y,this._callbacks=J,this._availableAfter=0,this.availableToConnect=!0,this._ctx=new Context,this.advertizing=!1,this.initiating=!1,this.connectionDisplaced=new Event$1}async onOffer($){var U;const I=$.author;if(this.connection&&![ConnectionState.CREATED,ConnectionState.INITIAL,ConnectionState.CONNECTING].includes(this.connection.state))return log$2.info(`received offer when connection already in ${this.connection.state} state`,void 0,{F:__dxlog_file3,L:114,S:this,C:(q,G)=>q(...G)}),{accept:!1};if(this.connection||this.initiating)if(I.toHex()<this.localPeerId.toHex())log$2("close local connection",{localPeerId:this.id,topic:this.topic,remotePeerId:this.localPeerId,sessionId:(U=this.connection)==null?void 0:U.sessionId},{F:__dxlog_file3,L:123,S:this,C:(q,G)=>q(...G)}),this.connection&&await this.closeConnection(new ConnectionDisplacedError);else return{accept:!1};if(await this._callbacks.onOffer(I)&&!this.connection){invariant($.sessionId,void 0,{F:__dxlog_file3,L:143,S:this,A:["message.sessionId",""]});const q=this._createConnection(!1,$.sessionId);try{await this._connectionLimiter.connecting($.sessionId),q.initiate(),await q.openConnection()}catch(G){G instanceof protocols.CancelledError||log$2.info("connection error",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,err:G},{F:__dxlog_file3,L:153,S:this,C:(K,Y)=>K(...Y)}),await this.closeConnection(G)}return{accept:!0}}return{accept:!1}}async initiateConnection(){invariant(!this.initiating,"Initiation in progress.",{F:__dxlog_file3,L:170,S:this,A:["!this.initiating","'Initiation in progress.'"]}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3,L:171,S:this,A:["!this.connection","'Already connected.'"]});const $=PublicKey.random();log$2("initiating...",{id:this.id,topic:this.topic,peerId:this.id,sessionId:$},{F:__dxlog_file3,L:173,S:this,C:(q,G)=>q(...G)});const I=this._createConnection(!0,$);this.initiating=!0;let U;try{if(await this._connectionLimiter.connecting($),I.initiate(),U=await this._signalMessaging.offer({author:this.localPeerId,recipient:this.id,sessionId:$,topic:this.topic,data:{offer:{}}}),log$2("received",{answer:U,topic:this.topic,ownId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:190,S:this,C:(q,G)=>q(...G)}),I.state!==ConnectionState.INITIAL){log$2("ignoring response",void 0,{F:__dxlog_file3,L:192,S:this,C:(q,G)=>q(...G)});return}}catch(q){throw log$2("initiation error: send offer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:196,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{if(!U.accept){this._callbacks.onRejected();return}}catch(q){throw log$2("initiation error: accept answer",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:209,S:this,C:(G,K)=>G(...K)}),await I.abort(q),q}finally{this.initiating=!1}try{log$2("opening connection as initiator",void 0,{F:__dxlog_file3,L:222,S:this,C:(q,G)=>q(...G)}),await I.openConnection(),this._callbacks.onAccepted()}catch(q){throw log$2("initiation error: open connection",{err:q,topic:this.topic,peerId:this.localPeerId,remoteId:this.id},{F:__dxlog_file3,L:226,S:this,C:(G,K)=>G(...K)}),log$2.warn("closing connection due to unhandled error on openConnection",{err:q},{F:__dxlog_file3,L:233,S:this,C:(G,K)=>G(...K)}),await this.closeConnection(q),q}finally{this.initiating=!1}}_createConnection($,I){var q;log$2("creating connection",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,sessionId:I},{F:__dxlog_file3,L:247,S:this,C:(G,K)=>G(...K)}),invariant(!this.connection,"Already connected.",{F:__dxlog_file3,L:254,S:this,A:["!this.connection","'Already connected.'"]});const U=new Connection(this.topic,this.localPeerId,this.id,I,$,this._signalMessaging,this._protocolProvider({initiator:$,localPeerId:this.localPeerId,remotePeerId:this.id,topic:this.topic}),this._transportFactory,{onConnected:()=>{this.availableToConnect=!0,this._lastConnectionTime=Date.now(),this._callbacks.onConnected(),this._connectionLimiter.doneConnecting(I),log$2.trace("dxos.mesh.connection.connected",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3,L:273,S:this,C:(G,K)=>G(...K)})},onClosed:G=>{log$2("connection closed",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$},{F:__dxlog_file3,L:282,S:this,C:(K,Y)=>K(...Y)}),this._connectionLimiter.doneConnecting(I),invariant(this.connection===U,"Connection mismatch (race condition).",{F:__dxlog_file3,L:287,S:this,A:["this.connection === connection","'Connection mismatch (race condition).'"]}),log$2.trace("dxos.mesh.connection.closed",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$},{F:__dxlog_file3,L:289,S:this,C:(K,Y)=>K(...Y)}),G instanceof ConnectionDisplacedError?this.connectionDisplaced.emit(this.connection):(this._lastConnectionTime&&this._lastConnectionTime+CONNECTION_COUNTS_STABLE_AFTER<Date.now()?this._availableAfter=0:(this.availableToConnect=!1,this._availableAfter=increaseInterval(this._availableAfter)),this._callbacks.onDisconnected(),scheduleTask(this._connectionCtx,()=>{this.availableToConnect=!0,this._callbacks.onPeerAvailable()},this._availableAfter)),this.connection=void 0}});return this._callbacks.onInitiated(U),(q=this._connectionCtx)==null||q.dispose(),this._connectionCtx=this._ctx.derive(),U.errors.handle(G=>{log$2.info("connection error, closing",{topic:this.topic,peerId:this.localPeerId,remoteId:this.id,initiator:$,err:G},{F:__dxlog_file3,L:329,S:this,C:(K,Y)=>K(...Y)}),log$2.trace("dxos.mesh.connection.error",{topic:this.topic,localPeerId:this.localPeerId,remotePeerId:this.id,sessionId:I,initiator:$,err:G},{F:__dxlog_file3,L:336,S:this,C:(K,Y)=>K(...Y)}),this.closeConnection(G)}),this.connection=U,U}async closeConnection($){if(!this.connection)return;const I=this.connection;log$2("closing...",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3,L:361,S:this,C:(U,q)=>U(...q)}),await I.close($),log$2("closed",{peerId:this.id,sessionId:I.sessionId},{F:__dxlog_file3,L:367,S:this,C:(U,q)=>U(...q)})}async onSignal($){if(!this.connection){log$2("dropping signal message for non-existent connection",{message:$},{F:__dxlog_file3,L:372,S:this,C:(I,U)=>I(...U)});return}await this.connection.signal($)}async destroy($){var I;await this._ctx.dispose(),log$2("Destroying peer",{peerId:this.id,topic:this.topic},{F:__dxlog_file3,L:382,S:this,C:(U,q)=>U(...q)}),await((I=this==null?void 0:this.connection)==null?void 0:I.close($))}};_ts_decorate2$1([synchronized],Peer.prototype,"destroy",null);var increaseInterval=$=>$===0?50:$<500?500:$<1e3?1e3:$<5e3?5e3:1e4;function _ts_decorate3$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file4$1="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/swarm/swarm.ts",INITIATION_DELAY=100,getClassName=$=>Object.getPrototypeOf($).constructor.name,Swarm=class{constructor($,I,U,q,G,K,Y,J,X=INITIATION_DELAY){this._topic=$,this._ownPeerId=I,this._topology=U,this._protocolProvider=q,this._messenger=G,this._transportFactory=K,this._label=Y,this._connectionLimiter=J,this._initiationDelay=X,this._ctx=new Context,this._listeningHandle=void 0,this._peers=new ComplexMap(PublicKey.hash),this._instanceId=PublicKey.random().toHex(),this.connectionAdded=new Event$1,this.disconnected=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.begin({id:this._instanceId,data:{topic:this._topic.toHex(),peerId:this._ownPeerId.toHex()}}),{F:__dxlog_file4$1,L:89,S:this,C:(Z,Q)=>Z(...Q)}),log$2("creating swarm",{peerId:I},{F:__dxlog_file4$1,L:93,S:this,C:(Z,Q)=>Z(...Q)}),U.init(this._getSwarmController()),this._swarmMessenger=new SwarmMessenger({sendMessage:async Z=>await this._messenger.sendMessage(Z),onSignal:async Z=>await this.onSignal(Z),onOffer:async Z=>await this.onOffer(Z),topic:this._topic}),log$2.trace("dxos.mesh.swarm.constructor",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file4$1,L:102,S:this,C:(Z,Q)=>Z(...Q)})}get connections(){return Array.from(this._peers.values()).map($=>$.connection).filter(isNotNullOrUndefined)}get ownPeerId(){return this._ownPeerId}get label(){return this._label}get topic(){return this._topic}async open(){invariant(!this._listeningHandle,void 0,{F:__dxlog_file4$1,L:129,S:this,A:["!this._listeningHandle",""]}),this._listeningHandle=await this._messenger.listen({peerId:this._ownPeerId,payloadType:"dxos.mesh.swarm.SwarmMessage",onMessage:async $=>{await this._swarmMessenger.receiveMessage($).catch(I=>log$2.info("Error while receiving message",{err:I},{F:__dxlog_file4$1,L:137,S:this,C:(U,q)=>U(...q)}))}})}async destroy(){var $;log$2("destroying...",void 0,{F:__dxlog_file4$1,L:143,S:this,C:(I,U)=>I(...U)}),await(($=this._listeningHandle)==null?void 0:$.unsubscribe()),this._listeningHandle=void 0,await this._ctx.dispose(),await this._topology.destroy(),await Promise.all(Array.from(this._peers.keys()).map(I=>this._destroyPeer(I,"swarm destroyed"))),log$2("destroyed",void 0,{F:__dxlog_file4$1,L:150,S:this,C:(I,U)=>I(...U)})}async setTopology($){invariant(!this._ctx.disposed,"Swarm is offline",{F:__dxlog_file4$1,L:154,S:this,A:["!this._ctx.disposed","'Swarm is offline'"]}),$!==this._topology&&(log$2("setting topology",{previous:getClassName(this._topology),topology:getClassName($)},{F:__dxlog_file4$1,L:158,S:this,C:(I,U)=>I(...U)}),await this._topology.destroy(),this._topology=$,this._topology.init(this._getSwarmController()),this._topology.update())}onSwarmEvent($){var I;if(log$2("swarm event",{swarmEvent:$},{F:__dxlog_file4$1,L:171,S:this,C:(U,q)=>U(...q)}),this._ctx.disposed){log$2("swarm event ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:174,S:this,C:(U,q)=>U(...q)});return}if($.peerAvailable){const U=PublicKey.from($.peerAvailable.peer);if(log$2("new peer",{peerId:U},{F:__dxlog_file4$1,L:180,S:this,C:(q,G)=>q(...G)}),!U.equals(this._ownPeerId)){const q=this._getOrCreatePeer(U);q.advertizing=!0}}else if($.peerLeft){const U=this._peers.get(PublicKey.from($.peerLeft.peer));U?(U.advertizing=!1,((I=U.connection)==null?void 0:I.state)!==ConnectionState.CONNECTED&&this._destroyPeer(U.id,"peer left").catch(q=>log$2.catch(q,void 0,{F:__dxlog_file4$1,L:191,S:this,C:(G,K)=>G(...K)}))):log$2("received peerLeft but no peer found",{peer:$.peerLeft.peer},{F:__dxlog_file4$1,L:194,S:this,C:(q,G)=>q(...G)})}this._topology.update()}async onOffer($){var q,G;if(log$2("offer",{message:$},{F:__dxlog_file4$1,L:203,S:this,C:(K,Y)=>K(...Y)}),this._ctx.disposed)return log$2("ignored for disposed swarm",void 0,{F:__dxlog_file4$1,L:205,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(invariant($.author,void 0,{F:__dxlog_file4$1,L:210,S:this,A:["message.author",""]}),!((q=$.recipient)!=null&&q.equals(this._ownPeerId)))return log$2("rejecting offer with incorrect peerId",{message:$},{F:__dxlog_file4$1,L:212,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};if(!((G=$.topic)!=null&&G.equals(this._topic)))return log$2("rejecting offer with incorrect topic",{message:$},{F:__dxlog_file4$1,L:216,S:this,C:(K,Y)=>K(...Y)}),{accept:!1};const U=await this._getOrCreatePeer($.author).onOffer($);return this._topology.update(),U}async onSignal($){var U,q;if(log$2("signal",{message:$},{F:__dxlog_file4$1,L:227,S:this,C:(G,K)=>G(...K)}),this._ctx.disposed){log$2.info("ignored for offline swarm",void 0,{F:__dxlog_file4$1,L:229,S:this,C:(G,K)=>G(...K)});return}invariant((U=$.recipient)==null?void 0:U.equals(this._ownPeerId),`Invalid signal peer id expected=${this.ownPeerId}, actual=${$.recipient}`,{F:__dxlog_file4$1,L:232,S:this,A:["message.recipient?.equals(this._ownPeerId)","`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"]}),invariant((q=$.topic)==null?void 0:q.equals(this._topic),void 0,{F:__dxlog_file4$1,L:236,S:this,A:["message.topic?.equals(this._topic)",""]}),invariant($.author,void 0,{F:__dxlog_file4$1,L:237,S:this,A:["message.author",""]}),await this._getOrCreatePeer($.author).onSignal($)}async goOffline(){await this._ctx.dispose(),await Promise.all([...this._peers.keys()].map($=>this._destroyPeer($,"goOffline")))}async goOnline(){this._ctx=new Context}_getOrCreatePeer($){let I=this._peers.get($);return I||(I=new Peer($,this._topic,this._ownPeerId,this._swarmMessenger,this._protocolProvider,this._transportFactory,this._connectionLimiter,{onInitiated:U=>{this.connectionAdded.emit(U)},onConnected:()=>{this.connected.emit($)},onDisconnected:async()=>{I.advertizing||await this._destroyPeer(I.id,"peer disconnected"),this.disconnected.emit($),this._topology.update()},onRejected:()=>{this._peers.has($)&&(log$2("peer rejected connection",{peerId:$},{F:__dxlog_file4$1,L:286,S:this,C:(U,q)=>U(...q)}),this._destroyPeer($,"peer rejected connection"))},onAccepted:()=>{this._topology.update()},onOffer:U=>this._topology.onOffer(U),onPeerAvailable:()=>{this._topology.update()}}),this._peers.set($,I)),I}async _destroyPeer($,I){invariant(this._peers.has($),void 0,{F:__dxlog_file4$1,L:308,S:this,A:["this._peers.has(peerId)",""]}),await this._peers.get($).destroy(new Error(I)),this._peers.delete($)}_getSwarmController(){return{getState:()=>({ownPeerId:this._ownPeerId,connected:Array.from(this._peers.values()).filter($=>$.connection).map($=>$.id),candidates:Array.from(this._peers.values()).filter($=>!$.connection&&$.advertizing&&$.availableToConnect).map($=>$.id)}),connect:$=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{try{await this._initiateConnection($)}catch(I){log$2("initiation error",I,{F:__dxlog_file4$1,L:334,S:this,C:(U,q)=>U(...q)})}})},disconnect:async $=>{this._ctx.disposed||scheduleTask(this._ctx,async()=>{await this._closeConnection($),this._topology.update()})}}}async _initiateConnection($){const I=this._ctx;if($.toHex()<this._ownPeerId.toHex()&&(log$2("initiation delay",{remoteId:$},{F:__dxlog_file4$1,L:361,S:this,C:(q,G)=>q(...G)}),await sleep(this._initiationDelay)),I.disposed)return;const U=this._getOrCreatePeer($);U.connection||(log$2("initiating connection...",{remoteId:$},{F:__dxlog_file4$1,L:375,S:this,C:(q,G)=>q(...G)}),await U.initiateConnection(),this._topology.update(),log$2("initiated",{remoteId:$},{F:__dxlog_file4$1,L:378,S:this,C:(q,G)=>q(...G)}))}async _closeConnection($){const I=this._peers.get($);I&&await I.closeConnection()}};_ts_decorate3$1([logInfo],Swarm.prototype,"_instanceId",void 0),_ts_decorate3$1([logInfo],Swarm.prototype,"ownPeerId",null),_ts_decorate3$1([logInfo],Swarm.prototype,"topic",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onSwarmEvent",null),_ts_decorate3$1([synchronized],Swarm.prototype,"onOffer",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOffline",null),_ts_decorate3$1([synchronized],Swarm.prototype,"goOnline",null);var EventType;(function($){$.CONNECTION_STATE_CHANGED="CONNECTION_STATE_CHANGED",$.PROTOCOL_ERROR="PROTOCOL_ERROR",$.PROTOCOL_EXTENSIONS_INITIALIZED="PROTOCOL_EXTENSIONS_INITIALIZED",$.PROTOCOL_EXTENSIONS_HANDSHAKE="PROTOCOL_EXTENSIONS_HANDSHAKE",$.PROTOCOL_HANDSHAKE="PROTOCOL_HANDSHAKE"})(EventType||(EventType={}));function _ts_decorate4$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file11="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/memory-transport.ts",MEMORY_TRANSPORT_DELAY=1,createStreamDelay=$=>new readableBrowserExports.Transform({objectMode:!0,transform:(I,U,q)=>{setTimeout(()=>q(null,I),$)}}),MemoryTransport=(Zn=class{constructor(I){this._options=I,this._instanceId=PublicKey.random(),this._remote=new Trigger,this._outgoingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._incomingDelay=createStreamDelay(MEMORY_TRANSPORT_DELAY),this._closed=!1,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream,invariant(!Zn._connections.has(this._instanceId),"Duplicate memory connection",{F:__dxlog_file11,L:64,S:this,A:["!MemoryTransport._connections.has(this._instanceId)","'Duplicate memory connection'"]}),Zn._connections.set(this._instanceId,this)}get isOpen(){return!this._closed}async open(){if(log$2("opening...",void 0,{F:__dxlog_file11,L:74,S:this,C:(I,U)=>I(...U)}),this._options.initiator){log$2("sending signal",void 0,{F:__dxlog_file11,L:78,S:this,C:(I,U)=>I(...U)});try{await this._options.sendSignal({payload:{transportId:this._instanceId.toHex()}})}catch(I){this._closed||this.errors.raise(toError(I))}}else this._remote.wait({timeout:this._options.timeout??1e3}).then(I=>{if(!this._closed){if(this._remoteInstanceId=I,this._remoteConnection=Zn._connections.get(this._remoteInstanceId),!this._remoteConnection){this._closed=!0,this.closed.emit();return}invariant(!this._remoteConnection._remoteConnection,`Remote already connected: ${this._remoteInstanceId}`,{F:__dxlog_file11,L:104,S:this,A:["!this._remoteConnection._remoteConnection","`Remote already connected: ${this._remoteInstanceId}`"]}),this._remoteConnection._remoteConnection=this,this._remoteConnection._remoteInstanceId=this._instanceId,log$2("connected",void 0,{F:__dxlog_file11,L:108,S:this,C:(U,q)=>U(...q)}),this._options.stream.pipe(this._outgoingDelay).pipe(this._remoteConnection._options.stream).pipe(this._incomingDelay).pipe(this._options.stream),this.connected.emit(),this._remoteConnection.connected.emit()}}).catch(I=>{this._closed||this.errors.raise(I)})}async close(){log$2("closing...",void 0,{F:__dxlog_file11,L:129,S:this,C:(I,U)=>I(...U)}),this._closed=!0,Zn._connections.delete(this._instanceId),this._remoteConnection&&(this._remoteConnection._closed=!0,Zn._connections.delete(this._remoteInstanceId),this._options.stream.unpipe(this._incomingDelay),this._incomingDelay.unpipe(this._remoteConnection._options.stream),this._remoteConnection._options.stream.unpipe(this._outgoingDelay),this._outgoingDelay.unpipe(this._options.stream),this._options.stream.unpipe(this._outgoingDelay),this._remoteConnection.closed.emit(),this._remoteConnection._remoteConnection=void 0,this._remoteConnection=void 0),this.closed.emit(),log$2("closed",void 0,{F:__dxlog_file11,L:157,S:this,C:(I,U)=>I(...U)})}async onSignal({payload:I}){if(log$2("received signal",{payload:I},{F:__dxlog_file11,L:161,S:this,C:(q,G)=>q(...G)}),!(I!=null&&I.transportId))return;const U=I.transportId;if(U){const q=PublicKey.fromHex(U);this._remote.wake(q)}}async getDetails(){return this._instanceId.toHex()}async getStats(){return{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0}}},Zn._connections=new ComplexMap(PublicKey.hash),Zn);_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_instanceId",void 0),_ts_decorate4$1([logInfo],MemoryTransport.prototype,"_remoteInstanceId",void 0);var toError=$=>$ instanceof Error?$:new Error(String($)),TransportKind;(function($){$.SIMPLE_PEER="SIMPLE_PEER",$.SIMPLE_PEER_PROXY="SIMPLE_PEER_PROXY",$.LIBDATACHANNEL="LIBDATACHANNEL",$.MEMORY="MEMORY",$.TCP="TCP"})(TransportKind||(TransportKind={}));var wrtc=null;try{wrtc=__require("@koush/wrtc")}catch{}function _ts_decorate5$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file15="/home/runner/work/dxos/dxos/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts",DATACHANNEL_LABEL="dxos.mesh.transport",MAX_BUFFERED_AMOUNT=64*1024,MAX_MESSAGE_SIZE=64*1024,LibDataChannelTransport=(rr=class{constructor(I){this._options=I,this._closed=!1,this._connected=!1,this._writeCallback=null,this._readyForCandidates=new Trigger,this.closed=new Event$1,this.connected=new Event$1,this.errors=new ErrorStream}get isOpen(){return!!this._peer&&!this._closed}async open(){this._closed&&this.errors.raise(new Error("connection already closed"));const{RTCPeerConnection:I}=(await importESM("node-datachannel/polyfill")).default;this._options.webrtcConfig?this._options.webrtcConfig.iceServers=this._options.webrtcConfig.iceServers??[]:this._options.webrtcConfig={iceServers:[]},this._peer=new I(this._options.webrtcConfig),this._peer.onicecandidateerror=U=>{log$2.error("peer.onicecandidateerror",{event:U},{F:__dxlog_file15,L:77,S:this,C:(q,G)=>q(...G)})},this._peer.onconnectionstatechange=U=>{var q;log$2.debug("peer.onconnectionstatechange",{event:U,peerConnectionState:(q=this._peer)==null?void 0:q.connectionState,transportConnectionState:this._connected},{F:__dxlog_file15,L:81,S:this,C:(G,K)=>G(...K)})},this._peer.onicecandidate=async U=>{if(log$2.debug("peer.onicecandidate",{event:U},{F:__dxlog_file15,L:91,S:this,C:(q,G)=>q(...G)}),U.candidate)try{await this._options.sendSignal({payload:{data:{type:"candidate",candidate:{candidate:U.candidate.candidate,sdpMLineIndex:U.candidate.sdpMLineIndex??0,sdpMid:U.candidate.sdpMid??0}}}})}catch(q){log$2.info("signaling error",{err:q},{F:__dxlog_file15,L:108,S:this,C:(G,K)=>G(...K)})}},this._options.initiator?(invariant(this._peer,"not open",{F:__dxlog_file15,L:114,S:this,A:["this._peer","'not open'"]}),this._peer.createOffer().then(async U=>{var q;this._closed||(((q=this._peer)==null?void 0:q.connectionState)!=="connecting"&&(log$2.error("peer not connecting",{peer:this._peer},{F:__dxlog_file15,L:125,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"))),log$2.debug("creating offer",{peer:this._peer,offer:U},{F:__dxlog_file15,L:129,S:this,C:(G,K)=>G(...K)}),await this._peer.setLocalDescription(U),await this._options.sendSignal({payload:{data:{type:U.type,sdp:U.sdp}}}))}).catch(U=>{this.errors.raise(U)}),this._handleChannel(this._peer.createDataChannel(DATACHANNEL_LABEL)),log$2.debug("created data channel",void 0,{F:__dxlog_file15,L:139,S:this,C:(U,q)=>U(...q)}),this._peer.ondatachannel=()=>{this.errors.raise(new Error("unexpected ondatachannel event for initiator"))}):this._peer.ondatachannel=U=>{log$2.debug("peer.ondatachannel (non-initiator)",{event:U},{F:__dxlog_file15,L:145,S:this,C:(q,G)=>q(...G)}),U.channel.label!==DATACHANNEL_LABEL&&this.errors.raise(new Error(`unexpected channel label ${U.channel.label}`)),this._handleChannel(U.channel)},rr._instanceCount++}async close(){await this._close(),--rr._instanceCount===0&&(await importESM("node-datachannel")).cleanup()}async _close(){var I;if(!this._closed){await this._disconnectStreams();try{(I=this._peer)==null||I.close()}catch(U){this.errors.raise(U)}this._peer=void 0,this._closed=!0,this.closed.emit()}}_handleChannel(I){this._channel=I,this._channel.onopen=()=>{log$2.debug("channel.onopen",void 0,{F:__dxlog_file15,L:190,S:this,C:(q,G)=>q(...G)});const U=new stream.Duplex({read:()=>{},write:async(q,G,K)=>{q.length>MAX_MESSAGE_SIZE&&this.errors.raise(new Error(`message too large: ${q.length} > ${MAX_MESSAGE_SIZE}`));try{I.send(q)}catch(Y){this.errors.raise(Y),await this._close()}this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT?(this._writeCallback!==null&&log$2.error("consumer trying to write before we are ready for more data",void 0,{F:__dxlog_file15,L:207,S:this,C:(Y,J)=>Y(...J)}),this._writeCallback=K):K()}});U.pipe(this._options.stream).pipe(U),this._stream=U,this._connected=!0,this.connected.emit()},this._channel.onclose=async U=>{log$2.info("channel.onclose",{err:U},{F:__dxlog_file15,L:223,S:this,C:(q,G)=>q(...G)}),await this._close()},this._channel.onerror=async U=>{this.errors.raise(new Error("channel error: "+U.toString())),await this._close()},this._channel.onbufferedamountlow=()=>{const U=this._writeCallback;this._writeCallback=null,U==null||U()},this._channel.onmessage=U=>{let q=U.data;q instanceof ArrayBuffer&&(q=export_Buffer.from(q)),this._stream.push(q)}}async onSignal(I){invariant(this._peer,"not open",{F:__dxlog_file15,L:249,S:this,A:["this._peer","'not open'"]});try{const U=I.payload.data;switch(U.type){case"offer":{if(this._peer.connectionState!=="new"){log$2.error("received offer but peer not in state new",{peer:this._peer},{F:__dxlog_file15,L:256,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));break}try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp});const q=await this._peer.createAnswer();await this._peer.setLocalDescription(q),await this._options.sendSignal({payload:{data:{type:q.type,sdp:q.sdp}}}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle offer from signalling server",{err:q},{F:__dxlog_file15,L:268,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling offer"))}break}case"answer":try{await this._peer.setRemoteDescription({type:U.type,sdp:U.sdp}),this._readyForCandidates.wake()}catch(q){log$2.error("cannot handle answer from signalling server",{err:q},{F:__dxlog_file15,L:279,S:this,C:(G,K)=>G(...K)}),this.errors.raise(new Error("error handling answer"))}break;case"candidate":await this._readyForCandidates.wait(),await this._peer.addIceCandidate({candidate:U.candidate.candidate});break;default:log$2.error("unhandled signal type",{type:U.type,signal:I},{F:__dxlog_file15,L:290,S:this,C:(q,G)=>q(...G)}),this.errors.raise(new Error(`unhandled signal type ${U.type}`))}}catch(U){log$2.catch(U,void 0,{F:__dxlog_file15,L:294,S:this,C:(q,G)=>q(...G)})}}async getDetails(){const I=await this._getStats(),U=I==null?void 0:I.remoteCandidate;return U?U.candidateType==="relay"?`${U.ip}:${U.port} relay for ${U.relatedAddress}:${U.relatedPort}`:`${U.ip}:${U.port} ${U.candidateType}`:"unavailable"}async getStats(){const I=await this._getStats();return I?{bytesSent:I.transport.bytesSent,bytesReceived:I.transport.bytesReceived,packetsSent:0,packetsReceived:0,rawStats:I.raw}:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0,rawStats:{}}}async _getStats(){invariant(this._peer,"not open",{F:__dxlog_file15,L:334,S:this,A:["this._peer","'not open'"]});const I=await this._peer.getStats(),U=Array.from(I.entries()),q=U.filter(J=>J[1].type==="transport")[0][1],G=U.filter(J=>J[0]===q.selectedCandidatePairId);let K,Y;return G.length>0&&(K=G[0][1],Y=U.filter(J=>J[0]===K.remoteCandidateId)[0][1]),{transport:q,selectedCandidatePair:K,remoteCandidate:Y,raw:Object.fromEntries(I)}}async _disconnectStreams(){var I,U,q,G;(G=(q=(U=(I=this._options.stream).unpipe)==null?void 0:U.call(I,this._stream))==null?void 0:q.unpipe)==null||G.call(q,this._options.stream)}},rr._instanceCount=0,rr);_ts_decorate5$1([synchronized],LibDataChannelTransport.prototype,"_close",null);var importESM=Function("path","return import(path)"),uaParser={exports:{}};(function($,I){(function(U,q){var G="1.0.35",K="",Y="?",J="function",X="undefined",Z="object",Q="string",ee="major",te="model",ne="name",ie="type",oe="vendor",ce="version",fe="architecture",se="console",de="mobile",ue="tablet",pe="smarttv",ve="wearable",me="embedded",be=350,_e="Amazon",Se="Apple",xe="ASUS",ke="BlackBerry",De="Browser",Be="Chrome",Ve="Edge",nt="Firefox",ot="Google",ft="Huawei",it="LG",ut="Microsoft",et="Motorola",Ue="Opera",We="Samsung",tt="Sharp",vt="Sony",je="Xiaomi",ze="Zebra",Ae="Facebook",Re="Chromium OS",Ce="Mac OS",ge=function(St,Ut){var le={};for(var re in St)Ut[re]&&Ut[re].length%2===0?le[re]=Ut[re].concat(St[re]):le[re]=St[re];return le},ye=function(St){for(var Ut={},le=0;le<St.length;le++)Ut[St[le].toUpperCase()]=St[le];return Ut},Me=function(St,Ut){return typeof St===Q?Ke(Ut).indexOf(Ke(St))!==-1:!1},Ke=function(St){return St.toLowerCase()},st=function(St){return typeof St===Q?St.replace(/[^\d\.]/g,K).split(".")[0]:q},dt=function(St,Ut){if(typeof St===Q)return St=St.replace(/^\s\s*/,K),typeof Ut===X?St:St.substring(0,be)},$t=function(St,Ut){for(var le=0,re,ae,he,we,Ee,Le;le<Ut.length&&!Ee;){var bt=Ut[le],Lt=Ut[le+1];for(re=ae=0;re<bt.length&&!Ee&&bt[re];)if(Ee=bt[re++].exec(St),Ee)for(he=0;he<Lt.length;he++)Le=Ee[++ae],we=Lt[he],typeof we===Z&&we.length>0?we.length===2?typeof we[1]==J?this[we[0]]=we[1].call(this,Le):this[we[0]]=we[1]:we.length===3?typeof we[1]===J&&!(we[1].exec&&we[1].test)?this[we[0]]=Le?we[1].call(this,Le,we[2]):q:this[we[0]]=Le?Le.replace(we[1],we[2]):q:we.length===4&&(this[we[0]]=Le?we[3].call(this,Le.replace(we[1],we[2])):q):this[we]=Le||q;le+=2}},Et=function(St,Ut){for(var le in Ut)if(typeof Ut[le]===Z&&Ut[le].length>0){for(var re=0;re<Ut[le].length;re++)if(Me(Ut[le][re],St))return le===Y?q:le}else if(Me(Ut[le],St))return le===Y?q:le;return St},rt={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},jt={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Gt={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[ce,[ne,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[ce,[ne,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[ne,ce],[/opios[\/ ]+([\w\.]+)/i],[ce,[ne,Ue+" Mini"]],[/\bopr\/([\w\.]+)/i],[ce,[ne,Ue]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(heytap|ovi)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[ne,ce],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[ce,[ne,"UC"+De]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[ce,[ne,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[ce,[ne,"WeChat"]],[/konqueror\/([\w\.]+)/i],[ce,[ne,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[ce,[ne,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[ce,[ne,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[ne,/(.+)/,"$1 Secure "+De],ce],[/\bfocus\/([\w\.]+)/i],[ce,[ne,nt+" Focus"]],[/\bopt\/([\w\.]+)/i],[ce,[ne,Ue+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[ce,[ne,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[ce,[ne,"Dolphin"]],[/coast\/([\w\.]+)/i],[ce,[ne,Ue+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[ce,[ne,"MIUI "+De]],[/fxios\/([-\w\.]+)/i],[ce,[ne,nt]],[/\bqihu|(qi?ho?o?|360)browser/i],[[ne,"360 "+De]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[ne,/(.+)/,"$1 "+De],ce],[/(comodo_dragon)\/([\w\.]+)/i],[[ne,/_/g," "],ce],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[ne,ce],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[ne],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[ne,Ae],ce],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[ne,ce],[/\bgsa\/([\w\.]+) .*safari\//i],[ce,[ne,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[ce,[ne,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[ce,[ne,Be+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[ne,Be+" WebView"],ce],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[ce,[ne,"Android "+De]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[ne,ce],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[ce,[ne,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[ce,ne],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[ne,[ce,Et,rt]],[/(webkit|khtml)\/([\w\.]+)/i],[ne,ce],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[ne,"Netscape"],ce],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[ce,[ne,nt+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[ne,ce],[/(cobalt)\/([\w\.]+)/i],[ne,[ce,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[fe,"amd64"]],[/(ia32(?=;))/i],[[fe,Ke]],[/((?:i[346]|x)86)[;\)]/i],[[fe,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[fe,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[fe,"armhf"]],[/windows (ce|mobile); ppc;/i],[[fe,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[fe,/ower/,K,Ke]],[/(sun4\w)[;\)]/i],[[fe,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[fe,Ke]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[te,[oe,We],[ie,ue]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[te,[oe,We],[ie,de]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[te,[oe,Se],[ie,de]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[te,[oe,Se],[ie,ue]],[/(macintosh);/i],[te,[oe,Se]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[te,[oe,tt],[ie,de]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[te,[oe,ft],[ie,ue]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[te,[oe,ft],[ie,de]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,de]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[te,/_/g," "],[oe,je],[ie,ue]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[te,[oe,"OPPO"],[ie,de]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[te,[oe,"Vivo"],[ie,de]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[te,[oe,"Realme"],[ie,de]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[te,[oe,et],[ie,de]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[te,[oe,et],[ie,ue]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[te,[oe,it],[ie,ue]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[te,[oe,it],[ie,de]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[te,[oe,"Lenovo"],[ie,ue]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[te,/_/g," "],[oe,"Nokia"],[ie,de]],[/(pixel c)\b/i],[te,[oe,ot],[ie,ue]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[te,[oe,ot],[ie,de]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[te,[oe,vt],[ie,de]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[te,"Xperia Tablet"],[oe,vt],[ie,ue]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[te,[oe,"OnePlus"],[ie,de]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[te,[oe,_e],[ie,ue]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[te,/(.+)/g,"Fire Phone $1"],[oe,_e],[ie,de]],[/(playbook);[-\w\),; ]+(rim)/i],[te,oe,[ie,ue]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[te,[oe,ke],[ie,de]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[te,[oe,xe],[ie,ue]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[te,[oe,xe],[ie,de]],[/(nexus 9)/i],[te,[oe,"HTC"],[ie,ue]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[oe,[te,/_/g," "],[ie,de]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[te,[oe,"Acer"],[ie,ue]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[te,[oe,"Meizu"],[ie,de]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[oe,te,[ie,de]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[oe,te,[ie,ue]],[/(surface duo)/i],[te,[oe,ut],[ie,ue]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[te,[oe,"Fairphone"],[ie,de]],[/(u304aa)/i],[te,[oe,"AT&T"],[ie,de]],[/\bsie-(\w*)/i],[te,[oe,"Siemens"],[ie,de]],[/\b(rct\w+) b/i],[te,[oe,"RCA"],[ie,ue]],[/\b(venue[\d ]{2,7}) b/i],[te,[oe,"Dell"],[ie,ue]],[/\b(q(?:mv|ta)\w+) b/i],[te,[oe,"Verizon"],[ie,ue]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[te,[oe,"Barnes & Noble"],[ie,ue]],[/\b(tm\d{3}\w+) b/i],[te,[oe,"NuVision"],[ie,ue]],[/\b(k88) b/i],[te,[oe,"ZTE"],[ie,ue]],[/\b(nx\d{3}j) b/i],[te,[oe,"ZTE"],[ie,de]],[/\b(gen\d{3}) b.+49h/i],[te,[oe,"Swiss"],[ie,de]],[/\b(zur\d{3}) b/i],[te,[oe,"Swiss"],[ie,ue]],[/\b((zeki)?tb.*\b) b/i],[te,[oe,"Zeki"],[ie,ue]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[oe,"Dragon Touch"],te,[ie,ue]],[/\b(ns-?\w{0,9}) b/i],[te,[oe,"Insignia"],[ie,ue]],[/\b((nxa|next)-?\w{0,9}) b/i],[te,[oe,"NextBook"],[ie,ue]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[oe,"Voice"],te,[ie,de]],[/\b(lvtel\-)?(v1[12]) b/i],[[oe,"LvTel"],te,[ie,de]],[/\b(ph-1) /i],[te,[oe,"Essential"],[ie,de]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[te,[oe,"Envizen"],[ie,ue]],[/\b(trio[-\w\. ]+) b/i],[te,[oe,"MachSpeed"],[ie,ue]],[/\btu_(1491) b/i],[te,[oe,"Rotor"],[ie,ue]],[/(shield[\w ]+) b/i],[te,[oe,"Nvidia"],[ie,ue]],[/(sprint) (\w+)/i],[oe,te,[ie,de]],[/(kin\.[onetw]{3})/i],[[te,/\./g," "],[oe,ut],[ie,de]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[te,[oe,ze],[ie,ue]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[te,[oe,ze],[ie,de]],[/smart-tv.+(samsung)/i],[oe,[ie,pe]],[/hbbtv.+maple;(\d+)/i],[[te,/^/,"SmartTV"],[oe,We],[ie,pe]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[oe,it],[ie,pe]],[/(apple) ?tv/i],[oe,[te,Se+" TV"],[ie,pe]],[/crkey/i],[[te,Be+"cast"],[oe,ot],[ie,pe]],[/droid.+aft(\w)( bui|\))/i],[te,[oe,_e],[ie,pe]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[te,[oe,tt],[ie,pe]],[/(bravia[\w ]+)( bui|\))/i],[te,[oe,vt],[ie,pe]],[/(mitv-\w{5}) bui/i],[te,[oe,je],[ie,pe]],[/Hbbtv.*(technisat) (.*);/i],[oe,te,[ie,pe]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[oe,dt],[te,dt],[ie,pe]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[ie,pe]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[oe,te,[ie,se]],[/droid.+; (shield) bui/i],[te,[oe,"Nvidia"],[ie,se]],[/(playstation [345portablevi]+)/i],[te,[oe,vt],[ie,se]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[te,[oe,ut],[ie,se]],[/((pebble))app/i],[oe,te,[ie,ve]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[te,[oe,Se],[ie,ve]],[/droid.+; (glass) \d/i],[te,[oe,ot],[ie,ve]],[/droid.+; (wt63?0{2,3})\)/i],[te,[oe,ze],[ie,ve]],[/(quest( 2| pro)?)/i],[te,[oe,Ae],[ie,ve]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[oe,[ie,me]],[/(aeobc)\b/i],[te,[oe,_e],[ie,me]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[te,[ie,de]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[te,[ie,ue]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[ie,ue]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[ie,de]],[/(android[-\w\. ]{0,9});.+buil/i],[te,[oe,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[ce,[ne,Ve+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[ce,[ne,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[ne,ce],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[ce,ne]],os:[[/microsoft (windows) (vista|xp)/i],[ne,ce],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[ne,[ce,Et,jt]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[ne,"Windows"],[ce,Et,jt]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/ios;fbsv\/([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[ce,/_/g,"."],[ne,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[ne,Ce],[ce,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[ce,ne],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[ne,ce],[/\(bb(10);/i],[ce,[ne,ke]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[ce,[ne,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[ce,[ne,nt+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[ce,[ne,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[ce,[ne,"watchOS"]],[/crkey\/([\d\.]+)/i],[ce,[ne,Be+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[ne,Re],ce],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[ne,ce],[/(sunos) ?([\w\.\d]*)/i],[[ne,"Solaris"],ce],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[ne,ce]]},At=function(St,Ut){if(typeof St===Z&&(Ut=St,St=q),!(this instanceof At))return new At(St,Ut).getResult();var le=typeof U!==X&&U.navigator?U.navigator:q,re=St||(le&&le.userAgent?le.userAgent:K),ae=le&&le.userAgentData?le.userAgentData:q,he=Ut?ge(Gt,Ut):Gt,we=le&&le.userAgent==re;return this.getBrowser=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.browser),Ee[ee]=st(Ee[ce]),we&&le&&le.brave&&typeof le.brave.isBrave==J&&(Ee[ne]="Brave"),Ee},this.getCPU=function(){var Ee={};return Ee[fe]=q,$t.call(Ee,re,he.cpu),Ee},this.getDevice=function(){var Ee={};return Ee[oe]=q,Ee[te]=q,Ee[ie]=q,$t.call(Ee,re,he.device),we&&!Ee[ie]&&ae&&ae.mobile&&(Ee[ie]=de),we&&Ee[te]=="Macintosh"&&le&&typeof le.standalone!==X&&le.maxTouchPoints&&le.maxTouchPoints>2&&(Ee[te]="iPad",Ee[ie]=ue),Ee},this.getEngine=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.engine),Ee},this.getOS=function(){var Ee={};return Ee[ne]=q,Ee[ce]=q,$t.call(Ee,re,he.os),we&&!Ee[ne]&&ae&&ae.platform!="Unknown"&&(Ee[ne]=ae.platform.replace(/chrome os/i,Re).replace(/macos/i,Ce)),Ee},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return re},this.setUA=function(Ee){return re=typeof Ee===Q&&Ee.length>be?dt(Ee,be):Ee,this},this.setUA(re),this};At.VERSION=G,At.BROWSER=ye([ne,ce,ee]),At.CPU=ye([fe]),At.DEVICE=ye([te,oe,ie,se,de,pe,ue,ve,me]),At.ENGINE=At.OS=ye([ne,ce]),$.exports&&(I=$.exports=At),I.UAParser=At;var zt=typeof U!==X&&(U.jQuery||U.Zepto);if(zt&&!zt.ua){var nn=new At;zt.ua=nn.getResult(),zt.ua.get=function(){return nn.getUA()},zt.ua.set=function(St){nn.setUA(St);var Ut=nn.getResult();for(var le in Ut)zt.ua[le]=Ut[le]}}})(typeof window=="object"?window:commonjsGlobal)})(uaParser,uaParser.exports);var uaParserExports=uaParser.exports,__dxlog_file$2="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/iframe.ts",browser,os$1;if(typeof navigator<"u"){const $=new uaParserExports.UAParser(navigator.userAgent);browser=$.getBrowser().name,os$1=$.getOS().name}var sendToIFrame=($,I,U)=>{if(!$.contentWindow){log$2("IFrame content window missing",{origin:I},{F:__dxlog_file$2,L:24,S:void 0,C:(q,G)=>q(...G)});return}browser==="Chrome"&&os$1==="iOS"?$.contentWindow.postMessage(U,I):$.contentWindow.postMessage(U,I,[U.payload])},sendToParentWindow=($,I)=>{browser==="Chrome"&&os$1==="iOS"?window.parent.postMessage(I,$):window.parent.postMessage(I,$,[I.payload])},createIFramePort=({channel:$,iframe:I,origin:U,onOrigin:q})=>({send:async G=>{if(!U){log$2("no origin set",{channel:$},{F:__dxlog_file$2,L:62,S:void 0,C:(J,X)=>J(...X)});return}log$2("sending",{channel:$,data:G.length},{F:__dxlog_file$2,L:66,S:void 0,C:(J,X)=>J(...X)});const K=G.buffer.slice(G.byteOffset,G.byteOffset+G.byteLength),Y={channel:$,payload:K};I?sendToIFrame(I,U,Y):sendToParentWindow(U,Y)},subscribe:G=>{const K=Y=>{if(!I&&Y.source!==window.parent)return;if(I&&Y.source!==I.contentWindow)return;const X=Y.data&&typeof Y.data=="object"&&"channel"in Y.data&&"payload"in Y.data?Y.data:void 0;(X==null?void 0:X.channel)===$&&(U||(U=Y.origin,q==null||q(U)),log$2("received",X,{F:__dxlog_file$2,L:98,S:void 0,C:(Z,Q)=>Z(...Q)}),G(new Uint8Array(X.payload)))};return window.addEventListener("message",K),()=>window.removeEventListener("message",K)}}),createIFrame=($,I,{hidden:U=!0,allow:q}={})=>{const G=()=>{const K=document.createElement("iframe");return K.id=I,K.src=$,U&&K.setAttribute("style","display: none;"),q&&K.setAttribute("allow",q),document.body.appendChild(K),K};return document.getElementById(I)??G()},__dxlog_file2$1="/home/runner/work/dxos/dxos/packages/core/mesh/rpc-tunnel/src/ports/worker.ts",createWorkerPort=({port:$,channel:I,subscribe:U})=>({send:async q=>{const G=q.buffer.slice(q.byteOffset,q.byteOffset+q.byteLength);$.postMessage({channel:I,payload:G},[G])},subscribe:U??(q=>{const G=K=>{const Y=K.data;I&&Y.channel!==I||(log$2.debug("Recieved message",Y,{F:__dxlog_file2$1,L:46,S:void 0,C:(J,X)=>J(...X)}),q(new Uint8Array(Y.payload)))};return $.onmessage=G,()=>{$.onmessage=null}})});function _ts_decorate$1($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file$1="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/agent.ts",getUnixSocket=($,I="unix")=>`${I}://`+clientProtocol.getProfilePath(clientProtocol.DX_RUNTIME,$,"agent.sock"),AgentClientServiceProvider=class{constructor($){this._profile=$,this.closed=new Event$1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._client.rpc}async open(){const{WebsocketRpcClient:$}=await Promise.resolve().then(()=>index);this._client=new $({url:getUnixSocket(this._profile,"ws+unix"),requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{}}),this._client.error.on(I=>{this.closed.emit(I)}),await this._client.open()}async close(){var $;try{await(($=this._client)==null?void 0:$.close())}catch(I){log$2.warn("Failed to close",I,{F:__dxlog_file$1,L:72,S:this,C:(U,q)=>U(...q)})}}};AgentClientServiceProvider=_ts_decorate$1([trace.resource({annotation:clientServices.ClientServicesProviderResource})],AgentClientServiceProvider);function _ts_decorate2($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var LocalClientServices=class{constructor($){this.closed=new Event$1,this._ctx=new Context,this.signalMetadataTags={runtime:"local-client-services"},this._isOpen=!1,this._params=$,typeof window>"u"?this.signalMetadataTags.origin="undefined":globalThis.__args?(this.signalMetadataTags.runtime="native",this.signalMetadataTags.origin=window.location.origin):this.signalMetadataTags.origin=window.location.origin}get descriptors(){return clientProtocol.clientServiceBundle}get services(){var $;return(($=this._host)==null?void 0:$.services)??{}}get host(){return this._host}async open(){if(this._isOpen)return;const{ClientServicesHost:$}=await import("@dxos/client-services");this._host=new $({...this._params,callbacks:{...this._params.callbacks,onReset:async()=>{var I,U;this.closed.emit(void 0),await((U=(I=this._params.callbacks)==null?void 0:I.onReset)==null?void 0:U.call(I))}}}),await this._host.open(this._ctx),this._isOpen=!0,setIdentityTags({identityService:this._host.services.IdentityService,devicesService:this._host.services.DevicesService,setTag:(I,U)=>{this.signalMetadataTags[I]=U}})}async close(){var $;this._isOpen&&(await(($=this._host)==null?void 0:$.close()),this._isOpen=!1)}};_ts_decorate2([trace.info()],LocalClientServices.prototype,"_isOpen",void 0),_ts_decorate2([synchronized],LocalClientServices.prototype,"open",null),_ts_decorate2([synchronized],LocalClientServices.prototype,"close",null),LocalClientServices=_ts_decorate2([trace.resource({annotation:clientServices.ClientServicesProviderResource})],LocalClientServices);var IFrameManager=class{constructor({source:$,onOpen:I,onMessage:U}){this._source=$,this._onOpen=I,this._onMessage=U,this._messageHandler=this._messageHandler.bind(this)}get source(){return this._source}get iframe(){return this._iframe}async open(){var I;if(this._iframe)return;window.addEventListener("message",this._messageHandler);const $=`__DXOS_CLIENT_${PublicKey.random().toHex()}__`;this._iframe=createIFrame(this._source.toString(),$,{allow:"clipboard-read; clipboard-write"}),await((I=this._onOpen)==null?void 0:I.call(this))}async close(){var $;window.removeEventListener("message",this._messageHandler),($=this._iframe)==null||$.remove(),this._iframe=void 0}async _messageHandler($){var I;(I=this._onMessage)==null||I.call(this,$)}},__dxlog_file4="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/shell-manager.ts",shellStyles=Object.entries({display:"none",position:"fixed",top:0,left:0,width:"100vw",height:"100vh",border:0,"z-index":60}).reduce(($,[I,U])=>`${$}${I}: ${U};`,""),ShellManager=class{constructor($,I=clientProtocol.DEFAULT_SHELL_CHANNEL){this._iframeManager=$,this._channel=I,this.contextUpdate=new Event$1,this._display=ShellDisplay.NONE}get display(){return this._display}async setLayout($){var I;log$2("set layout",$,{F:__dxlog_file4,L:51,S:this,C:(U,q)=>U(...q)}),this._display=ShellDisplay.FULLSCREEN,this.contextUpdate.emit({display:this._display}),await((I=this._shellRpc)==null?void 0:I.rpc.ShellService.setLayout($,{timeout:RPC_TIMEOUT}))}async open(){if(this._shellRpc)return;await this._iframeManager.open();const $=this._iframeManager.iframe;$.setAttribute("style",shellStyles),$.setAttribute("name","dxos-shell"),$.setAttribute("data-testid","dxos-shell"),this.contextUpdate.on(({display:q,reload:G})=>{G&&window.location.reload(),$.style.display=q===ShellDisplay.NONE?"none":"",q===ShellDisplay.NONE&&$.blur()});const I=this._iframeManager.source.origin==="null"?this._iframeManager.source.toString().split("/").slice(0,3).join("/"):this._iframeManager.source.origin,U=createIFramePort({origin:I,channel:this._channel,iframe:this._iframeManager.iframe});this._shellRpc=createProtoRpcPeer({requested:clientProtocol.shellServiceBundle,exposed:clientProtocol.appServiceBundle,handlers:{AppService:{setContext:async q=>{log$2("set context",q,{F:__dxlog_file4,L:98,S:this,C:(G,K)=>G(...K)}),q.display&&(this._display=q.display),this.contextUpdate.emit(q)}}},port:U}),await this._shellRpc.open()}async close(){var $;this._shellRpc&&(await(($=this._shellRpc)==null?void 0:$.close()),this._shellRpc=void 0)}};function _ts_decorate3($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var IFrameClientServicesHost=class{constructor({host:$,source:I=clientProtocol.DEFAULT_VAULT_URL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT}){this.closed=new Event$1,this._host=$,this._source=I,this._vault=U,this._timeout=q;const G=new Trigger;this._iframeManager=new IFrameManager({source:new URL(this._source,window.location.origin),onOpen:async()=>{var K,Y,J;await asyncTimeout(G.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(J=(Y=(K=this._iframeManager)==null?void 0:K.iframe)==null?void 0:Y.contentWindow)==null||J.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin)},onMessage:K=>{var X,Z,Q;const{channel:Y,payload:J}=K.data;if(Y===this._vault){if(J==="loaded")G.wake();else if(J==="client"){const ee=new MessageChannel,te=createBundledRpcServer({services:this._host.descriptors,handlers:this._host.services,port:createWorkerPort({port:ee.port1})});(Q=(Z=(X=this._iframeManager)==null?void 0:X.iframe)==null?void 0:Z.contentWindow)==null||Q.postMessage({channel:this._vault,payload:{command:"port",port:ee.port2}},this._iframeManager.source.origin,[ee.port2]),te.open()}}}}),this._shellManager=new ShellManager(this._iframeManager)}get descriptors(){return this._host.descriptors}get services(){return this._host.services}async open(){await this._host.open(new Context),await this._shellManager.open()}async close(){await this._shellManager.close(),await this._iframeManager.close(),await this._host.close(new Context)}};IFrameClientServicesHost=_ts_decorate3([trace.resource()],IFrameClientServicesHost);function _ts_decorate4($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file5="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/service-proxy.ts",ClientServicesProxy=class{constructor($,I=3e4){this._port=$,this._timeout=I,this.closed=new Event$1}get proxy(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file5,L:30,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return invariant(this._proxy,"Client services not open",{F:__dxlog_file5,L:39,S:this,A:["this._proxy","'Client services not open'"]}),this._proxy.rpc}async open(){this._proxy||(this._proxy=createProtoRpcPeer({requested:clientProtocol.clientServiceBundle,exposed:{},handlers:{},port:this._port}),await asyncTimeout(this._proxy.open(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Failed to establish dxrpc connection",{timeout:this._timeout})))}async close(){this._proxy&&(await this._proxy.close(),this._proxy=void 0)}};ClientServicesProxy=_ts_decorate4([trace.resource({annotation:clientServices.ClientServicesProviderResource})],ClientServicesProxy);function _ts_decorate5($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file6="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/iframe-service-proxy.ts",IFrameClientServicesProxy=class{constructor({source:$=clientProtocol.DEFAULT_VAULT_URL,shell:I=clientProtocol.DEFAULT_SHELL_CHANNEL,vault:U=clientProtocol.DEFAULT_INTERNAL_CHANNEL,timeout:q=clientProtocol.PROXY_CONNECTION_TIMEOUT,logFilter:G="error,warn"}={}){this.closed=new Event$1,this._instanceId=PublicKey.random().toHex(),this._source=$,this._shell=I,this._vault=U,this._logFilter=parseFilter(G),this._timeout=q;const K=new Trigger,Y=new Trigger;this._iframeManager=new IFrameManager({source:new URL(typeof this._shell=="string"?this._source:`${this._source}#disableshell`,window.location.origin),onOpen:async()=>{var X,Z;await asyncTimeout(K.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to load")),(Z=(X=this._iframeManager.iframe)==null?void 0:X.contentWindow)==null||Z.postMessage({channel:this._vault,payload:"init"},this._iframeManager.source.origin);const J=await asyncTimeout(Y.wait(),this._timeout,new protocols.RemoteServiceConnectionTimeout("Vault failed to provide MessagePort"));this._appPort=createWorkerPort({port:J})},onMessage:async J=>{const{channel:X,payload:Z}=J.data;X===this._vault&&(Z==="loaded"?K.wake():(Z==null?void 0:Z.command)==="init"&&Y.wake(Z.port))}}),typeof this._shell=="string"&&(this._shellManager=new ShellManager(this._iframeManager))}get proxy(){return this._clientServicesProxy.proxy}get descriptors(){return this._clientServicesProxy.descriptors}get services(){return this._clientServicesProxy.services}async open(){var $;this._clientServicesProxy||(log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.begin({id:this._instanceId}),{F:__dxlog_file6,L:142,S:this,C:(I,U)=>I(...U)}),await this._iframeManager.open(),this._clientServicesProxy=new ClientServicesProxy(this._appPort),await this._clientServicesProxy.open(),this._loggingStream=this._clientServicesProxy.services.LoggingService.queryLogs({filters:this._logFilter},{timeout:RPC_TIMEOUT}),this._loggingStream.subscribe(I=>{switch(I.level){case LogLevel.DEBUG:log$2.debug(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:157,S:this,C:(U,q)=>U(...q)});break;case LogLevel.INFO:log$2.info(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:160,S:this,C:(U,q)=>U(...q)});break;case LogLevel.WARN:log$2.warn(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:163,S:this,C:(U,q)=>U(...q)});break;case LogLevel.ERROR:log$2.error(`[vault] ${I.message}`,I.context,{F:__dxlog_file6,L:166,S:this,C:(U,q)=>U(...q)});break}}),await(($=this._shellManager)==null?void 0:$.open()))}async close(){var $,I,U;await(($=this._shellManager)==null?void 0:$.close()),await this._iframeManager.close(),await((I=this._loggingStream)==null?void 0:I.close()),await((U=this._clientServicesProxy)==null?void 0:U.close()),this._clientServicesProxy=void 0,log$2.trace("dxos.sdk.iframe-clientTraceices-proxy",protocols.trace.end({id:this._instanceId}),{F:__dxlog_file6,L:180,S:this,C:(q,G)=>q(...G)})}};IFrameClientServicesProxy=_ts_decorate5([trace.resource()],IFrameClientServicesProxy);function _ts_decorate6($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file8="/home/runner/work/dxos/dxos/packages/sdk/client/src/services/worker-client-services.ts",WorkerClientServices=class{constructor({config:$,createWorker:I,logFilter:U="error,warn",observabilityGroup:q,signalTelemetryEnabled:G}){this.closed=new Event$1,this.joinedSpace=new Event$1,this._isOpen=!1,this._config=$,this._createWorker=I,this._logFilter=parseFilter(U),this._observabilityGroup=q,this._signalTelemetryEnabled=G??!1}get descriptors(){return clientProtocol.clientServiceBundle}get services(){return this._services.services}get runtime(){return this._runtime}async open(){if(this._isOpen)return;log$2("opening...",void 0,{F:__dxlog_file8,L:88,S:this,C:(K,Y)=>K(...Y)});const{SharedWorkerConnection:$}=await import("@dxos/client-services"),I=new Trigger,U=this._createWorker();U.port.postMessage({dxlog:localStorage.getItem("dxlog")}),U.port.onmessage=K=>{const{command:Y,payload:J}=K.data;Y==="init"&&I.wake(J)};const{systemPort:q,appPort:G}=await I.wait();this._runtime=new $({config:this._config,systemPort:createWorkerPort({port:q})}),await this._runtime.open({origin:location.origin,observabilityGroup:this._observabilityGroup,signalTelemetryEnabled:this._signalTelemetryEnabled}),this._services=new ClientServicesProxy(createWorkerPort({port:G})),await this._services.open(),navigator.locks.request(LOCK_KEY,()=>{log$2("terminated",void 0,{F:__dxlog_file8,L:115,S:this,C:(K,Y)=>K(...Y)}),this._isOpen&&this.closed.emit(new Error("Shared worker terminated."))}),this._loggingStream=this._services.services.LoggingService.queryLogs({filters:this._logFilter},{timeout:RPC_TIMEOUT}),this._loggingStream.subscribe(K=>{switch(K.level){case LogLevel.DEBUG:log$2.debug(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.INFO:log$2.info(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.WARN:log$2.warn(K.message,K.context,mapLogMeta(K.meta));break;case LogLevel.ERROR:log$2.error(K.message,K.context,mapLogMeta(K.meta));break}}),log$2("opened",void 0,{F:__dxlog_file8,L:144,S:this,C:(K,Y)=>K(...Y)}),this._isOpen=!0}async close(){var $;this._isOpen&&(log$2("closing...",void 0,{F:__dxlog_file8,L:154,S:this,C:(I,U)=>I(...U)}),await(($=this._loggingStream)==null?void 0:$.close()),await this._runtime.close(),await this._services.close(),log$2("closed",void 0,{F:__dxlog_file8,L:159,S:this,C:(I,U)=>I(...U)}),this._isOpen=!1)}};_ts_decorate6([trace.info()],WorkerClientServices.prototype,"_isOpen",void 0),_ts_decorate6([synchronized],WorkerClientServices.prototype,"open",null),_ts_decorate6([synchronized],WorkerClientServices.prototype,"close",null),WorkerClientServices=_ts_decorate6([trace.resource()],WorkerClientServices);var mapLogMeta=$=>$&&{F:$.file,L:$.line,S:$.scope},i$1=Symbol.for("preact-signals");function t(){if(s$1>1)s$1--;else{for(var $,I=!1;h$1!==void 0;){var U=h$1;for(h$1=void 0,f++;U!==void 0;){var q=U.o;if(U.o=void 0,U.f&=-3,!(8&U.f)&&c(U))try{U.c()}catch(G){I||($=G,I=!0)}U=q}}if(f=0,s$1--,I)throw $}}var o=void 0,h$1=void 0,s$1=0,f=0,v$1=0;function e($){if(o!==void 0){var I=$.n;if(I===void 0||I.t!==o)return I={i:0,S:$,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:I},o.s!==void 0&&(o.s.n=I),o.s=I,$.n=I,32&o.f&&$.S(I),I;if(I.i===-1)return I.i=0,I.n!==void 0&&(I.n.p=I.p,I.p!==void 0&&(I.p.n=I.n),I.p=o.s,I.n=void 0,o.s.n=I,o.s=I),I}}function u($){this.v=$,this.i=0,this.n=void 0,this.t=void 0}u.prototype.brand=i$1,u.prototype.h=function(){return!0},u.prototype.S=function($){this.t!==$&&$.e===void 0&&($.x=this.t,this.t!==void 0&&(this.t.e=$),this.t=$)},u.prototype.U=function($){if(this.t!==void 0){var I=$.e,U=$.x;I!==void 0&&(I.x=U,$.e=void 0),U!==void 0&&(U.e=I,$.x=void 0),$===this.t&&(this.t=U)}},u.prototype.subscribe=function($){var I=this;return E(function(){var U=I.value,q=o;o=void 0;try{$(U)}finally{o=q}})},u.prototype.valueOf=function(){return this.value},u.prototype.toString=function(){return this.value+""},u.prototype.toJSON=function(){return this.value},u.prototype.peek=function(){var $=o;o=void 0;try{return this.value}finally{o=$}},Object.defineProperty(u.prototype,"value",{get:function(){var $=e(this);return $!==void 0&&($.i=this.i),this.v},set:function($){if($!==this.v){if(f>100)throw new Error("Cycle detected");this.v=$,this.i++,v$1++,s$1++;try{for(var I=this.t;I!==void 0;I=I.x)I.t.N()}finally{t()}}}});function c($){for(var I=$.s;I!==void 0;I=I.n)if(I.S.i!==I.i||!I.S.h()||I.S.i!==I.i)return!0;return!1}function a($){for(var I=$.s;I!==void 0;I=I.n){var U=I.S.n;if(U!==void 0&&(I.r=U),I.S.n=I,I.i=-1,I.n===void 0){$.s=I;break}}}function l($){for(var I=$.s,U=void 0;I!==void 0;){var q=I.p;I.i===-1?(I.S.U(I),q!==void 0&&(q.n=I.n),I.n!==void 0&&(I.n.p=q)):U=I,I.S.n=I.r,I.r!==void 0&&(I.r=void 0),I=q}$.s=U}function y($){u.call(this,void 0),this.x=$,this.s=void 0,this.g=v$1-1,this.f=4}(y.prototype=new u).h=function(){if(this.f&=-3,1&this.f)return!1;if((36&this.f)==32||(this.f&=-5,this.g===v$1))return!0;if(this.g=v$1,this.f|=1,this.i>0&&!c(this))return this.f&=-2,!0;var $=o;try{a(this),o=this;var I=this.x();(16&this.f||this.v!==I||this.i===0)&&(this.v=I,this.f&=-17,this.i++)}catch(U){this.v=U,this.f|=16,this.i++}return o=$,l(this),this.f&=-2,!0},y.prototype.S=function($){if(this.t===void 0){this.f|=36;for(var I=this.s;I!==void 0;I=I.n)I.S.S(I)}u.prototype.S.call(this,$)},y.prototype.U=function($){if(this.t!==void 0&&(u.prototype.U.call(this,$),this.t===void 0)){this.f&=-33;for(var I=this.s;I!==void 0;I=I.n)I.S.U(I)}},y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var $=this.t;$!==void 0;$=$.x)$.t.N()}},Object.defineProperty(y.prototype,"value",{get:function(){if(1&this.f)throw new Error("Cycle detected");var $=e(this);if(this.h(),$!==void 0&&($.i=this.i),16&this.f)throw this.v;return this.v}});function _($){var I=$.u;if($.u=void 0,typeof I=="function"){s$1++;var U=o;o=void 0;try{I()}catch(q){throw $.f&=-2,$.f|=8,g($),q}finally{o=U,t()}}}function g($){for(var I=$.s;I!==void 0;I=I.n)I.S.U(I);$.x=void 0,$.s=void 0,_($)}function p$1($){if(o!==this)throw new Error("Out-of-order effect");l(this),o=$,this.f&=-2,8&this.f&&g(this),t()}function b$1($){this.x=$,this.u=void 0,this.s=void 0,this.o=void 0,this.f=32}b$1.prototype.c=function(){var $=this.S();try{if(8&this.f||this.x===void 0)return;var I=this.x();typeof I=="function"&&(this.u=I)}finally{$()}},b$1.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1,this.f&=-9,_(this),a(this),s$1++;var $=o;return o=this,p$1.bind(this,$)},b$1.prototype.N=function(){2&this.f||(this.f|=2,this.o=h$1,h$1=this)},b$1.prototype.d=function(){this.f|=8,1&this.f||g(this)};function E($){var I=new b$1($);try{I.c()}catch(U){throw I.d(),U}return I.d.bind(I)}var shim={exports:{}},useSyncExternalStoreShim_production_min={};/**
|
|
924
924
|
* @license React
|
|
925
925
|
* use-sync-external-store-shim.production.min.js
|
|
926
926
|
*
|
|
@@ -936,7 +936,7 @@ Use Chrome, Firefox or Internet Explorer 11`)}var Buffer$2=requireSafeBuffer().B
|
|
|
936
936
|
*
|
|
937
937
|
* This source code is licensed under the MIT license found in the
|
|
938
938
|
* LICENSE file in the root directory of this source tree.
|
|
939
|
-
*/var hasRequiredUseSyncExternalStoreShim_development;function requireUseSyncExternalStoreShim_development(){return hasRequiredUseSyncExternalStoreShim_development||(hasRequiredUseSyncExternalStoreShim_development=1,process.env.NODE_ENV!=="production"&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var $=React,I=$.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function U(de){{for(var ue=arguments.length,pe=new Array(ue>1?ue-1:0),ve=1;ve<ue;ve++)pe[ve-1]=arguments[ve];q("error",de,pe)}}function q(de,ue,pe){{var ve=I.ReactDebugCurrentFrame,me=ve.getStackAddendum();me!==""&&(ue+="%s",pe=pe.concat([me]));var be=pe.map(function(_e){return String(_e)});be.unshift("Warning: "+ue),Function.prototype.apply.call(console[de],console,be)}}function G(de,ue){return de===ue&&(de!==0||1/de===1/ue)||de!==de&&ue!==ue}var K=typeof Object.is=="function"?Object.is:G,Y=$.useState,J=$.useEffect,X=$.useLayoutEffect,Z=$.useDebugValue,Q=!1,ee=!1;function te(de,ue,pe){Q||$.startTransition!==void 0&&(Q=!0,U("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var ve=ue();if(!ee){var me=ue();K(ve,me)||(U("The result of getSnapshot should be cached to avoid an infinite loop"),ee=!0)}var be=Y({inst:{value:ve,getSnapshot:ue}}),_e=be[0].inst,Se=be[1];return X(function(){_e.value=ve,_e.getSnapshot=ue,ne(_e)&&Se({inst:_e})},[de,ve,ue]),J(function(){ne(_e)&&Se({inst:_e});var xe=function(){ne(_e)&&Se({inst:_e})};return de(xe)},[de]),Z(ve),ve}function ne(de){var ue=de.getSnapshot,pe=de.value;try{var ve=ue();return!K(pe,ve)}catch{return!0}}function ie(de,ue,pe){return ue()}var oe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ce=!oe,fe=ce?ie:te,se=$.useSyncExternalStore!==void 0?$.useSyncExternalStore:fe;useSyncExternalStoreShim_development.useSyncExternalStore=se,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),useSyncExternalStoreShim_development}process.env.NODE_ENV==="production"?shim.exports=requireUseSyncExternalStoreShim_production_min():shim.exports=requireUseSyncExternalStoreShim_development()
|
|
939
|
+
*/var hasRequiredUseSyncExternalStoreShim_development;function requireUseSyncExternalStoreShim_development(){return hasRequiredUseSyncExternalStoreShim_development||(hasRequiredUseSyncExternalStoreShim_development=1,process.env.NODE_ENV!=="production"&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var $=React,I=$.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function U(de){{for(var ue=arguments.length,pe=new Array(ue>1?ue-1:0),ve=1;ve<ue;ve++)pe[ve-1]=arguments[ve];q("error",de,pe)}}function q(de,ue,pe){{var ve=I.ReactDebugCurrentFrame,me=ve.getStackAddendum();me!==""&&(ue+="%s",pe=pe.concat([me]));var be=pe.map(function(_e){return String(_e)});be.unshift("Warning: "+ue),Function.prototype.apply.call(console[de],console,be)}}function G(de,ue){return de===ue&&(de!==0||1/de===1/ue)||de!==de&&ue!==ue}var K=typeof Object.is=="function"?Object.is:G,Y=$.useState,J=$.useEffect,X=$.useLayoutEffect,Z=$.useDebugValue,Q=!1,ee=!1;function te(de,ue,pe){Q||$.startTransition!==void 0&&(Q=!0,U("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var ve=ue();if(!ee){var me=ue();K(ve,me)||(U("The result of getSnapshot should be cached to avoid an infinite loop"),ee=!0)}var be=Y({inst:{value:ve,getSnapshot:ue}}),_e=be[0].inst,Se=be[1];return X(function(){_e.value=ve,_e.getSnapshot=ue,ne(_e)&&Se({inst:_e})},[de,ve,ue]),J(function(){ne(_e)&&Se({inst:_e});var xe=function(){ne(_e)&&Se({inst:_e})};return de(xe)},[de]),Z(ve),ve}function ne(de){var ue=de.getSnapshot,pe=de.value;try{var ve=ue();return!K(pe,ve)}catch{return!0}}function ie(de,ue,pe){return ue()}var oe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",ce=!oe,fe=ce?ie:te,se=$.useSyncExternalStore!==void 0?$.useSyncExternalStore:fe;useSyncExternalStoreShim_development.useSyncExternalStore=se,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),useSyncExternalStoreShim_development}var hasRequiredShim;function requireShim(){return hasRequiredShim||(hasRequiredShim=1,process.env.NODE_ENV==="production"?shim.exports=requireUseSyncExternalStoreShim_production_min():shim.exports=requireUseSyncExternalStoreShim_development()),shim.exports}var shimExports=requireShim(),jsxDevRuntime={exports:{}},reactJsxDevRuntime_production_min={};/**
|
|
940
940
|
* @license React
|
|
941
941
|
* react-jsx-dev-runtime.production.min.js
|
|
942
942
|
*
|
|
@@ -970,7 +970,7 @@ Check the top-level render call using <`+kt+">.")}return pt}}function Nn(He,pt){
|
|
|
970
970
|
*
|
|
971
971
|
* This source code is licensed under the MIT license found in the
|
|
972
972
|
* LICENSE file in the root directory of this source tree.
|
|
973
|
-
*/var hasRequiredWithSelector_production_min;function requireWithSelector_production_min(){if(hasRequiredWithSelector_production_min)return withSelector_production_min;hasRequiredWithSelector_production_min=1;var $=React,I=
|
|
973
|
+
*/var hasRequiredWithSelector_production_min;function requireWithSelector_production_min(){if(hasRequiredWithSelector_production_min)return withSelector_production_min;hasRequiredWithSelector_production_min=1;var $=React,I=requireShim();function U(Z,Q){return Z===Q&&(Z!==0||1/Z===1/Q)||Z!==Z&&Q!==Q}var q=typeof Object.is=="function"?Object.is:U,G=I.useSyncExternalStore,K=$.useRef,Y=$.useEffect,J=$.useMemo,X=$.useDebugValue;return withSelector_production_min.useSyncExternalStoreWithSelector=function(Z,Q,ee,te,ne){var ie=K(null);if(ie.current===null){var oe={hasValue:!1,value:null};ie.current=oe}else oe=ie.current;ie=J(function(){function fe(ve){if(!se){if(se=!0,de=ve,ve=te(ve),ne!==void 0&&oe.hasValue){var me=oe.value;if(ne(me,ve))return ue=me}return ue=ve}if(me=ue,q(de,ve))return me;var be=te(ve);return ne!==void 0&&ne(me,be)?me:(de=ve,ue=be)}var se=!1,de,ue,pe=ee===void 0?null:ee;return[function(){return fe(Q())},pe===null?void 0:function(){return fe(pe())}]},[Q,ee,te,ne]);var ce=G(Z,ie[0],ie[1]);return Y(function(){oe.hasValue=!0,oe.value=ce},[ce]),X(ce),ce},withSelector_production_min}var withSelector_development={};/**
|
|
974
974
|
* @license React
|
|
975
975
|
* use-sync-external-store-shim/with-selector.development.js
|
|
976
976
|
*
|
|
@@ -978,7 +978,7 @@ Check the top-level render call using <`+kt+">.")}return pt}}function Nn(He,pt){
|
|
|
978
978
|
*
|
|
979
979
|
* This source code is licensed under the MIT license found in the
|
|
980
980
|
* LICENSE file in the root directory of this source tree.
|
|
981
|
-
*/var hasRequiredWithSelector_development;function requireWithSelector_development(){return hasRequiredWithSelector_development||(hasRequiredWithSelector_development=1,process.env.NODE_ENV!=="production"&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var $=React,I=
|
|
981
|
+
*/var hasRequiredWithSelector_development;function requireWithSelector_development(){return hasRequiredWithSelector_development||(hasRequiredWithSelector_development=1,process.env.NODE_ENV!=="production"&&function(){typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error);var $=React,I=requireShim();function U(Q,ee){return Q===ee&&(Q!==0||1/Q===1/ee)||Q!==Q&&ee!==ee}var q=typeof Object.is=="function"?Object.is:U,G=I.useSyncExternalStore,K=$.useRef,Y=$.useEffect,J=$.useMemo,X=$.useDebugValue;function Z(Q,ee,te,ne,ie){var oe=K(null),ce;oe.current===null?(ce={hasValue:!1,value:null},oe.current=ce):ce=oe.current;var fe=J(function(){var pe=!1,ve,me,be=function(ke){if(!pe){pe=!0,ve=ke;var De=ne(ke);if(ie!==void 0&&ce.hasValue){var Be=ce.value;if(ie(Be,De))return me=Be,Be}return me=De,De}var Ve=ve,nt=me;if(q(Ve,ke))return nt;var ot=ne(ke);return ie!==void 0&&ie(nt,ot)?nt:(ve=ke,me=ot,ot)},_e=te===void 0?null:te,Se=function(){return be(ee())},xe=_e===null?void 0:function(){return be(_e())};return[Se,xe]},[ee,te,ne,ie]),se=fe[0],de=fe[1],ue=G(Q,se,de);return Y(function(){ce.hasValue=!0,ce.value=ue},[ue]),X(ue),ue}withSelector_development.useSyncExternalStoreWithSelector=Z,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error)}()),withSelector_development}process.env.NODE_ENV==="production"?withSelector.exports=requireWithSelector_production_min():withSelector.exports=requireWithSelector_development();var withSelectorExports=withSelector.exports;/*! *****************************************************************************
|
|
982
982
|
Copyright (c) Microsoft Corporation.
|
|
983
983
|
|
|
984
984
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -998,5 +998,5 @@ Event: `).concat(JSON.stringify(event)));else if(this.status!==InterpreterStatus
|
|
|
998
998
|
`).concat(ue.message))}if(fe&&ce){te.target!==void 0&&(X=te.target),J.push.apply(J,__spreadArray([],__read$2(te.actions),!1)),Z=te;break}}}catch(ue){q={error:ue}}finally{try{ee&&!ee.done&&(G=Q.return)&&G.call(Q)}finally{if(q)throw q.error}}if(Z){if(!X.length)return{transitions:[Z],exitSet:[],configuration:I.value?[this]:[],source:I,actions:J};var se=flatten(X.map(function(ue){return K.getRelativeStateNodes(ue,I.historyValue)})),de=!!Z.internal;return{transitions:[Z],exitSet:de?[]:flatten(X.map(function(ue){return K.getPotentiallyReenteringNodes(ue)})),configuration:se,source:I,actions:J}}},$.prototype.getPotentiallyReenteringNodes=function(I){if(this.order<I.order)return[this];for(var U=[],q=this,G=I;q&&q!==G;)U.push(q),q=q.parent;return q!==G?[]:(U.push(G),U)},$.prototype.getActions=function(I,U,q,G,K,Y,J){var X,Z,Q,ee,te=this,ne=Y?getConfiguration([],this.getStateNodes(Y.value)):[],ie=new Set;try{for(var oe=__values(Array.from(I).sort(function(xe,ke){return xe.order-ke.order})),ce=oe.next();!ce.done;ce=oe.next()){var fe=ce.value;(!has(ne,fe)||has(q.exitSet,fe)||fe.parent&&ie.has(fe.parent))&&ie.add(fe)}}catch(xe){X={error:xe}}finally{try{ce&&!ce.done&&(Z=oe.return)&&Z.call(oe)}finally{if(X)throw X.error}}try{for(var se=__values(ne),de=se.next();!de.done;de=se.next()){var fe=de.value;(!has(I,fe)||has(q.exitSet,fe.parent))&&q.exitSet.push(fe)}}catch(xe){Q={error:xe}}finally{try{de&&!de.done&&(ee=se.return)&&ee.call(se)}finally{if(Q)throw Q.error}}q.exitSet.sort(function(xe,ke){return ke.order-xe.order});var ue=Array.from(ie).sort(function(xe,ke){return xe.order-ke.order}),pe=new Set(q.exitSet),ve=flatten(ue.map(function(xe){var ke=[];if(xe.type!=="final")return ke;var De=xe.parent;if(!De.parent)return ke;ke.push(done(xe.id,xe.doneData),done(De.id,xe.doneData?mapContext(xe.doneData,G,K):void 0));var Be=De.parent;return Be.type==="parallel"&&getChildren(Be).every(function(Ve){return isInFinalState(q.configuration,Ve)})&&ke.push(done(Be.id)),ke})),me=ue.map(function(xe){var ke=xe.onEntry,De=xe.activities.map(function(Be){return start(Be)});return{type:"entry",actions:toActionObjects(J?__spreadArray(__spreadArray([],__read$2(ke),!1),__read$2(De),!1):__spreadArray(__spreadArray([],__read$2(De),!1),__read$2(ke),!1),te.machine.options.actions)}}).concat({type:"state_done",actions:ve.map(function(xe){return raise(xe)})}),be=Array.from(pe).map(function(xe){return{type:"exit",actions:toActionObjects(__spreadArray(__spreadArray([],__read$2(xe.onExit),!1),__read$2(xe.activities.map(function(ke){return stop(ke)})),!1),te.machine.options.actions)}}),_e=be.concat({type:"transition",actions:toActionObjects(q.actions,this.machine.options.actions)}).concat(me);if(U){var Se=toActionObjects(flatten(__spreadArray([],__read$2(I),!1).sort(function(xe,ke){return ke.order-xe.order}).map(function(xe){return xe.onExit})),this.machine.options.actions).filter(function(xe){return!isRaisableAction(xe)});return _e.concat({type:"stop",actions:Se})}return _e},$.prototype.transition=function(I,U,q,G){I===void 0&&(I=this.initialState);var K=toSCXMLEvent(U),Y;if(I instanceof State)Y=q===void 0?I:this.resolveState(State.from(I,q));else{var J=isString(I)?this.resolve(pathToStateValue(this.getResolvedPath(I))):this.resolve(I),X=q??this.machine.context;Y=this.resolveState(State.from(J,X))}if(!IS_PRODUCTION&&K.name===WILDCARD)throw new Error("An event cannot have the wildcard type ('".concat(WILDCARD,"')"));if(this.strict&&!this.events.includes(K.name)&&!isBuiltInEvent(K.name))throw new Error("Machine '".concat(this.id,"' does not accept event '").concat(K.name,"'"));var Z=this._transition(Y.value,Y,K)||{transitions:[],configuration:[],exitSet:[],source:Y,actions:[]},Q=getConfiguration([],this.getStateNodes(Y.value)),ee=Z.configuration.length?getConfiguration(Q,Z.configuration):Q;return Z.configuration=__spreadArray([],__read$2(ee),!1),this.resolveTransition(Z,Y,Y.context,G,K)},$.prototype.resolveRaisedTransition=function(I,U,q,G){var K,Y=I.actions;return I=this.transition(I,U,void 0,G),I._event=q,I.event=q.data,(K=I.actions).unshift.apply(K,__spreadArray([],__read$2(Y),!1)),I},$.prototype.resolveTransition=function(I,U,q,G,K){var Y,J,X,Z,Q=this;K===void 0&&(K=initEvent);var ee=I.configuration,te=!U||I.transitions.length>0,ne=te?I.configuration:U?U.configuration:[],ie=isInFinalState(ne,this),oe=te?getValue(this.machine,ee):void 0,ce=U?U.historyValue?U.historyValue:I.source?this.machine.historyValue(U.value):void 0:void 0,fe=this.getActions(new Set(ne),ie,I,q,K,U,G),se=U?__assign$1({},U.activities):{};try{for(var de=__values(fe),ue=de.next();!ue.done;ue=de.next()){var pe=ue.value;try{for(var ve=(X=void 0,__values(pe.actions)),me=ve.next();!me.done;me=ve.next()){var be=me.value;be.type===start$1?se[be.activity.id||be.activity.type]=be:be.type===stop$1&&(se[be.activity.id||be.activity.type]=!1)}}catch(tt){X={error:tt}}finally{try{me&&!me.done&&(Z=ve.return)&&Z.call(ve)}finally{if(X)throw X.error}}}}catch(tt){Y={error:tt}}finally{try{ue&&!ue.done&&(J=de.return)&&J.call(de)}finally{if(Y)throw Y.error}}var _e=__read$2(resolveActions(this,U,q,K,fe,G,this.machine.config.predictableActionArguments||this.machine.config.preserveActionOrder),2),Se=_e[0],xe=_e[1],ke=__read$2(partition(Se,isRaisableAction),2),De=ke[0],Be=ke[1],Ve=Se.filter(function(tt){var vt;return tt.type===start$1&&((vt=tt.activity)===null||vt===void 0?void 0:vt.type)===invoke}),nt=Ve.reduce(function(tt,vt){return tt[vt.activity.id]=createInvocableActor(vt.activity,Q.machine,xe,K),tt},U?__assign$1({},U.children):{}),ot=new State({value:oe||U.value,context:xe,_event:K,_sessionid:U?U._sessionid:null,historyValue:oe?ce?updateHistoryValue(ce,oe):void 0:U?U.historyValue:void 0,history:!oe||I.source?U:void 0,actions:oe?Be:[],activities:oe?se:U?U.activities:{},events:[],configuration:ne,transitions:I.transitions,children:nt,done:ie,tags:getTagsFromConfiguration(ne),machine:this}),ft=q!==xe;ot.changed=K.name===update||ft;var it=ot.history;it&&delete it.history;var ut=!ie&&(this._transient||ee.some(function(tt){return tt._transient}));if(!te&&(!ut||K.name===NULL_EVENT))return ot;var et=ot;if(!ie)for(ut&&(et=this.resolveRaisedTransition(et,{type:nullEvent},K,G));De.length;){var Ue=De.shift();et=this.resolveRaisedTransition(et,Ue._event,K,G)}var We=et.changed||(it?!!et.actions.length||ft||typeof it.value!=typeof et.value||!stateValuesEqual(et.value,it.value):void 0);return et.changed=We,et.history=it,et},$.prototype.getStateNode=function(I){if(isStateId(I))return this.machine.getStateNodeById(I);if(!this.states)throw new Error("Unable to retrieve child state '".concat(I,"' from '").concat(this.id,"'; no child states exist."));var U=this.states[I];if(!U)throw new Error("Child state '".concat(I,"' does not exist on '").concat(this.id,"'"));return U},$.prototype.getStateNodeById=function(I){var U=isStateId(I)?I.slice(STATE_IDENTIFIER.length):I;if(U===this.id)return this;var q=this.machine.idMap[U];if(!q)throw new Error("Child state node '#".concat(U,"' does not exist on machine '").concat(this.id,"'"));return q},$.prototype.getStateNodeByPath=function(I){if(typeof I=="string"&&isStateId(I))try{return this.getStateNodeById(I.slice(1))}catch{}for(var U=toStatePath(I,this.delimiter).slice(),q=this;U.length;){var G=U.shift();if(!G.length)break;q=q.getStateNode(G)}return q},$.prototype.resolve=function(I){var U,q=this;if(!I)return this.initialStateValue||EMPTY_OBJECT;switch(this.type){case"parallel":return mapValues(this.initialStateValue,function(K,Y){return K?q.getStateNode(Y).resolve(I[Y]||K):EMPTY_OBJECT});case"compound":if(isString(I)){var G=this.getStateNode(I);return G.type==="parallel"||G.type==="compound"?(U={},U[I]=G.initialStateValue,U):I}return Object.keys(I).length?mapValues(I,function(K,Y){return K?q.getStateNode(Y).resolve(K):EMPTY_OBJECT}):this.initialStateValue||{};default:return I||EMPTY_OBJECT}},$.prototype.getResolvedPath=function(I){if(isStateId(I)){var U=this.machine.idMap[I.slice(STATE_IDENTIFIER.length)];if(!U)throw new Error("Unable to find state node '".concat(I,"'"));return U.path}return toStatePath(I,this.delimiter)},Object.defineProperty($.prototype,"initialStateValue",{get:function(){var I;if(this.__cache.initialStateValue)return this.__cache.initialStateValue;var U;if(this.type==="parallel")U=mapFilterValues(this.states,function(q){return q.initialStateValue||EMPTY_OBJECT},function(q){return q.type!=="history"});else if(this.initial!==void 0){if(!this.states[this.initial])throw new Error("Initial state '".concat(this.initial,"' not found on '").concat(this.key,"'"));U=isLeafNode(this.states[this.initial])?this.initial:(I={},I[this.initial]=this.states[this.initial].initialStateValue,I)}else U={};return this.__cache.initialStateValue=U,this.__cache.initialStateValue},enumerable:!1,configurable:!0}),$.prototype.getInitialState=function(I,U){this._init();var q=this.getStateNodes(I);return this.resolveTransition({configuration:q,exitSet:[],transitions:[],source:void 0,actions:[]},void 0,U??this.machine.context,void 0)},Object.defineProperty($.prototype,"initialState",{get:function(){var I=this.initialStateValue;if(!I)throw new Error("Cannot retrieve initial state from simple state '".concat(this.id,"'."));return this.getInitialState(I)},enumerable:!1,configurable:!0}),Object.defineProperty($.prototype,"target",{get:function(){var I;if(this.type==="history"){var U=this.config;isString(U.target)?I=isStateId(U.target)?pathToStateValue(this.machine.getStateNodeById(U.target).path.slice(this.path.length-1)):U.target:I=U.target}return I},enumerable:!1,configurable:!0}),$.prototype.getRelativeStateNodes=function(I,U,q){return q===void 0&&(q=!0),q?I.type==="history"?I.resolveHistory(U):I.initialStateNodes:[I]},Object.defineProperty($.prototype,"initialStateNodes",{get:function(){var I=this;if(isLeafNode(this))return[this];if(this.type==="compound"&&!this.initial)return IS_PRODUCTION||warn(!1,"Compound state node '".concat(this.id,"' has no initial state.")),[this];var U=toStatePaths(this.initialStateValue);return flatten(U.map(function(q){return I.getFromRelativePath(q)}))},enumerable:!1,configurable:!0}),$.prototype.getFromRelativePath=function(I){if(!I.length)return[this];var U=__read$2(I),q=U[0],G=U.slice(1);if(!this.states)throw new Error("Cannot retrieve subPath '".concat(q,"' from node with no states"));var K=this.getStateNode(q);if(K.type==="history")return K.resolveHistory();if(!this.states[q])throw new Error("Child state '".concat(q,"' does not exist on '").concat(this.id,"'"));return this.states[q].getFromRelativePath(G)},$.prototype.historyValue=function(I){if(Object.keys(this.states).length)return{current:I||this.initialStateValue,states:mapFilterValues(this.states,function(U,q){if(!I)return U.historyValue();var G=isString(I)?void 0:I[q];return U.historyValue(G||U.initialStateValue)},function(U){return!U.history})}},$.prototype.resolveHistory=function(I){var U=this;if(this.type!=="history")return[this];var q=this.parent;if(!I){var G=this.target;return G?flatten(toStatePaths(G).map(function(Y){return q.getFromRelativePath(Y)})):q.initialStateNodes}var K=nestedPath(q.path,"states")(I).current;return isString(K)?[q.getStateNode(K)]:flatten(toStatePaths(K).map(function(Y){return U.history==="deep"?q.getFromRelativePath(Y):[q.states[Y[0]]]}))},Object.defineProperty($.prototype,"stateIds",{get:function(){var I=this,U=flatten(Object.keys(this.states).map(function(q){return I.states[q].stateIds}));return[this.id].concat(U)},enumerable:!1,configurable:!0}),Object.defineProperty($.prototype,"events",{get:function(){var I,U,q,G;if(this.__cache.events)return this.__cache.events;var K=this.states,Y=new Set(this.ownEvents);if(K)try{for(var J=__values(Object.keys(K)),X=J.next();!X.done;X=J.next()){var Z=X.value,Q=K[Z];if(Q.states)try{for(var ee=(q=void 0,__values(Q.events)),te=ee.next();!te.done;te=ee.next()){var ne=te.value;Y.add("".concat(ne))}}catch(ie){q={error:ie}}finally{try{te&&!te.done&&(G=ee.return)&&G.call(ee)}finally{if(q)throw q.error}}}}catch(ie){I={error:ie}}finally{try{X&&!X.done&&(U=J.return)&&U.call(J)}finally{if(I)throw I.error}}return this.__cache.events=Array.from(Y)},enumerable:!1,configurable:!0}),Object.defineProperty($.prototype,"ownEvents",{get:function(){var I=new Set(this.transitions.filter(function(U){return!(!U.target&&!U.actions.length&&U.internal)}).map(function(U){return U.eventType}));return Array.from(I)},enumerable:!1,configurable:!0}),$.prototype.resolveTarget=function(I){var U=this;if(I!==void 0)return I.map(function(q){if(!isString(q))return q;var G=q[0]===U.delimiter;if(G&&!U.parent)return U.getStateNodeByPath(q.slice(1));var K=G?U.key+q:q;if(U.parent)try{var Y=U.parent.getStateNodeByPath(K);return Y}catch(J){throw new Error("Invalid transition definition for state node '".concat(U.id,`':
|
|
999
999
|
`).concat(J.message))}else return U.getStateNodeByPath(K)})},$.prototype.formatTransition=function(I){var U=this,q=normalizeTarget(I.target),G="internal"in I?I.internal:q?q.some(function(X){return isString(X)&&X[0]===U.delimiter}):!0,K=this.machine.options.guards,Y=this.resolveTarget(q),J=__assign$1(__assign$1({},I),{actions:toActionObjects(toArray(I.actions)),cond:toGuard(I.cond,K),target:Y,source:this,internal:G,eventType:I.event,toJSON:function(){return __assign$1(__assign$1({},J),{target:J.target?J.target.map(function(X){return"#".concat(X.id)}):void 0,source:"#".concat(U.id)})}});return J},$.prototype.formatTransitions=function(){var I,U,q=this,G;if(!this.config.on)G=[];else if(Array.isArray(this.config.on))G=this.config.on;else{var K=this.config.on,Y=WILDCARD,J=K[Y],X=J===void 0?[]:J,Z=__rest$1(K,[typeof Y=="symbol"?Y:Y+""]);G=flatten(Object.keys(Z).map(function(se){!IS_PRODUCTION&&se===NULL_EVENT&&warn(!1,"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. "+'Please check the `on` configuration for "#'.concat(q.id,'".'));var de=toTransitionConfigArray(se,Z[se]);return IS_PRODUCTION||validateArrayifiedTransitions(q,se,de),de}).concat(toTransitionConfigArray(WILDCARD,X)))}var Q=this.config.always?toTransitionConfigArray("",this.config.always):[],ee=this.config.onDone?toTransitionConfigArray(String(done(this.id)),this.config.onDone):[];IS_PRODUCTION||warn(!(this.config.onDone&&!this.parent),'Root nodes cannot have an ".onDone" transition. Please check the config of "'.concat(this.id,'".'));var te=flatten(this.invoke.map(function(se){var de=[];return se.onDone&&de.push.apply(de,__spreadArray([],__read$2(toTransitionConfigArray(String(doneInvoke(se.id)),se.onDone)),!1)),se.onError&&de.push.apply(de,__spreadArray([],__read$2(toTransitionConfigArray(String(error(se.id)),se.onError)),!1)),de})),ne=this.after,ie=flatten(__spreadArray(__spreadArray(__spreadArray(__spreadArray([],__read$2(ee),!1),__read$2(te),!1),__read$2(G),!1),__read$2(Q),!1).map(function(se){return toArray(se).map(function(de){return q.formatTransition(de)})}));try{for(var oe=__values(ne),ce=oe.next();!ce.done;ce=oe.next()){var fe=ce.value;ie.push(fe)}}catch(se){I={error:se}}finally{try{ce&&!ce.done&&(U=oe.return)&&U.call(oe)}finally{if(I)throw I.error}}return ie},$}(),warned=!1;function createMachine($,I){return!IS_PRODUCTION&&!("predictableActionArguments"in $)&&!warned&&(warned=!0,console.warn("It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html")),new StateNode($,I)}var assign=assign$1,index$1=React.useLayoutEffect;function useConstant($){var I=React__namespace.useRef();return I.current||(I.current={v:$()}),I.current.v}var __assign=function(){return __assign=Object.assign||function($){for(var I,U=1,q=arguments.length;U<q;U++){I=arguments[U];for(var G in I)Object.prototype.hasOwnProperty.call(I,G)&&($[G]=I[G])}return $},__assign.apply(this,arguments)},__rest=function($,I){var U={};for(var q in $)Object.prototype.hasOwnProperty.call($,q)&&I.indexOf(q)<0&&(U[q]=$[q]);if($!=null&&typeof Object.getOwnPropertySymbols=="function")for(var G=0,q=Object.getOwnPropertySymbols($);G<q.length;G++)I.indexOf(q[G])<0&&Object.prototype.propertyIsEnumerable.call($,q[G])&&(U[q[G]]=$[q[G]]);return U},__read$1=function($,I){var U=typeof Symbol=="function"&&$[Symbol.iterator];if(!U)return $;var q=U.call($),G,K=[],Y;try{for(;(I===void 0||I-- >0)&&!(G=q.next()).done;)K.push(G.value)}catch(J){Y={error:J}}finally{try{G&&!G.done&&(U=q.return)&&U.call(q)}finally{if(Y)throw Y.error}}return K};function useIdleInterpreter($,I){var U=useConstant(function(){return typeof $=="function"?$():$});if(process.env.NODE_ENV!=="production"&&typeof $!="function"){var q=__read$1(React.useState(U),1),G=q[0];$!==G&&console.warn("Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\nPlease make sure that you pass the same Machine as argument each time.")}var K=I.context,Y=I.guards,J=I.actions,X=I.activities,Z=I.services,Q=I.delays;I.state;var ee=__rest(I,["context","guards","actions","activities","services","delays","state"]),te=useConstant(function(){var ne={context:K,guards:Y,actions:J,activities:X,services:Z,delays:Q},ie=U.withConfig(ne,function(){return __assign(__assign({},U.context),K)});return interpret(ie,ee)});return index$1(function(){Object.assign(te.machine.options.actions,J),Object.assign(te.machine.options.guards,Y),Object.assign(te.machine.options.activities,X),Object.assign(te.machine.options.services,Z),Object.assign(te.machine.options.delays,Q)},[J,Y,X,Z,Q]),te}function isInterpreterStateEqual($,I,U){if($.status===InterpreterStatus.NotStarted)return!0;var q=U.changed===void 0&&(Object.keys(U.children).length>0||typeof I.changed=="boolean");return!(U.changed||q)}var __read=function($,I){var U=typeof Symbol=="function"&&$[Symbol.iterator];if(!U)return $;var q=U.call($),G,K=[],Y;try{for(;(I===void 0||I-- >0)&&!(G=q.next()).done;)K.push(G.value)}catch(J){Y={error:J}}finally{try{G&&!G.done&&(U=q.return)&&U.call(q)}finally{if(Y)throw Y.error}}return K};function identity($){return $}function useMachine($){for(var I=[],U=1;U<arguments.length;U++)I[U-1]=arguments[U];var q=__read(I,1),G=q[0],K=G===void 0?{}:G,Y=useIdleInterpreter($,K),J=React.useCallback(function(){return Y.status===InterpreterStatus.NotStarted?K.state?State.create(K.state):Y.machine.initialState:Y.getSnapshot()},[Y]),X=React.useCallback(function(ee,te){return isInterpreterStateEqual(Y,ee,te)},[Y]),Z=React.useCallback(function(ee){var te=Y.subscribe(ee).unsubscribe;return te},[Y]),Q=withSelectorExports.useSyncExternalStoreWithSelector(Z,J,J,identity,X);return React.useEffect(function(){var ee=K.state;return Y.start(ee?State.create(ee):void 0),function(){Y.stop(),Y.status=InterpreterStatus.NotStarted}},[]),[Q,Y.send,Y]}const identityMachine=createMachine({id:"identity",predictableActionArguments:!0,context:{identity:null,identitySubscribable:null},initial:"choosingAction",invoke:{src:$=>$.identitySubscribable},states:{unknown:{always:[{cond:"initiallyManagingDeviceInvitation",target:"managingDeviceInvitation",actions:"log"},{target:"choosingAction",actions:"log"}]},choosingAction:{},managingDeviceInvitation:{},confirmingResetStorage:{},confirmingJoinNewIdentity:{}},on:{unchooseAction:{target:".choosingAction",actions:["unsetInvitation","log"]},deselectInvitation:{target:".choosingAction",actions:["unsetInvitation","log"]},selectInvitation:{target:".managingDeviceInvitation",actions:["setInvitation","log"]},chooseJoinNewIdentity:{target:".confirmingJoinNewIdentity",actions:"log"},chooseResetStorage:{target:".confirmingResetStorage",actions:"log"}}},{guards:{initiallyManagingDeviceInvitation:({initialDisposition:$},I)=>$==="manage-device-invitation"},actions:{setIdentity:assign({identity:($,I)=>(I==null?void 0:I.identity)??null}),setInvitation:assign({invitation:($,I)=>(I==null?void 0:I.invitation)??null}),unsetInvitation:assign({invitation:()=>{}}),log:($,I)=>{log$2("[transition]",{event:I,context:$})}}}),useIdentityMachine=($,I)=>useMachine(identityMachine,{...I,context:{...I==null?void 0:I.context,identity:$.halo.identity.get(),identitySubscribable:$.halo.identity.map(U=>({type:"setIdentity",identity:U}))}}),IdentityActionChooser=$=>{const{send:I}=$,U=reactClient.useClient(),q=halo.useHaloInvitations(),G=reactClient.useAgentHostingProviderClient(U.config),K=React.useCallback(J=>{const X=clientProtocol.InvitationEncoder.encode(J);J.state===Invitation.State.CONNECTING&&log$2.info(JSON.stringify({invitationCode:X,authCode:J.authCode}))},[]),Y=()=>{q.forEach(X=>X.cancel());const J=U.halo.share();process.env.NODE_ENV!=="production"&&J.subscribe(K),I==null||I({type:"selectInvitation",invitation:J})};return React.createElement(IdentityActionChooserImpl,{...$,onCreateInvitationClick:Y,agentHostingEnabled:!!G})},IdentityActionChooserImpl=({send:$,onCreateInvitationClick:I,devices:U,onAgentDestroy:q,onAgentCreate:G,agentStatus:K,agentActive:Y,agentHostingEnabled:J})=>React.createElement(React.Fragment,null,React.createElement(DeviceList,{devices:U,onClickAdd:I,onClickJoinExisting:()=>$==null?void 0:$({type:"chooseJoinNewIdentity"}),onClickReset:()=>$==null?void 0:$({type:"chooseResetStorage"})}),J&&React.createElement(AgentConfig,{agentActive:Y,agentStatus:K,onAgentDestroy:q,onAgentCreate:G})),useAgentHandlers=({client:$,invitations:I,identity:U})=>{const[q,G]=React.useState(""),[K,Y]=React.useState(""),[J,X]=React.useState(!1),Z=reactClient.useAgentHostingProviderClient($.config);React.useEffect(()=>{(async()=>{if(Z){const ie=await(Z==null?void 0:Z.getAgent((U==null?void 0:U.identityKey.truncate())??"foo"));ie?(X(!0),Y(ie)):(X(!1),G("No agent deployed via provider."))}else G("No agent provider configured.")})()},[]);const Q=React.useCallback(async ne=>{const ie=clientProtocol.InvitationEncoder.encode(ne);if(ne.state===Invitation.State.CONNECTING&&(log$2.info(JSON.stringify({invitationCode:ie,authCode:ne.authCode})),invariant(U,"Identity not found"),Z))try{const oe=await(Z==null?void 0:Z.createAgent(ie,U.identityKey.truncate()));Y(oe),X(!0),G("")}catch(oe){G(`error creating agent: ${oe.message}`)}},[]);return{onAgentCreate:async()=>{I.forEach(ie=>ie.cancel()),$.halo.share({type:Invitation.Type.INTERACTIVE,authMethod:Invitation.AuthMethod.NONE,multiUse:!0}).subscribe(Q)},onAgentDestroy:async()=>{const ne=$.halo.identity.get();invariant(ne,"Identity not found");try{await(Z==null?void 0:Z.destroyAgent(ne.identityKey.truncate())),G("No agent deployed via provider."),Y(""),X(!1)}catch(ie){G(`error destroying agent: ${ie.message}`)}},validationMessage:q,agentStatus:K,agentActive:J}};var qrcode={exports:{}};(function($,I){var U=function(){var q=function(pe,ve){var me=236,be=17,_e=pe,Se=K[ve],xe=null,ke=0,De=null,Be=[],Ve={},nt=function(Ae,Re){ke=_e*4+17,xe=function(Ce){for(var ge=new Array(Ce),ye=0;ye<Ce;ye+=1){ge[ye]=new Array(Ce);for(var Me=0;Me<Ce;Me+=1)ge[ye][Me]=null}return ge}(ke),ot(0,0),ot(ke-7,0),ot(0,ke-7),ut(),it(),Ue(Ae,Re),_e>=7&&et(Ae),De==null&&(De=vt(_e,Se,Be)),We(De,Re)},ot=function(Ae,Re){for(var Ce=-1;Ce<=7;Ce+=1)if(!(Ae+Ce<=-1||ke<=Ae+Ce))for(var ge=-1;ge<=7;ge+=1)Re+ge<=-1||ke<=Re+ge||(0<=Ce&&Ce<=6&&(ge==0||ge==6)||0<=ge&&ge<=6&&(Ce==0||Ce==6)||2<=Ce&&Ce<=4&&2<=ge&&ge<=4?xe[Ae+Ce][Re+ge]=!0:xe[Ae+Ce][Re+ge]=!1)},ft=function(){for(var Ae=0,Re=0,Ce=0;Ce<8;Ce+=1){nt(!0,Ce);var ge=J.getLostPoint(Ve);(Ce==0||Ae>ge)&&(Ae=ge,Re=Ce)}return Re},it=function(){for(var Ae=8;Ae<ke-8;Ae+=1)xe[Ae][6]==null&&(xe[Ae][6]=Ae%2==0);for(var Re=8;Re<ke-8;Re+=1)xe[6][Re]==null&&(xe[6][Re]=Re%2==0)},ut=function(){for(var Ae=J.getPatternPosition(_e),Re=0;Re<Ae.length;Re+=1)for(var Ce=0;Ce<Ae.length;Ce+=1){var ge=Ae[Re],ye=Ae[Ce];if(xe[ge][ye]==null)for(var Me=-2;Me<=2;Me+=1)for(var Ke=-2;Ke<=2;Ke+=1)Me==-2||Me==2||Ke==-2||Ke==2||Me==0&&Ke==0?xe[ge+Me][ye+Ke]=!0:xe[ge+Me][ye+Ke]=!1}},et=function(Ae){for(var Re=J.getBCHTypeNumber(_e),Ce=0;Ce<18;Ce+=1){var ge=!Ae&&(Re>>Ce&1)==1;xe[Math.floor(Ce/3)][Ce%3+ke-8-3]=ge}for(var Ce=0;Ce<18;Ce+=1){var ge=!Ae&&(Re>>Ce&1)==1;xe[Ce%3+ke-8-3][Math.floor(Ce/3)]=ge}},Ue=function(Ae,Re){for(var Ce=Se<<3|Re,ge=J.getBCHTypeInfo(Ce),ye=0;ye<15;ye+=1){var Me=!Ae&&(ge>>ye&1)==1;ye<6?xe[ye][8]=Me:ye<8?xe[ye+1][8]=Me:xe[ke-15+ye][8]=Me}for(var ye=0;ye<15;ye+=1){var Me=!Ae&&(ge>>ye&1)==1;ye<8?xe[8][ke-ye-1]=Me:ye<9?xe[8][15-ye-1+1]=Me:xe[8][15-ye-1]=Me}xe[ke-8][8]=!Ae},We=function(Ae,Re){for(var Ce=-1,ge=ke-1,ye=7,Me=0,Ke=J.getMaskFunction(Re),st=ke-1;st>0;st-=2)for(st==6&&(st-=1);;){for(var dt=0;dt<2;dt+=1)if(xe[ge][st-dt]==null){var $t=!1;Me<Ae.length&&($t=(Ae[Me]>>>ye&1)==1);var Et=Ke(ge,st-dt);Et&&($t=!$t),xe[ge][st-dt]=$t,ye-=1,ye==-1&&(Me+=1,ye=7)}if(ge+=Ce,ge<0||ke<=ge){ge-=Ce,Ce=-Ce;break}}},tt=function(Ae,Re){for(var Ce=0,ge=0,ye=0,Me=new Array(Re.length),Ke=new Array(Re.length),st=0;st<Re.length;st+=1){var dt=Re[st].dataCount,$t=Re[st].totalCount-dt;ge=Math.max(ge,dt),ye=Math.max(ye,$t),Me[st]=new Array(dt);for(var Et=0;Et<Me[st].length;Et+=1)Me[st][Et]=255&Ae.getBuffer()[Et+Ce];Ce+=dt;var rt=J.getErrorCorrectPolynomial($t),jt=Z(Me[st],rt.getLength()-1),Gt=jt.mod(rt);Ke[st]=new Array(rt.getLength()-1);for(var Et=0;Et<Ke[st].length;Et+=1){var At=Et+Gt.getLength()-Ke[st].length;Ke[st][Et]=At>=0?Gt.getAt(At):0}}for(var zt=0,Et=0;Et<Re.length;Et+=1)zt+=Re[Et].totalCount;for(var nn=new Array(zt),St=0,Et=0;Et<ge;Et+=1)for(var st=0;st<Re.length;st+=1)Et<Me[st].length&&(nn[St]=Me[st][Et],St+=1);for(var Et=0;Et<ye;Et+=1)for(var st=0;st<Re.length;st+=1)Et<Ke[st].length&&(nn[St]=Ke[st][Et],St+=1);return nn},vt=function(Ae,Re,Ce){for(var ge=Q.getRSBlocks(Ae,Re),ye=ee(),Me=0;Me<Ce.length;Me+=1){var Ke=Ce[Me];ye.put(Ke.getMode(),4),ye.put(Ke.getLength(),J.getLengthInBits(Ke.getMode(),Ae)),Ke.write(ye)}for(var st=0,Me=0;Me<ge.length;Me+=1)st+=ge[Me].dataCount;if(ye.getLengthInBits()>st*8)throw"code length overflow. ("+ye.getLengthInBits()+">"+st*8+")";for(ye.getLengthInBits()+4<=st*8&&ye.put(0,4);ye.getLengthInBits()%8!=0;)ye.putBit(!1);for(;!(ye.getLengthInBits()>=st*8||(ye.put(me,8),ye.getLengthInBits()>=st*8));)ye.put(be,8);return tt(ye,ge)};Ve.addData=function(Ae,Re){Re=Re||"Byte";var Ce=null;switch(Re){case"Numeric":Ce=te(Ae);break;case"Alphanumeric":Ce=ne(Ae);break;case"Byte":Ce=ie(Ae);break;case"Kanji":Ce=oe(Ae);break;default:throw"mode:"+Re}Be.push(Ce),De=null},Ve.isDark=function(Ae,Re){if(Ae<0||ke<=Ae||Re<0||ke<=Re)throw Ae+","+Re;return xe[Ae][Re]},Ve.getModuleCount=function(){return ke},Ve.make=function(){if(_e<1){for(var Ae=1;Ae<40;Ae++){for(var Re=Q.getRSBlocks(Ae,Se),Ce=ee(),ge=0;ge<Be.length;ge++){var ye=Be[ge];Ce.put(ye.getMode(),4),Ce.put(ye.getLength(),J.getLengthInBits(ye.getMode(),Ae)),ye.write(Ce)}for(var Me=0,ge=0;ge<Re.length;ge++)Me+=Re[ge].dataCount;if(Ce.getLengthInBits()<=Me*8)break}_e=Ae}nt(!1,ft())},Ve.createTableTag=function(Ae,Re){Ae=Ae||2,Re=typeof Re>"u"?Ae*4:Re;var Ce="";Ce+='<table style="',Ce+=" border-width: 0px; border-style: none;",Ce+=" border-collapse: collapse;",Ce+=" padding: 0px; margin: "+Re+"px;",Ce+='">',Ce+="<tbody>";for(var ge=0;ge<Ve.getModuleCount();ge+=1){Ce+="<tr>";for(var ye=0;ye<Ve.getModuleCount();ye+=1)Ce+='<td style="',Ce+=" border-width: 0px; border-style: none;",Ce+=" border-collapse: collapse;",Ce+=" padding: 0px; margin: 0px;",Ce+=" width: "+Ae+"px;",Ce+=" height: "+Ae+"px;",Ce+=" background-color: ",Ce+=Ve.isDark(ge,ye)?"#000000":"#ffffff",Ce+=";",Ce+='"/>';Ce+="</tr>"}return Ce+="</tbody>",Ce+="</table>",Ce},Ve.createSvgTag=function(Ae,Re,Ce,ge){var ye={};typeof arguments[0]=="object"&&(ye=arguments[0],Ae=ye.cellSize,Re=ye.margin,Ce=ye.alt,ge=ye.title),Ae=Ae||2,Re=typeof Re>"u"?Ae*4:Re,Ce=typeof Ce=="string"?{text:Ce}:Ce||{},Ce.text=Ce.text||null,Ce.id=Ce.text?Ce.id||"qrcode-description":null,ge=typeof ge=="string"?{text:ge}:ge||{},ge.text=ge.text||null,ge.id=ge.text?ge.id||"qrcode-title":null;var Me=Ve.getModuleCount()*Ae+Re*2,Ke,st,dt,$t,Et="",rt;for(rt="l"+Ae+",0 0,"+Ae+" -"+Ae+",0 0,-"+Ae+"z ",Et+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"',Et+=ye.scalable?"":' width="'+Me+'px" height="'+Me+'px"',Et+=' viewBox="0 0 '+Me+" "+Me+'" ',Et+=' preserveAspectRatio="xMinYMin meet"',Et+=ge.text||Ce.text?' role="img" aria-labelledby="'+je([ge.id,Ce.id].join(" ").trim())+'"':"",Et+=">",Et+=ge.text?'<title id="'+je(ge.id)+'">'+je(ge.text)+"</title>":"",Et+=Ce.text?'<description id="'+je(Ce.id)+'">'+je(Ce.text)+"</description>":"",Et+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>',Et+='<path d="',dt=0;dt<Ve.getModuleCount();dt+=1)for($t=dt*Ae+Re,Ke=0;Ke<Ve.getModuleCount();Ke+=1)Ve.isDark(dt,Ke)&&(st=Ke*Ae+Re,Et+="M"+st+","+$t+rt);return Et+='" stroke="transparent" fill="black"/>',Et+="</svg>",Et},Ve.createDataURL=function(Ae,Re){Ae=Ae||2,Re=typeof Re>"u"?Ae*4:Re;var Ce=Ve.getModuleCount()*Ae+Re*2,ge=Re,ye=Ce-Re;return ue(Ce,Ce,function(Me,Ke){if(ge<=Me&&Me<ye&&ge<=Ke&&Ke<ye){var st=Math.floor((Me-ge)/Ae),dt=Math.floor((Ke-ge)/Ae);return Ve.isDark(dt,st)?0:1}else return 1})},Ve.createImgTag=function(Ae,Re,Ce){Ae=Ae||2,Re=typeof Re>"u"?Ae*4:Re;var ge=Ve.getModuleCount()*Ae+Re*2,ye="";return ye+="<img",ye+=' src="',ye+=Ve.createDataURL(Ae,Re),ye+='"',ye+=' width="',ye+=ge,ye+='"',ye+=' height="',ye+=ge,ye+='"',Ce&&(ye+=' alt="',ye+=je(Ce),ye+='"'),ye+="/>",ye};var je=function(Ae){for(var Re="",Ce=0;Ce<Ae.length;Ce+=1){var ge=Ae.charAt(Ce);switch(ge){case"<":Re+="<";break;case">":Re+=">";break;case"&":Re+="&";break;case'"':Re+=""";break;default:Re+=ge;break}}return Re},ze=function(Ae){var Re=1;Ae=typeof Ae>"u"?Re*2:Ae;var Ce=Ve.getModuleCount()*Re+Ae*2,ge=Ae,ye=Ce-Ae,Me,Ke,st,dt,$t,Et={"██":"█","█ ":"▀"," █":"▄"," ":" "},rt={"██":"▀","█ ":"▀"," █":" "," ":" "},jt="";for(Me=0;Me<Ce;Me+=2){for(st=Math.floor((Me-ge)/Re),dt=Math.floor((Me+1-ge)/Re),Ke=0;Ke<Ce;Ke+=1)$t="█",ge<=Ke&&Ke<ye&&ge<=Me&&Me<ye&&Ve.isDark(st,Math.floor((Ke-ge)/Re))&&($t=" "),ge<=Ke&&Ke<ye&&ge<=Me+1&&Me+1<ye&&Ve.isDark(dt,Math.floor((Ke-ge)/Re))?$t+=" ":$t+="█",jt+=Ae<1&&Me+1>=ye?rt[$t]:Et[$t];jt+=`
|
|
1000
1000
|
`}return Ce%2&&Ae>0?jt.substring(0,jt.length-Ce-1)+Array(Ce+1).join("▀"):jt.substring(0,jt.length-1)};return Ve.createASCII=function(Ae,Re){if(Ae=Ae||1,Ae<2)return ze(Re);Ae-=1,Re=typeof Re>"u"?Ae*2:Re;var Ce=Ve.getModuleCount()*Ae+Re*2,ge=Re,ye=Ce-Re,Me,Ke,st,dt,$t=Array(Ae+1).join("██"),Et=Array(Ae+1).join(" "),rt="",jt="";for(Me=0;Me<Ce;Me+=1){for(st=Math.floor((Me-ge)/Ae),jt="",Ke=0;Ke<Ce;Ke+=1)dt=1,ge<=Ke&&Ke<ye&&ge<=Me&&Me<ye&&Ve.isDark(st,Math.floor((Ke-ge)/Ae))&&(dt=0),jt+=dt?$t:Et;for(st=0;st<Ae;st+=1)rt+=jt+`
|
|
1001
|
-
`}return rt.substring(0,rt.length-1)},Ve.renderTo2dContext=function(Ae,Re){Re=Re||2;for(var Ce=Ve.getModuleCount(),ge=0;ge<Ce;ge++)for(var ye=0;ye<Ce;ye++)Ae.fillStyle=Ve.isDark(ge,ye)?"black":"white",Ae.fillRect(ge*Re,ye*Re,Re,Re)},Ve};q.stringToBytesFuncs={default:function(pe){for(var ve=[],me=0;me<pe.length;me+=1){var be=pe.charCodeAt(me);ve.push(be&255)}return ve}},q.stringToBytes=q.stringToBytesFuncs.default,q.createStringToBytes=function(pe,ve){var me=function(){for(var _e=se(pe),Se=function(){var it=_e.read();if(it==-1)throw"eof";return it},xe=0,ke={};;){var De=_e.read();if(De==-1)break;var Be=Se(),Ve=Se(),nt=Se(),ot=String.fromCharCode(De<<8|Be),ft=Ve<<8|nt;ke[ot]=ft,xe+=1}if(xe!=ve)throw xe+" != "+ve;return ke}(),be=63;return function(_e){for(var Se=[],xe=0;xe<_e.length;xe+=1){var ke=_e.charCodeAt(xe);if(ke<128)Se.push(ke);else{var De=me[_e.charAt(xe)];typeof De=="number"?(De&255)==De?Se.push(De):(Se.push(De>>>8),Se.push(De&255)):Se.push(be)}}return Se}};var G={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},K={L:1,M:0,Q:3,H:2},Y={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},J=function(){var pe=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],ve=1335,me=7973,be=21522,_e={},Se=function(xe){for(var ke=0;xe!=0;)ke+=1,xe>>>=1;return ke};return _e.getBCHTypeInfo=function(xe){for(var ke=xe<<10;Se(ke)-Se(ve)>=0;)ke^=ve<<Se(ke)-Se(ve);return(xe<<10|ke)^be},_e.getBCHTypeNumber=function(xe){for(var ke=xe<<12;Se(ke)-Se(me)>=0;)ke^=me<<Se(ke)-Se(me);return xe<<12|ke},_e.getPatternPosition=function(xe){return pe[xe-1]},_e.getMaskFunction=function(xe){switch(xe){case Y.PATTERN000:return function(ke,De){return(ke+De)%2==0};case Y.PATTERN001:return function(ke,De){return ke%2==0};case Y.PATTERN010:return function(ke,De){return De%3==0};case Y.PATTERN011:return function(ke,De){return(ke+De)%3==0};case Y.PATTERN100:return function(ke,De){return(Math.floor(ke/2)+Math.floor(De/3))%2==0};case Y.PATTERN101:return function(ke,De){return ke*De%2+ke*De%3==0};case Y.PATTERN110:return function(ke,De){return(ke*De%2+ke*De%3)%2==0};case Y.PATTERN111:return function(ke,De){return(ke*De%3+(ke+De)%2)%2==0};default:throw"bad maskPattern:"+xe}},_e.getErrorCorrectPolynomial=function(xe){for(var ke=Z([1],0),De=0;De<xe;De+=1)ke=ke.multiply(Z([1,X.gexp(De)],0));return ke},_e.getLengthInBits=function(xe,ke){if(1<=ke&&ke<10)switch(xe){case G.MODE_NUMBER:return 10;case G.MODE_ALPHA_NUM:return 9;case G.MODE_8BIT_BYTE:return 8;case G.MODE_KANJI:return 8;default:throw"mode:"+xe}else if(ke<27)switch(xe){case G.MODE_NUMBER:return 12;case G.MODE_ALPHA_NUM:return 11;case G.MODE_8BIT_BYTE:return 16;case G.MODE_KANJI:return 10;default:throw"mode:"+xe}else if(ke<41)switch(xe){case G.MODE_NUMBER:return 14;case G.MODE_ALPHA_NUM:return 13;case G.MODE_8BIT_BYTE:return 16;case G.MODE_KANJI:return 12;default:throw"mode:"+xe}else throw"type:"+ke},_e.getLostPoint=function(xe){for(var ke=xe.getModuleCount(),De=0,Be=0;Be<ke;Be+=1)for(var Ve=0;Ve<ke;Ve+=1){for(var nt=0,ot=xe.isDark(Be,Ve),ft=-1;ft<=1;ft+=1)if(!(Be+ft<0||ke<=Be+ft))for(var it=-1;it<=1;it+=1)Ve+it<0||ke<=Ve+it||ft==0&&it==0||ot==xe.isDark(Be+ft,Ve+it)&&(nt+=1);nt>5&&(De+=3+nt-5)}for(var Be=0;Be<ke-1;Be+=1)for(var Ve=0;Ve<ke-1;Ve+=1){var ut=0;xe.isDark(Be,Ve)&&(ut+=1),xe.isDark(Be+1,Ve)&&(ut+=1),xe.isDark(Be,Ve+1)&&(ut+=1),xe.isDark(Be+1,Ve+1)&&(ut+=1),(ut==0||ut==4)&&(De+=3)}for(var Be=0;Be<ke;Be+=1)for(var Ve=0;Ve<ke-6;Ve+=1)xe.isDark(Be,Ve)&&!xe.isDark(Be,Ve+1)&&xe.isDark(Be,Ve+2)&&xe.isDark(Be,Ve+3)&&xe.isDark(Be,Ve+4)&&!xe.isDark(Be,Ve+5)&&xe.isDark(Be,Ve+6)&&(De+=40);for(var Ve=0;Ve<ke;Ve+=1)for(var Be=0;Be<ke-6;Be+=1)xe.isDark(Be,Ve)&&!xe.isDark(Be+1,Ve)&&xe.isDark(Be+2,Ve)&&xe.isDark(Be+3,Ve)&&xe.isDark(Be+4,Ve)&&!xe.isDark(Be+5,Ve)&&xe.isDark(Be+6,Ve)&&(De+=40);for(var et=0,Ve=0;Ve<ke;Ve+=1)for(var Be=0;Be<ke;Be+=1)xe.isDark(Be,Ve)&&(et+=1);var Ue=Math.abs(100*et/ke/ke-50)/5;return De+=Ue*10,De},_e}(),X=function(){for(var pe=new Array(256),ve=new Array(256),me=0;me<8;me+=1)pe[me]=1<<me;for(var me=8;me<256;me+=1)pe[me]=pe[me-4]^pe[me-5]^pe[me-6]^pe[me-8];for(var me=0;me<255;me+=1)ve[pe[me]]=me;var be={};return be.glog=function(_e){if(_e<1)throw"glog("+_e+")";return ve[_e]},be.gexp=function(_e){for(;_e<0;)_e+=255;for(;_e>=256;)_e-=255;return pe[_e]},be}();function Z(pe,ve){if(typeof pe.length>"u")throw pe.length+"/"+ve;var me=function(){for(var _e=0;_e<pe.length&&pe[_e]==0;)_e+=1;for(var Se=new Array(pe.length-_e+ve),xe=0;xe<pe.length-_e;xe+=1)Se[xe]=pe[xe+_e];return Se}(),be={};return be.getAt=function(_e){return me[_e]},be.getLength=function(){return me.length},be.multiply=function(_e){for(var Se=new Array(be.getLength()+_e.getLength()-1),xe=0;xe<be.getLength();xe+=1)for(var ke=0;ke<_e.getLength();ke+=1)Se[xe+ke]^=X.gexp(X.glog(be.getAt(xe))+X.glog(_e.getAt(ke)));return Z(Se,0)},be.mod=function(_e){if(be.getLength()-_e.getLength()<0)return be;for(var Se=X.glog(be.getAt(0))-X.glog(_e.getAt(0)),xe=new Array(be.getLength()),ke=0;ke<be.getLength();ke+=1)xe[ke]=be.getAt(ke);for(var ke=0;ke<_e.getLength();ke+=1)xe[ke]^=X.gexp(X.glog(_e.getAt(ke))+Se);return Z(xe,0).mod(_e)},be}var Q=function(){var pe=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],ve=function(_e,Se){var xe={};return xe.totalCount=_e,xe.dataCount=Se,xe},me={},be=function(_e,Se){switch(Se){case K.L:return pe[(_e-1)*4+0];case K.M:return pe[(_e-1)*4+1];case K.Q:return pe[(_e-1)*4+2];case K.H:return pe[(_e-1)*4+3];default:return}};return me.getRSBlocks=function(_e,Se){var xe=be(_e,Se);if(typeof xe>"u")throw"bad rs block @ typeNumber:"+_e+"/errorCorrectionLevel:"+Se;for(var ke=xe.length/3,De=[],Be=0;Be<ke;Be+=1)for(var Ve=xe[Be*3+0],nt=xe[Be*3+1],ot=xe[Be*3+2],ft=0;ft<Ve;ft+=1)De.push(ve(nt,ot));return De},me}(),ee=function(){var pe=[],ve=0,me={};return me.getBuffer=function(){return pe},me.getAt=function(be){var _e=Math.floor(be/8);return(pe[_e]>>>7-be%8&1)==1},me.put=function(be,_e){for(var Se=0;Se<_e;Se+=1)me.putBit((be>>>_e-Se-1&1)==1)},me.getLengthInBits=function(){return ve},me.putBit=function(be){var _e=Math.floor(ve/8);pe.length<=_e&&pe.push(0),be&&(pe[_e]|=128>>>ve%8),ve+=1},me},te=function(pe){var ve=G.MODE_NUMBER,me=pe,be={};be.getMode=function(){return ve},be.getLength=function(xe){return me.length},be.write=function(xe){for(var ke=me,De=0;De+2<ke.length;)xe.put(_e(ke.substring(De,De+3)),10),De+=3;De<ke.length&&(ke.length-De==1?xe.put(_e(ke.substring(De,De+1)),4):ke.length-De==2&&xe.put(_e(ke.substring(De,De+2)),7))};var _e=function(xe){for(var ke=0,De=0;De<xe.length;De+=1)ke=ke*10+Se(xe.charAt(De));return ke},Se=function(xe){if("0"<=xe&&xe<="9")return xe.charCodeAt(0)-48;throw"illegal char :"+xe};return be},ne=function(pe){var ve=G.MODE_ALPHA_NUM,me=pe,be={};be.getMode=function(){return ve},be.getLength=function(Se){return me.length},be.write=function(Se){for(var xe=me,ke=0;ke+1<xe.length;)Se.put(_e(xe.charAt(ke))*45+_e(xe.charAt(ke+1)),11),ke+=2;ke<xe.length&&Se.put(_e(xe.charAt(ke)),6)};var _e=function(Se){if("0"<=Se&&Se<="9")return Se.charCodeAt(0)-48;if("A"<=Se&&Se<="Z")return Se.charCodeAt(0)-65+10;switch(Se){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+Se}};return be},ie=function(pe){var ve=G.MODE_8BIT_BYTE,me=q.stringToBytes(pe),be={};return be.getMode=function(){return ve},be.getLength=function(_e){return me.length},be.write=function(_e){for(var Se=0;Se<me.length;Se+=1)_e.put(me[Se],8)},be},oe=function(pe){var ve=G.MODE_KANJI,me=q.stringToBytesFuncs.SJIS;if(!me)throw"sjis not supported.";(function(Se,xe){var ke=me(Se);if(ke.length!=2||(ke[0]<<8|ke[1])!=xe)throw"sjis not supported."})("友",38726);var be=me(pe),_e={};return _e.getMode=function(){return ve},_e.getLength=function(Se){return~~(be.length/2)},_e.write=function(Se){for(var xe=be,ke=0;ke+1<xe.length;){var De=(255&xe[ke])<<8|255&xe[ke+1];if(33088<=De&&De<=40956)De-=33088;else if(57408<=De&&De<=60351)De-=49472;else throw"illegal char at "+(ke+1)+"/"+De;De=(De>>>8&255)*192+(De&255),Se.put(De,13),ke+=2}if(ke<xe.length)throw"illegal char at "+(ke+1)},_e},ce=function(){var pe=[],ve={};return ve.writeByte=function(me){pe.push(me&255)},ve.writeShort=function(me){ve.writeByte(me),ve.writeByte(me>>>8)},ve.writeBytes=function(me,be,_e){be=be||0,_e=_e||me.length;for(var Se=0;Se<_e;Se+=1)ve.writeByte(me[Se+be])},ve.writeString=function(me){for(var be=0;be<me.length;be+=1)ve.writeByte(me.charCodeAt(be))},ve.toByteArray=function(){return pe},ve.toString=function(){var me="";me+="[";for(var be=0;be<pe.length;be+=1)be>0&&(me+=","),me+=pe[be];return me+="]",me},ve},fe=function(){var pe=0,ve=0,me=0,be="",_e={},Se=function(ke){be+=String.fromCharCode(xe(ke&63))},xe=function(ke){if(!(ke<0)){if(ke<26)return 65+ke;if(ke<52)return 97+(ke-26);if(ke<62)return 48+(ke-52);if(ke==62)return 43;if(ke==63)return 47}throw"n:"+ke};return _e.writeByte=function(ke){for(pe=pe<<8|ke&255,ve+=8,me+=1;ve>=6;)Se(pe>>>ve-6),ve-=6},_e.flush=function(){if(ve>0&&(Se(pe<<6-ve),pe=0,ve=0),me%3!=0)for(var ke=3-me%3,De=0;De<ke;De+=1)be+="="},_e.toString=function(){return be},_e},se=function(pe){var ve=pe,me=0,be=0,_e=0,Se={};Se.read=function(){for(;_e<8;){if(me>=ve.length){if(_e==0)return-1;throw"unexpected end of file./"+_e}var ke=ve.charAt(me);if(me+=1,ke=="=")return _e=0,-1;if(ke.match(/^\s$/))continue;be=be<<6|xe(ke.charCodeAt(0)),_e+=6}var De=be>>>_e-8&255;return _e-=8,De};var xe=function(ke){if(65<=ke&&ke<=90)return ke-65;if(97<=ke&&ke<=122)return ke-97+26;if(48<=ke&&ke<=57)return ke-48+52;if(ke==43)return 62;if(ke==47)return 63;throw"c:"+ke};return Se},de=function(pe,ve){var me=pe,be=ve,_e=new Array(pe*ve),Se={};Se.setPixel=function(Be,Ve,nt){_e[Ve*me+Be]=nt},Se.write=function(Be){Be.writeString("GIF87a"),Be.writeShort(me),Be.writeShort(be),Be.writeByte(128),Be.writeByte(0),Be.writeByte(0),Be.writeByte(0),Be.writeByte(0),Be.writeByte(0),Be.writeByte(255),Be.writeByte(255),Be.writeByte(255),Be.writeString(","),Be.writeShort(0),Be.writeShort(0),Be.writeShort(me),Be.writeShort(be),Be.writeByte(0);var Ve=2,nt=ke(Ve);Be.writeByte(Ve);for(var ot=0;nt.length-ot>255;)Be.writeByte(255),Be.writeBytes(nt,ot,255),ot+=255;Be.writeByte(nt.length-ot),Be.writeBytes(nt,ot,nt.length-ot),Be.writeByte(0),Be.writeString(";")};var xe=function(Be){var Ve=Be,nt=0,ot=0,ft={};return ft.write=function(it,ut){if(it>>>ut)throw"length over";for(;nt+ut>=8;)Ve.writeByte(255&(it<<nt|ot)),ut-=8-nt,it>>>=8-nt,ot=0,nt=0;ot=it<<nt|ot,nt=nt+ut},ft.flush=function(){nt>0&&Ve.writeByte(ot)},ft},ke=function(Be){for(var Ve=1<<Be,nt=(1<<Be)+1,ot=Be+1,ft=De(),it=0;it<Ve;it+=1)ft.add(String.fromCharCode(it));ft.add(String.fromCharCode(Ve)),ft.add(String.fromCharCode(nt));var ut=ce(),et=xe(ut);et.write(Ve,ot);var Ue=0,We=String.fromCharCode(_e[Ue]);for(Ue+=1;Ue<_e.length;){var tt=String.fromCharCode(_e[Ue]);Ue+=1,ft.contains(We+tt)?We=We+tt:(et.write(ft.indexOf(We),ot),ft.size()<4095&&(ft.size()==1<<ot&&(ot+=1),ft.add(We+tt)),We=tt)}return et.write(ft.indexOf(We),ot),et.write(nt,ot),et.flush(),ut.toByteArray()},De=function(){var Be={},Ve=0,nt={};return nt.add=function(ot){if(nt.contains(ot))throw"dup key:"+ot;Be[ot]=Ve,Ve+=1},nt.size=function(){return Ve},nt.indexOf=function(ot){return Be[ot]},nt.contains=function(ot){return typeof Be[ot]<"u"},nt};return Se},ue=function(pe,ve,me){for(var be=de(pe,ve),_e=0;_e<ve;_e+=1)for(var Se=0;Se<pe;Se+=1)be.setPixel(Se,_e,me(Se,_e));var xe=ce();be.write(xe);for(var ke=fe(),De=xe.toByteArray(),Be=0;Be<De.length;Be+=1)ke.writeByte(De[Be]);return ke.flush(),"data:image/gif;base64,"+ke};return q}();(function(){U.stringToBytesFuncs["UTF-8"]=function(q){function G(K){for(var Y=[],J=0;J<K.length;J++){var X=K.charCodeAt(J);X<128?Y.push(X):X<2048?Y.push(192|X>>6,128|X&63):X<55296||X>=57344?Y.push(224|X>>12,128|X>>6&63,128|X&63):(J++,X=65536+((X&1023)<<10|K.charCodeAt(J)&1023),Y.push(240|X>>18,128|X>>12&63,128|X>>6&63,128|X&63))}return Y}return G(q)}})(),function(q){$.exports=q()}(function(){return U})})(qrcode);var qrcodeExports=qrcode.exports;const qrGenerator=getDefaultExportFromCjs(qrcodeExports);var __defProp=Object.defineProperty,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=($,I,U)=>I in $?__defProp($,I,{enumerable:!0,configurable:!0,writable:!0,value:U}):$[I]=U,__spreadValues=($,I)=>{for(var U in I||(I={}))__hasOwnProp.call(I,U)&&__defNormalProp($,U,I[U]);if(__getOwnPropSymbols)for(var U of __getOwnPropSymbols(I))__propIsEnum.call(I,U)&&__defNormalProp($,U,I[U]);return $},__objRest=($,I)=>{var U={};for(var q in $)__hasOwnProp.call($,q)&&I.indexOf(q)<0&&(U[q]=$[q]);if($!=null&&__getOwnPropSymbols)for(var q of __getOwnPropSymbols($))I.indexOf(q)<0&&__propIsEnum.call($,q)&&(U[q]=$[q]);return U},VIEWPORT_SIZE=1e3,RE_CODE_LENGTH_OVERFLOW=/code length overflow/i;qrGenerator.stringToBytes=qrGenerator.stringToBytesFuncs["UTF-8"];var createQrCode=($,I,U)=>{U=Math.max(1,U);for(let q=U;q<=40;q+=1)try{const G=qrGenerator(q,I);G.addData($),G.make();const K=G.getModuleCount();return{text:$,level:I,version:q,moduleCount:K,isDark:(J,X)=>J>=0&&J<K&&X>=0&&X<K&&G.isDark(J,X)}}catch(G){if(!(q<40&&RE_CODE_LENGTH_OVERFLOW.test(String(G))))throw G}return null},round=Math.round,drawM=($,I)=>`M ${round($)} ${round(I)}`,drawL=($,I)=>`L ${round($)} ${round(I)}`,drawA=($,I,U)=>`A ${round(U)} ${round(U)} 0 0 1 ${round($)} ${round(I)}`,drawDark=($,I,U,q,G,K,Y,J,X)=>{const Z=[];return K?Z.push(drawM($+G,I)):Z.push(drawM($,I)),Y?Z.push(drawL(U-G,I),drawA(U,I+G,G)):Z.push(drawL(U,I)),J?Z.push(drawL(U,q-G),drawA(U-G,q,G)):Z.push(drawL(U,q)),X?Z.push(drawL($+G,q),drawA($,q-G,G)):Z.push(drawL($,q)),K?Z.push(drawL($,I+G),drawA($+G,I,G)):Z.push(drawL($,I)),Z.join(" ")},drawLight=($,I,U,q,G,K,Y,J,X)=>{const Z=[];return K&&Z.push(drawM($+G,I),drawL($,I),drawL($,I+G),drawA($+G,I,G)),Y&&Z.push(drawM(U,I+G),drawL(U,I),drawL(U-G,I),drawA(U,I+G,G)),J&&Z.push(drawM(U-G,q),drawL(U,q),drawL(U,q-G),drawA(U-G,q,G)),X&&Z.push(drawM($,q-G),drawL($,q),drawL($+G,q),drawA($,q-G,G)),Z.join(" ")},drawMod=($,I,U,q,G)=>{const K=G*U,Y=q*U,J=K+U,X=Y+U,Z=I*.005*U,Q=$.isDark,ee=q-1,te=q+1,ne=G-1,ie=G+1,oe=Q(q,G),ce=Q(ee,ne),fe=Q(ee,G),se=Q(ee,ie),de=Q(q,ie),ue=Q(te,ie),pe=Q(te,G),ve=Q(te,ne),me=Q(q,ne);return oe?drawDark(K,Y,J,X,Z,!fe&&!me,!fe&&!de,!pe&&!de,!pe&&!me):drawLight(K,Y,J,X,Z,fe&&me&&ce,fe&&de&&se,pe&&de&&ue,pe&&me&&ve)},createPath=($,I)=>{if(!$)return"";const U=$.moduleCount,q=VIEWPORT_SIZE/U,G=[];for(let K=0;K<U;K+=1)for(let Y=0;Y<U;Y+=1)G.push(drawMod($,I,q,K,Y));return G.join(" ")},QR=$=>{var I=$,{color:U="#000",backgroundColor:q,cutout:G=!1,cutoutElement:K,errorCorrectionLevel:Y="Q",rounding:J=0,children:X}=I,Z=__objRest(I,["color","backgroundColor","cutout","cutoutElement","errorCorrectionLevel","rounding","children"]),Q,ee;const te=React.useMemo(()=>createQrCode(X,Y,1),[X,Y]);if(!te)return null;const ne=(Q=te==null?void 0:te.moduleCount)!=null?Q:1,oe=VIEWPORT_SIZE/((ee=te==null?void 0:te.moduleCount)!=null?ee:1)*(Math.floor(ne*.18)*2-1)+2,ce=(VIEWPORT_SIZE-oe)/2;return React__namespace.createElement("svg",__spreadValues({xmlns:"http://www.w3.org/2000/svg",viewBox:`0 0 ${VIEWPORT_SIZE} ${VIEWPORT_SIZE}`},Z),G?React__namespace.createElement("mask",{id:"react-qr-rounded__mask"},React__namespace.createElement("rect",{x:"0",y:"0",width:VIEWPORT_SIZE,height:VIEWPORT_SIZE,fill:"#fff"}),React__namespace.createElement("rect",{x:ce,y:ce,width:oe,height:oe,rx:J,ry:J,fill:"#000"})):null,q?React__namespace.createElement("rect",{x:"0",y:"0",width:VIEWPORT_SIZE,height:VIEWPORT_SIZE,fill:q}):null,React__namespace.createElement("path",{fill:U,d:createPath(te,J),mask:G?"url(#react-qr-rounded__mask)":void 0}),K?React__namespace.createElement("foreignObject",{x:ce,y:ce,width:oe,height:oe},React__namespace.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",width:"100%",overflow:"hidden",borderRadius:J}},K)):null)};const invitationStatusValue=new Map([[Invitation.State.ERROR,-3],[Invitation.State.TIMEOUT,-2],[Invitation.State.CANCELLED,-1],[Invitation.State.INIT,0],[Invitation.State.CONNECTING,1],[Invitation.State.CONNECTED,2],[Invitation.State.READY_FOR_AUTHENTICATION,3],[Invitation.State.AUTHENTICATING,4],[Invitation.State.SUCCESS,5]]),InvitationManagerView=({children:$,...I})=>React.createElement(Viewport.View,{...I,classNames:"grow flex flex-col justify-around items-center"},$),InvitationManager=({invitationUrl:$,active:I,send:U,status:q,multiUse:G,authCode:K,id:Y="0"})=>{const{t:J}=useTranslation("os"),X=useId("invitation-manager__qr-code"),Z=G?0:invitationStatusValue.get(q)??0,Q=Z===3,ee=hexToEmoji(Y),te=React.useMemo(()=>{switch(!0){case Z===5:case Z<0:return"showing final";case Z===3:return"showing auth code";default:return"showing qr"}},[Z]);return React.createElement(React.Fragment,null,React.createElement(Viewport.Root,{activeView:te,classNames:"grow plb-1"},React.createElement(Viewport.Views,null,React.createElement(InvitationManagerView,{id:"showing qr",emoji:ee},React.createElement("p",{className:"text-sm mlb-1 font-normal text-center"},J(G?"invite many qr label":"invite one qr label")),React.createElement("div",{role:"none",className:mx(descriptionText,"is-full max-is-[14rem] relative")},React.createElement(QR,{rounding:100,backgroundColor:"transparent",color:"currentColor",className:mx("is-full bs-full p-2",Q&&"invisible"),"aria-labelledby":X,errorCorrectionLevel:"Q",cutout:!0},$??"never"),React.createElement(Centered,null,React.createElement(Emoji,{text:ee}))),React.createElement("span",{id:X,className:"sr-only"},J("qr label")),React.createElement(CopyButton,{variant:"ghost",value:$??"never"})),React.createElement(InvitationManagerView,{id:"showing auth code"},React.createElement(Label,null,J("auth code message")),React.createElement(AuthCode,{code:K,large:!0,classNames:"text-black dark:text-white"}),React.createElement(Label,null,"Be sure the other device is showing this symbol:"),ee&&React.createElement(Emoji,{text:ee})),React.createElement(InvitationManagerView,{id:"showing final"},Z>0?React.createElement(react.Check,{className:mx("m-1.5",getSize(6))}):React.createElement(react.X,{className:mx("m-1.5",getSize(6))})))),React.createElement(Actions,{classNames:"mbs-4"},React.createElement(Action,{disabled:!I,onClick:()=>U==null?void 0:U({type:"deselectInvitation"})},J("back label"))))},ConfirmReset=({active:$,onCancel:I,onConfirm:U,mode:q})=>{const{t:G}=useTranslation("os"),[K,Y]=React.useState(""),[J,X]=React.useState(!1),Z=async()=>(X(!0),U==null?void 0:U().then(()=>X(!1),Q=>{log$2.catch(Q),Y(G("failed to reset identity message")),X(!1)}));return React.createElement(ConfirmResetImpl,{disabled:!$,pending:J,validationMessage:K,onConfirm:Z,onCancel:I,mode:q})},ConfirmResetImpl=({disabled:$,pending:I,validationMessage:U,onConfirm:q,onCancel:G,mode:K})=>{const{t:Y}=useTranslation("os"),J=Y("confirmation value"),[X,Z]=React.useState(""),Q=K==="join new identity"?"join-new-identity":"reset-storage";return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col gap-2 justify-center"},React.createElement(Message$1.Root,{valence:"error"},React.createElement(Message$1.Title,null,React.createElement(react.Warning,{className:mx(getSize(6),"inline mie-2")}),Y("sign out chooser title")),React.createElement(Message$1.Body,null,Y("sign out chooser message"))),React.createElement(Input,{validationMessage:U,label:React.createElement(StepHeading,{className:"text-start mlb-2"},Y(K==="join new identity"?"join new identity input label":"reset storage input label",{confirmationValue:J})),disabled:$,"data-testid":`${Q}.reset-identity-input`,placeholder:J,onChange:({target:{value:ee}})=>Z(ee)})),React.createElement(Actions,null,G&&React.createElement(Action,{disabled:$,onClick:G,"data-testid":`${Q}.reset-identity-cancel`},Y("cancel label")),q&&React.createElement(Action,{variant:"destructive",disabled:$||I||X!==J,onClick:q,"data-testid":`${Q}.reset-identity-confirm`},Y(I?"reset in progress label":"reset device label"))))},viewStyles="pbs-1 pbe-3 pli-3",getHueValue=$=>{var I,U;return((U=(I=$==null?void 0:$.profile)==null?void 0:I.data)==null?void 0:U.hue)||hexToHue(($==null?void 0:$.identityKey.toHex())??"0")},getEmojiValue=$=>{var I,U;return((U=(I=$==null?void 0:$.profile)==null?void 0:I.data)==null?void 0:U.emoji)||hexToEmoji(($==null?void 0:$.identityKey.toHex())??"0")},IdentityHeading=({titleId:$,title:I,identity:U,onDone:q,onUpdateProfile:G,connectionState:K,onChangeConnectionState:Y})=>{var pe,ve;const J=keyToFallback(U.identityKey),{t:X}=useTranslation("os"),[Z,Q]=React.useState(((pe=U.profile)==null?void 0:pe.displayName)??""),[ee,te]=React.useState(getEmojiValue(U)),[ne,ie]=React.useState(getHueValue(U)),{textValue:oe,setTextValue:ce}=useClipboardContext(),fe=U.identityKey.toHex(),se=oe===fe,de=async()=>{const me={...Z&&{displayName:Z},...(ee||ne)&&{data:{...ee&&{emoji:ee},...ne&&{hue:ne}}}};return G==null?void 0:G(me)};React.useEffect(()=>{de()},[ee,ne]);const ue=K===ConnectionState$2.ONLINE;return React.createElement(Heading,{titleId:$,title:I,corner:React.createElement(CloseButton,{onDone:q})},React.createElement(Avatar.Root,{size:16,variant:"circle",status:ue?"active":"error",hue:ne||J.hue},React.createElement(Toolbar.Root,{classNames:"grid grid-cols-[1fr_var(--rail-action)_min-content_var(--rail-action)_1fr] items-center gap-2"},React.createElement(Tooltip.Root,null,React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:"bs-[--rail-action] is-[--rail-action] justify-self-end",onClick:()=>Y==null?void 0:Y(ue?ConnectionState$2.OFFLINE:ConnectionState$2.ONLINE)},React.createElement("span",{className:"sr-only"},X(ue?"disconnect label":"connect label")),ue?React.createElement(react.PlugsConnected,{className:getSize(5)}):React.createElement(react.Plugs,{className:getSize(5)}))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},X(ue?"disconnect label":"connect label"),React.createElement(Tooltip.Arrow,null)))),React.createElement(EmojiPickerToolbarButton,{emoji:ee,onChangeEmoji:te,classNames:"bs-[--rail-action]"}),React.createElement(Avatar.Frame,{classNames:"relative z-[2] -mli-4 chromatic-ignore"},React.createElement(Avatar.Fallback,{text:ee||J.emoji})),React.createElement(HuePickerToolbarButton,{hue:ne,onChangeHue:ie,classNames:"bs-[--rail-action]"}),React.createElement(Tooltip.Root,null,React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:"bs-[--rail-action] justify-self-start","data-testid":"update-profile-form-copy-key",onClick:()=>ce(fe)},React.createElement("span",{className:"sr-only"},X(se?"copy success label":"copy self public key label")),React.createElement(react.CopySimple,{className:getSize(5)}))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},X(se?"copy success label":"copy self public key label"),React.createElement(Tooltip.Arrow,null))))),React.createElement(Avatar.Label,{classNames:"sr-only","data-testid":"identityHeading.displayName"},((ve=U.profile)==null?void 0:ve.displayName)??generateName(U.identityKey.toHex())),React.createElement(Input$1.Root,null,React.createElement(Input$1.Label,{srOnly:!0},X("display name input label")),React.createElement(Input$1.TextInput,{variant:"subdued","data-testid":"display-name-input",placeholder:X("display name input placeholder"),classNames:"mbs-2 text-center font-light text-xl",value:Z,onChange:({target:{value:me}})=>{Q(me)},onBlur:de}))))},IdentityPanelImpl=$=>{const{identity:I,titleId:U,activeView:q,onUpdateProfile:G,onResetStorage:K,onJoinNewIdentity:Y,IdentityActionChooser:J=IdentityActionChooser,InvitationManager:X=InvitationManager,connectionState:Z,onChangeConnectionState:Q,onDone:ee,...te}=$,{t:ne}=useTranslation("os"),ie=React.useMemo(()=>{switch(q){case"device invitation manager":return ne("choose add device label");default:return ne("identity heading")}},[q,ne]),oe=()=>{var ce;return(ce=te.send)==null?void 0:ce.call(te,"unchooseAction")};return React.createElement(DensityProvider,{density:"fine"},React.createElement(IdentityHeading,{identity:I,titleId:U,title:ie,onDone:ee,onUpdateProfile:G,connectionState:Z,onChangeConnectionState:Q}),React.createElement(Viewport.Root,{activeView:q},React.createElement(Viewport.Views,null,React.createElement(Viewport.View,{id:"identity action chooser",classNames:viewStyles},React.createElement(J,{active:q==="identity action chooser",...te})),React.createElement(Viewport.View,{id:"device invitation manager",classNames:viewStyles},React.createElement(X,{active:q==="device invitation manager",...te,invitationUrl:te.createInvitationUrl(te.invitationCode)})),React.createElement(Viewport.View,{classNames:viewStyles,id:"confirm join new identity"},React.createElement(ConfirmReset,{active:q==="confirm join new identity",...te,mode:"join new identity",onConfirm:Y,onCancel:oe})),React.createElement(Viewport.View,{classNames:viewStyles,id:"confirm reset storage"},React.createElement(ConfirmReset,{active:q==="confirm reset storage",...te,mode:"reset storage",onConfirm:K,onCancel:oe})))))},IdentityPanelWithInvitationImpl=({invitation:$,...I})=>{const U=useInvitationStatus($);return React.createElement(IdentityPanelImpl,{...I,...U})},IdentityPanel=({titleId:$,createInvitationUrl:I=G=>G,initialDisposition:U="default",...q})=>{const G=useId("identityPanel__heading",$),K=reactClient.useClient(),Y=halo.useDevices(),J=halo.useIdentity(),X=halo.useHaloInvitations(),Z=useAgentHandlers({client:K,identity:J,invitations:X});if(!J)return log$2.error("IdentityPanel rendered with no active identity."),null;const[Q,ee,te]=useIdentityMachine(K,{context:{initialDisposition:U}}),{swarm:ne}=useNetworkStatus(),ie=async se=>K==null?void 0:K.mesh.updateConfig(se);React.useEffect(()=>te.subscribe(de=>{log$2("[state]",de)}).unsubscribe,[te]);const oe=React.useMemo(()=>{switch(!0){case Q.matches("choosingAction"):return"identity action chooser";case Q.matches("managingDeviceInvitation"):return"device invitation manager";case Q.matches("confirmingResetStorage"):return"confirm reset storage";case Q.matches("confirmingJoinNewIdentity"):return"confirm join new identity";default:return"identity action chooser"}},[Q]),fe={...q,identity:J,devices:Y,activeView:oe,send:ee,titleId:G,createInvitationUrl:I,onUpdateProfile:async se=>{ee({type:"updateProfile"}),await K.halo.updateProfile(se)},connectionState:ne,onChangeConnectionState:ie,...Z};return Q.context.invitation?React.createElement(IdentityPanelWithInvitationImpl,{...fe,invitation:Q.context.invitation}):React.createElement(IdentityPanelImpl,{...fe})},JoinHeading=React.forwardRef(({mode:$,titleId:I,onExit:U,exitActionParent:q},G)=>{const{t:K}=useTranslation("os"),Y=React.createElement(Button,{variant:"ghost",...U&&{onClick:U},classNames:mx(descriptionText,"plb-0 pli-2 absolute block-start-0 inline-end-0 z-[1]"),"data-testid":"join-exit"},React.createElement(react.X,{weight:"bold",className:getSize(4)}),React.createElement("span",{className:"sr-only"},K("exit label")));return React.createElement(Heading,{ref:G,titleId:I,title:K($==="halo-only"?"selecting identity heading":"joining space heading"),...$==="halo-only"?{titleSrOnly:!0}:{corner:q?React.cloneElement(q,{},Y):Y},titleSrOnly:$==="halo-only"})}),getInvitationSubscribable=($,I)=>(log$2("[subscribing to invitation]",I),{subscribe:(U,q,G)=>I.subscribe(K=>{switch(K.state){case Invitation.State.CONNECTING:return log$2("[invitation connecting]",{Kind:$,invitation:K}),U({type:`connecting${$}Invitation`,invitation:K});case Invitation.State.CONNECTED:return log$2("[invitation connected]",{Kind:$,invitation:K}),U({type:`connected${$}Invitation`,invitation:K});case Invitation.State.READY_FOR_AUTHENTICATION:return log$2("[invitation ready for authentication]",{Kind:$,invitation:K}),U({type:`readyForAuthentication${$}Invitation`,invitation:K});case Invitation.State.AUTHENTICATING:return log$2("[invitation authenticating]",{Kind:$,invitation:K}),U({type:`authenticating${$}Invitation`,invitation:K});case Invitation.State.SUCCESS:return log$2("[invitation success]",{Kind:$,invitation:K}),U({type:`success${$}Invitation`,invitation:K}),G==null?void 0:G();case Invitation.State.CANCELLED:return log$2.warn("[invitation cancelled]",{Kind:$}),U({type:`fail${$}Invitation`,reason:"cancelled"});case Invitation.State.TIMEOUT:return log$2.error("[invitation timeout]",{Kind:$}),U({type:`fail${$}Invitation`,reason:"timeout"})}},K=>K instanceof reactClient.AlreadyJoinedError?(log$2("[already joined]",{Kind:$,error:K}),U({type:`success${$}Invitation`,invitation:I.get()}),G==null?void 0:G()):(log$2.error("[invitation errored]",{Kind:$,error:K}),U({type:`fail${$}Invitation`,reason:"error"}),q==null?void 0:q(K)))}),acceptingInvitationTemplate=($,I)=>({initial:`unknown${$}`,states:{[`unknown${$}`]:{always:[{cond:({mode:q})=>q==="halo-only"&&$==="Space",target:"#join.finishingJoiningHalo"},{cond:q=>!!q[$.toLowerCase()].unredeemedCode,target:`acceptingRedeemed${$}Invitation`,actions:[`redeem${$}InvitationCode`,`invalidate${$}InvitationCode`,"log"]},{target:`inputting${$}InvitationCode`,actions:"log"}]},[`inputting${$}InvitationCode`]:{},[`acceptingRedeemed${$}Invitation`]:{invoke:{src:q=>q[$.toLowerCase()].invitationSubscribable},initial:`unknown${$}Invitation`,states:{[`unknown${$}Invitation`]:{always:[{cond:q=>{var G,K;if($!=="Space")return!1;{const Y=(K=(G=q.space.invitation)==null?void 0:G.spaceKey)==null?void 0:K.toHex(),J=q.space.succeededKeys;return Y?!!(J!=null&&J.has(Y)):!1}},target:I,actions:"log"},{cond:q=>{const G=q[$.toLowerCase()].invitation;return!G||(G==null?void 0:G.state)===Invitation.State.CONNECTING},target:`connecting${$}Invitation`,actions:"log"},{target:`inputting${$}VerificationCode`,actions:"log"}]},[`connecting${$}Invitation`]:{},[`inputting${$}VerificationCode`]:{},[`authenticating${$}VerificationCode`]:{on:{[`readyForAuthentication${$}Invitation`]:{target:`authenticationFailing${$}VerificationCode`,actions:["setInvitation","log"]}}},[`authenticationFailing${$}VerificationCode`]:{},[`failing${$}Invitation`]:{},[`success${$}Invitation`]:{}},on:{[`reset${$}Invitation`]:{target:`#join${$==="Halo"?".choosingIdentity":""}.accepting${$}Invitation.unknown${$}`,actions:["resetInvitation","log"]},[`connecting${$}Invitation`]:{target:`.connecting${$}Invitation`,actions:["setInvitation","log"]},[`connected${$}Invitation`]:{target:`.connecting${$}Invitation`,actions:["setInvitation","log"]},[`readyForAuthentication${$}Invitation`]:{target:`.inputting${$}VerificationCode`,actions:["setInvitation","log"]},[`authenticating${$}Invitation`]:{target:`.authenticating${$}VerificationCode`,actions:["setInvitation","log"]},[`success${$}Invitation`]:{target:I,actions:["setInvitation","log"]},[`fail${$}Invitation`]:{target:`.failing${$}Invitation`,actions:[assign({[$.toLowerCase()]:(q,G)=>({...q[$.toLowerCase()],failReason:G.reason})}),"log"]}}}},on:{[`set${$}InvitationCode`]:{target:`.acceptingRedeemed${$}Invitation`,actions:[assign({[$.toLowerCase()]:(q,G)=>({...q[$.toLowerCase()],unredeemedCode:G.code,succeededKeys:G.succeededKeys})}),`redeem${$}InvitationCode`,`invalidate${$}InvitationCode`,"log"]}}}),joinMachine=createMachine({id:"join",predictableActionArguments:!0,context:{initialDisposition:"default",mode:"default",identity:null,halo:{},space:{}},initial:"unknown",states:{unknown:{always:[{cond:"existingIdentity",target:"resettingIdentity",actions:"log"},{cond:"initiallyAcceptingHaloInvitation",target:"#join.choosingIdentity.acceptingHaloInvitation",actions:"log"},{cond:"noSelectedIdentity",target:"choosingIdentity",actions:"log"},{target:"acceptingSpaceInvitation",actions:"log"}]},choosingIdentity:{initial:"unknownAuthMethod",states:{unknownAuthMethod:{always:[{cond:"hasHaloUnredeemedCode",target:"acceptingHaloInvitation",actions:"log"},{target:"choosingAuthMethod",actions:"log"}]},choosingAuthMethod:{},recoveringIdentity:{},creatingIdentity:{},acceptingHaloInvitation:acceptingInvitationTemplate("Halo","#join.acceptingSpaceInvitation"),confirmingAddedIdentity:{}},on:{recoverIdentity:{target:".recoveringIdentity",actions:"log"},createIdentity:{target:".creatingIdentity",actions:"log"},acceptHaloInvitation:{target:".acceptingHaloInvitation",actions:"log"},addIdentity:{target:".confirmingAddedIdentity",actions:"log"},selectIdentity:{target:"acceptingSpaceInvitation",actions:["setIdentity","log"]},deselectAuthMethod:{target:".choosingAuthMethod",actions:"log"}}},resettingIdentity:{},acceptingSpaceInvitation:acceptingInvitationTemplate("Space","#join.finishingJoiningSpace"),finishingJoiningSpace:{type:"final"},finishingJoiningHalo:{type:"final"}},on:{resetIdentity:{target:"choosingIdentity",actions:"unsetIdentity"}}},{guards:{existingIdentity:({identity:$,mode:I},U)=>I==="halo-only"&&!!$,noSelectedIdentity:({identity:$},I)=>!$,initiallyAcceptingHaloInvitation:({identity:$,initialDisposition:I},U)=>!$&&I==="accept-halo-invitation",hasHaloUnredeemedCode:({halo:$},I)=>!!$.unredeemedCode,noSpaceInvitation:({space:$},I)=>!$.invitation&&!$.unredeemedCode},actions:{setIdentity:assign({identity:($,I)=>I.identity}),unsetIdentity:assign({identity:()=>null}),resetInvitation:assign({halo:($,I)=>I.type!=="resetHaloInvitation"?$.halo:($.halo.invitationObservable&&$.halo.invitationObservable.cancel(),{...$.halo,invitation:void 0,invitationObservable:void 0,invitationSubscribable:void 0}),space:($,I)=>I.type!=="resetSpaceInvitation"?$.space:($.space.invitationObservable&&$.space.invitationObservable.cancel(),{...$.space,invitation:void 0,invitationObservable:void 0,invitationSubscribable:void 0})}),setInvitation:assign({halo:($,I)=>I.type.includes("Halo")?{...$.halo,invitation:I.invitation}:$.halo,space:($,I)=>I.type.includes("Space")?{...$.space,invitation:I.invitation}:$.space}),log:($,I)=>{log$2("[transition]",{event:I,haloInvitation:$.halo.invitation,spaceInvitation:$.space.invitation})}}}),defaultCodeFromUrl=($,I)=>{try{const U=new URLSearchParams(I.substring(I.lastIndexOf("?")));return U.get(`${$}InvitationCode`)??U.get(`${$}Invitation`)??U.get("invitationCode")??U.get("invitation")??I}catch(U){return log$2.catch(U),I}},useJoinMachine=($,I)=>{const U=React.useCallback(({halo:Y})=>{if(Y.unredeemedCode)try{const J=clientProtocol.InvitationEncoder.decode(defaultCodeFromUrl("halo",Y.unredeemedCode)),X=$.halo.join(J);return{...Y,invitationObservable:X,invitationSubscribable:getInvitationSubscribable("Halo",X)}}catch(J){return log$2.error("Could not redeem device invitation code",J),Y}else return Y},[$]),q=React.useCallback(({space:Y})=>{if(Y.unredeemedCode)try{const J=clientProtocol.InvitationEncoder.decode(defaultCodeFromUrl("space",Y.unredeemedCode)),X=$.spaces.join(J);return{...Y,invitationObservable:X,invitationSubscribable:getInvitationSubscribable("Space",X)}}catch(J){return log$2.error("Could not redeem space invitation code",J),Y}else return Y},[$]),G=React.useCallback(({halo:Y})=>{var J;return Y.unredeemedCode?((J=I==null?void 0:I.onInvalidateInvitationCode)==null||J.call(I,Y.unredeemedCode),{...Y,unredeemedCode:void 0}):Y},[I==null?void 0:I.onInvalidateInvitationCode]),K=React.useCallback(({space:Y})=>{var J;return Y.unredeemedCode?((J=I==null?void 0:I.onInvalidateInvitationCode)==null||J.call(I,Y.unredeemedCode),{...Y,unredeemedCode:void 0}):Y},[I==null?void 0:I.onInvalidateInvitationCode]);return useMachine(joinMachine,{...I,actions:{...I==null?void 0:I.actions,redeemHaloInvitationCode:assign({halo:U}),redeemSpaceInvitationCode:assign({space:q}),invalidateHaloInvitationCode:assign({halo:G}),invalidateSpaceInvitationCode:assign({space:K})}})},AdditionMethodChooser=$=>{const I=!$.active,{send:U}=$,{t:q}=useTranslation("os"),G={disabled:I,after:React.createElement(react.CaretRight,{className:getSize(4),weight:"bold"}),slots:{label:{className:"text-sm"}}};return React.createElement(React.Fragment,null,React.createElement(StepHeading,null,q("addition method chooser title")),React.createElement("div",{role:"none",className:"flex flex-col gap-1 grow"},React.createElement(CompoundButton,{...G,description:q("create identity description"),before:React.createElement(react.Plus,{className:getSize(6)}),onClick:()=>U({type:"createIdentity"}),"data-autofocus":"choosingAuthMethod","data-testid":"identity-chooser.create-identity"},q("create identity label")),React.createElement(CompoundButton,{...G,description:q("join identity description"),before:React.createElement(react.QrCode,{className:getSize(6)}),onClick:()=>U({type:"acceptHaloInvitation"}),"data-testid":"identity-chooser.join-identity"},q("join identity label")),React.createElement(CompoundButton,{...G,disabled:!0,description:q("recover identity description"),before:React.createElement(react.Textbox,{className:getSize(6)}),onClick:()=>U({type:"recoverIdentity"}),"data-testid":"identity-chooser.recover-identity"},q("recover identity label"))))},IdentityAdded=$=>{var ie,oe,ce,fe,se,de;const{mode:I,addedIdentity:U,active:q,send:G,onDone:K,doneActionParent:Y}=$,J=!q,{t:X}=useTranslation("os"),Z=(U==null?void 0:U.identityKey.toHex())??"0",Q=hexToFallback(Z),ee=useId("identityListItem__label"),te=((ie=U==null?void 0:U.profile)==null?void 0:ie.displayName)??(U&&generateName(Z)),ne=React.createElement(Action,{...K&&{onClick:()=>K(null)},disabled:J,"data-autofocus":"confirmingAddedIdentity","data-testid":"identity-added-done"},React.createElement("span",null,X("done label")));return React.createElement(React.Fragment,null,React.createElement(StepHeading,null,X("identity added label")),React.createElement("div",{role:"none",className:"grow flex flex-col items-center justify-center text-center gap-2"},React.createElement(Avatar.Root,{status:"active",labelId:ee,hue:((ce=(oe=U==null?void 0:U.profile)==null?void 0:oe.data)==null?void 0:ce.hue)||Q.hue},React.createElement(Avatar.Frame,null,React.createElement(Avatar.Fallback,{text:((se=(fe=U==null?void 0:U.profile)==null?void 0:fe.data)==null?void 0:se.emoji)||Q.emoji})),React.createElement(Avatar.Label,{classNames:mx("text-lg truncate",!((de=U==null?void 0:U.profile)!=null&&de.displayName)&&"font-mono")},te))),React.createElement(Actions,null,I==="halo-only"?Y?React.cloneElement(Y,{},ne):ne:React.createElement(Action,{variant:"primary",disabled:J||!U,onClick:()=>U&&G({type:"selectIdentity",identity:U}),"data-autofocus":"confirmingAddedIdentity"},X("continue label"))))},IdentityInput=$=>{const{send:I,method:U}=$,q=U==="recover identity",G=reactClient.useClient(),{t:K}=useTranslation("os"),[Y,J]=React.useState(""),X=Z=>{G.halo.createIdentity({[q?"seedphrase":"displayName"]:Z}).then(Q=>{I==null||I({type:"selectIdentity",identity:Q})},Q=>{log$2.catch(Q),J(K(q?"failed to recover identity message":"failed to create identity message"))})};return React.createElement(IdentityInputImpl,{...$,onDisplayNameConfirm:X,validationMessage:Y})},IdentityInputImpl=$=>{const{method:I,send:U,active:q,onDisplayNameConfirm:G,validationMessage:K}=$,Y=!q,{t:J}=useTranslation("os"),[X,Z]=React.useState(""),Q=I==="recover identity";return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},React.createElement(Input,{validationMessage:K,label:React.createElement(StepHeading,null,J(Q?"recover identity input label":"new identity input label")),disabled:Y,"data-testid":"identity-input",placeholder:Q?"Type your recovery phrase":"Type a display name",onChange:({target:{value:ee}})=>Z(ee)})),React.createElement(Actions,null,React.createElement(Action,{variant:"ghost",disabled:Y,onClick:()=>U==null?void 0:U({type:"deselectAuthMethod"}),"data-testid":`${I==="recover identity"?"recover":"create"}-identity-input-back`},J("back label")),React.createElement(Action,{variant:"primary",disabled:Y,onClick:()=>G==null?void 0:G(X),"data-testid":`${I==="recover identity"?"recover":"create"}-identity-input-continue`},J("continue label"))))},InvitationAccepted=$=>{const{active:I,Kind:U,doneActionParent:q,onDone:G}=$,K=!I,{t:Y}=useTranslation("os"),J=React.createElement(Action,{variant:"primary",onClick:G,disabled:K,"data-autofocus":`success${U}Invitation finishingJoining${U}`,"data-testid":`${U.toLowerCase()}-invitation-accepted-done`},Y("done label"));return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},React.createElement("p",{className:"text-center text-sm font-normal"},Y("welcome message"))),React.createElement(Actions,null,q?React.cloneElement(q,{},J):J))},invitationCodeFromUrl=$=>{try{const I=new URLSearchParams($.substring($.lastIndexOf("?")));return I.get("spaceInvitationCode")??I.get("deviceInvitationCode")??$}catch(I){return log$2.catch(I),$}},InvitationInput=$=>{const{Kind:I,active:U,send:q,unredeemedCode:G,onExit:K,exitActionParent:Y,onDone:J,doneActionParent:X,succeededKeys:Z}=$,Q=!U,{t:ee}=useTranslation("os"),[te,ne]=React.useState(G??"");React.useEffect(()=>{G&&ne(G??"")},[G]);const ie=()=>{te.trim().length!==0&&q({type:`set${I}InvitationCode`,code:invitationCodeFromUrl(te),...I==="Space"&&{succeededKeys:Z}})},oe=React.createElement(Action,{variant:"ghost",disabled:Q,...K?{onClick:()=>K()}:{onClick:()=>J==null?void 0:J(null)},"data-testid":"join-exit"},ee("cancel label"));return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},React.createElement(Input,{label:React.createElement(StepHeading,null,ee("invitation input label")),placeholder:"Type an invitation code",disabled:Q,value:te,onChange:({target:{value:ce}})=>ne(ce),"data-autofocus":`inputting${I}InvitationCode`,"data-testid":`${I.toLowerCase()}-invitation-input`,onKeyUp:({key:ce})=>ce==="Enter"&&ie()})),React.createElement(Actions,null,I==="Halo"?React.createElement(Action,{variant:"ghost",disabled:Q,onClick:()=>q({type:"deselectAuthMethod"}),"data-testid":`${I.toLowerCase()}-invitation-input-back`},ee("back label")):Y?React.cloneElement(Y,{},oe):X?React.cloneElement(X,{},oe):oe,React.createElement(Action,{variant:"primary",disabled:Q,onClick:ie,"data-testid":`${I.toLowerCase()}-invitation-input-continue`},ee("continue label"))))},InvitationActions=({invitationState:$,onInvitationCancel:I,active:U,send:q,Kind:G,failReason:K})=>{const{t:Y}=useTranslation("os");return K?React.createElement(React.Fragment,null,React.createElement(StepHeading,{className:descriptionText},Y(K==="timeout"?"timeout status label":K==="cancelled"?"cancelled status label":"error status label")),React.createElement("div",{role:"none",className:"grow"}),React.createElement(Actions,null,React.createElement(Action,{disabled:!U,onClick:()=>q({type:`reset${G}Invitation`}),"data-testid":"invitation-rescuer-reset"},Y("reset label")))):React.createElement(React.Fragment,null,React.createElement(StepHeading,{className:descriptionText},Y("connecting status label")),React.createElement("div",{role:"none",className:"grow"}),React.createElement(Actions,null,React.createElement(Action,{disabled:!0,classNames:"order-2","data-testid":"next"},Y("next label")),React.createElement(Action,{disabled:!U,onClick:I,"data-testid":"invitation-rescuer-cancel"},Y("cancel label"))))},InvitationRescuer=$=>{const{Kind:I,invitationState:U,active:q,send:G}=$,{t:K}=useTranslation("os");return React.createElement(React.Fragment,null,typeof U>"u"?React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},React.createElement(StepHeading,{className:descriptionText},"There was a problem joining the space")),React.createElement(Actions,null,React.createElement(Action,{disabled:!q,"data-testid":"invitation-rescuer-blank-reset",onClick:()=>G({type:`reset${I}Invitation`})},K("reset label")))):React.createElement(InvitationActions,{...$}))},pinLength=6,InvitationAuthenticator=({failed:$,Kind:I,active:U,pending:q,invitationId:G,onInvitationAuthenticate:K,onInvitationCancel:Y})=>{const J=!U||q,{t:X}=useTranslation("os"),Z=I.toLowerCase(),[Q,ee]=React.useState(""),te=({target:{value:ne}})=>{var ie;ee(ne),ne.length===pinLength&&((ie=document.querySelector(`[data-autofocus-pinlength="${Z}"]`))==null||ie.focus())};return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},G&&React.createElement(Emoji,{text:hexToEmoji(G)}),React.createElement(Input$1.Root,{...$&&{validationValence:"error"}},React.createElement(Input$1.Label,{asChild:!0},React.createElement(StepHeading,null,X("auth code input label"))),React.createElement(Input$1.PinInput,{disabled:J,length:pinLength,onChange:te,inputMode:"numeric",autoComplete:"off",pattern:"\\d*","data-autofocus":`connecting${I}Invitation inputting${I}VerificationCode authenticationFailing${I}VerificationCode authenticating${I}VerificationCode`,"data-prevent-ios-autofocus":!0,"data-testid":`${Z}-auth-code-input`,"data-1p-ignore":!0}),$&&React.createElement(Input$1.DescriptionAndValidation,{classNames:"text-center"},React.createElement(Input$1.Validation,null,X("failed to authenticate message"))))),React.createElement(Actions,null,React.createElement(Action,{variant:"ghost",disabled:J,onClick:()=>Y==null?void 0:Y(),"data-testid":`${Z}-invitation-authenticator-cancel`},X("cancel label")),React.createElement(Action,{variant:"primary",disabled:J,onClick:()=>K==null?void 0:K(Q),"data-autofocus-pinlength":Z,"data-testid":`${Z}-invitation-authenticator-next`},X("next label"))))},stepStyles="pbs-1 pbe-3 pli-3",JoinPanelImpl=$=>{const{titleId:I,send:U,activeView:q,failed:G,mode:K,unredeemedCodes:Y,invitationStates:J,succeededKeys:X,failReasons:Z,onExit:Q,onHaloDone:ee,onSpaceDone:te,exitActionParent:ne,doneActionParent:ie,onHaloInvitationCancel:oe,onSpaceInvitationCancel:ce,onHaloInvitationAuthenticate:fe,onSpaceInvitationAuthenticate:se,onCancelResetStorage:de,onConfirmResetStorage:ue,IdentityInput:pe=IdentityInput,ConfirmReset:ve=ConfirmReset}=$;return React.createElement(DensityProvider,{density:"fine"},K!=="halo-only"&&React.createElement(JoinHeading,{titleId:I,mode:K,onExit:Q,exitActionParent:ne}),React.createElement(Viewport.Root,{focusManaged:!0,activeView:q},React.createElement(Viewport.Views,null,React.createElement(Viewport.View,{classNames:stepStyles,id:"addition method chooser"},React.createElement(AdditionMethodChooser,{send:U,active:q==="addition method chooser"})),React.createElement(Viewport.View,{classNames:stepStyles,id:"reset storage confirmation"},React.createElement(ve,{send:U,active:q==="reset identity confirmation",onCancel:de,onConfirm:ue})),React.createElement(Viewport.View,{classNames:stepStyles,id:"create identity input"},React.createElement(pe,{send:U,method:"create identity",active:q==="create identity input"})),React.createElement(Viewport.View,{classNames:stepStyles,id:"recover identity input"},React.createElement(pe,{send:U,method:"recover identity",active:q==="recover identity input"})),React.createElement(Viewport.View,{classNames:stepStyles,id:"halo invitation input"},React.createElement(InvitationInput,{send:U,Kind:"Halo",active:q==="halo invitation input",...(Y==null?void 0:Y.Halo)&&{unredeemedCode:Y.Halo},...(X==null?void 0:X.Halo)&&{succeededKeys:X.Halo}})),React.createElement(Viewport.View,{classNames:stepStyles,id:"halo invitation rescuer"},React.createElement(InvitationRescuer,{send:U,Kind:"Halo",active:q==="halo invitation rescuer",invitationState:J==null?void 0:J.Halo,onInvitationCancel:oe,failReason:Z==null?void 0:Z.Halo})),React.createElement(Viewport.View,{classNames:stepStyles,id:"halo invitation authenticator"},React.createElement(InvitationAuthenticator,{send:U,Kind:"Halo",active:q==="halo invitation authenticator",onInvitationCancel:oe,onInvitationAuthenticate:fe,...G.has("Halo")&&{failed:!0}})),React.createElement(Viewport.View,{classNames:stepStyles,id:"halo invitation accepted"},React.createElement(InvitationAccepted,{send:U,Kind:"Halo",active:q==="halo invitation accepted",doneActionParent:ie,onDone:ee})),React.createElement(Viewport.View,{classNames:stepStyles,id:"identity added"},React.createElement(IdentityAdded,{send:U,mode:K,active:q==="identity added",doneActionParent:ie,onDone:ee})),React.createElement(Viewport.View,{classNames:stepStyles,id:"space invitation input"},React.createElement(InvitationInput,{send:U,Kind:"Space",active:q==="space invitation input",...(Y==null?void 0:Y.Space)&&{unredeemedCode:Y.Space},...(X==null?void 0:X.Space)&&{succeededKeys:X.Space},onExit:Q,exitActionParent:ne})),React.createElement(Viewport.View,{classNames:stepStyles,id:"space invitation rescuer"},React.createElement(InvitationRescuer,{send:U,Kind:"Space",active:q==="space invitation rescuer",invitationState:J==null?void 0:J.Space,onInvitationCancel:ce,failReason:Z==null?void 0:Z.Space})),React.createElement(Viewport.View,{classNames:stepStyles,id:"space invitation authenticator"},React.createElement(InvitationAuthenticator,{send:U,Kind:"Space",active:q==="space invitation authenticator",onInvitationCancel:ce,onInvitationAuthenticate:se,...G.has("Space")&&{failed:!0}})),React.createElement(Viewport.View,{classNames:stepStyles,id:"space invitation accepted"},React.createElement(InvitationAccepted,{send:U,Kind:"Space",active:q==="space invitation accepted",doneActionParent:ie,onDone:te})))))},JoinPanel=({titleId:$,mode:I="default",initialDisposition:U="default",initialInvitationCode:q,exitActionParent:G,onExit:K,doneActionParent:Y,onDone:J,onCancelResetStorage:X})=>{const Z=reactClient.useClient(),Q=halo.useIdentity(),{hasIosKeyboard:ee}=useThemeContext(),te=useId("joinPanel__heading",$),[ne,ie,oe]=useJoinMachine(Z,{context:{mode:I,initialDisposition:U,identity:Q,...q&&{[I==="halo-only"?"halo":"space"]:{unredeemedCode:q}}}});React.useEffect(()=>oe.subscribe(xe=>{log$2("[state]",xe)}).unsubscribe,[oe]),React.useEffect(()=>{const Se=ne.configuration[0].id.split("."),xe=Se[Se.length-1],ke=xe==="finishingJoining"?"successSpaceInvitation":xe,De=document.querySelector(`[data-autofocus~="${ke}"]`);De&&!(ee&&De.hasAttribute("data-prevent-ios-autofocus"))&&De.focus()},[ne.value,ee]);const ce=React.useMemo(()=>{switch(!0){case ne.matches({choosingIdentity:"choosingAuthMethod"}):return"addition method chooser";case ne.matches("resettingIdentity"):return"reset identity confirmation";case ne.matches({choosingIdentity:"creatingIdentity"}):return"create identity input";case ne.matches({choosingIdentity:"recoveringIdentity"}):return"recover identity input";case ne.matches({choosingIdentity:{acceptingHaloInvitation:"inputtingHaloInvitationCode"}}):return"halo invitation input";case[{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"connectingHaloInvitation"}}},{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"failingHaloInvitation"}}}].some(ne.matches):return"halo invitation rescuer";case[{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"inputtingHaloVerificationCode"}}},{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"authenticatingHaloVerificationCode"}}},{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"authenticationFailingHaloVerificationCode"}}}].some(ne.matches):return"halo invitation authenticator";case[{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"successHaloInvitation"}}},"finishingJoiningHalo"].some(ne.matches):return"halo invitation accepted";case ne.matches({choosingIdentity:"confirmingAddedIdentity"}):return"identity added";case ne.matches({acceptingSpaceInvitation:"inputtingSpaceInvitationCode"}):return"space invitation input";case[{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"connectingSpaceInvitation"}},{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"failingSpaceInvitation"}}].some(ne.matches):return"space invitation rescuer";case[{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"inputtingSpaceVerificationCode"}},{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"authenticatingSpaceVerificationCode"}},{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"authenticationFailingSpaceVerificationCode"}}].some(ne.matches):return"space invitation authenticator";case ne.matches("finishingJoiningSpace"):return"space invitation accepted";default:return"never"}},[ne]),fe=React.useMemo(()=>{const Se=new Set;switch(!0){case ne.matches({choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"authenticationFailingHaloVerificationCode"}}}):Se.add("Halo");break;case ne.matches({acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"authenticationFailingSpaceVerificationCode"}}):Se.add("Space");break}return Se},[ne]),se=React.useMemo(()=>({Halo:ne.context.halo.unredeemedCode,Space:ne.context.space.unredeemedCode}),[ne]),de=reactClient.useMulticastObservable(Z.spaces),ue=React.useMemo(()=>({Space:de?new Set(de.map(({key:Se})=>Se.toHex())):void 0}),[de]),pe=React.useMemo(()=>{var Se,xe;return{Halo:(Se=ne.context.halo.invitationObservable)==null?void 0:Se.get().state,Space:(xe=ne.context.space.invitationObservable)==null?void 0:xe.get().state}},[ne]),ve=React.useMemo(()=>({Halo:ne.context.halo.failReason,Space:ne.context.space.failReason}),[ne]),me=React.useCallback(()=>{var Se,xe,ke,De;J==null||J({identityKey:((Se=ne.context.halo.invitation)==null?void 0:Se.identityKey)??null,swarmKey:((xe=ne.context.halo.invitation)==null?void 0:xe.swarmKey)??null,spaceKey:((ke=ne.context.halo.invitation)==null?void 0:ke.spaceKey)??null,target:((De=ne.context.halo.invitation)==null?void 0:De.target)??null})},[ne,J]),be=React.useCallback(()=>{var Se,xe,ke,De;J==null||J({identityKey:((Se=ne.context.space.invitation)==null?void 0:Se.identityKey)??null,swarmKey:((xe=ne.context.space.invitation)==null?void 0:xe.swarmKey)??null,spaceKey:((ke=ne.context.space.invitation)==null?void 0:ke.spaceKey)??null,target:((De=ne.context.space.invitation)==null?void 0:De.target)??null})},[ne,J]),_e=React.useCallback(()=>Z.reset().then(()=>{ie({type:"resetIdentity"})}),[Z,ie]);return React.createElement(JoinPanelImpl,{titleId:te,mode:I,send:ie,activeView:ce,failed:fe,failReasons:ve,pending:["connecting","authenticating"].some(Se=>ne==null?void 0:ne.configuration[0].id.includes(Se)),unredeemedCodes:se,invitationStates:pe,succeededKeys:ue,identity:Q,onExit:K,exitActionParent:G,doneActionParent:Y,onHaloDone:me,onSpaceDone:be,onHaloInvitationCancel:()=>{var Se;return(Se=ne.context.halo.invitationObservable)==null?void 0:Se.cancel()},onSpaceInvitationCancel:()=>{var Se;return(Se=ne.context.space.invitationObservable)==null?void 0:Se.cancel()},onHaloInvitationAuthenticate:Se=>{var xe;return ie({type:"authenticateHaloVerificationCode"}),(xe=ne.context.halo.invitationObservable)==null?void 0:xe.authenticate(Se)},onSpaceInvitationAuthenticate:Se=>{var xe;return ie({type:"authenticateSpaceVerificationCode"}),(xe=ne.context.space.invitationObservable)==null?void 0:xe.authenticate(Se)},onConfirmResetStorage:_e,onCancelResetStorage:X})},spaceMachine=createMachine({id:"space",predictableActionArguments:!0,context:{space:null},initial:"managingSpace",states:{managingSpace:{},managingSpaceInvitation:{}},on:{deselectInvitation:{target:".managingSpace",actions:["unsetInvitation","log"]},selectInvitation:{target:".managingSpaceInvitation",actions:["setInvitation","log"]}}},{actions:{setInvitation:assign({invitation:($,I)=>(I==null?void 0:I.invitation)??null}),unsetInvitation:assign({invitation:()=>{}}),log:($,I)=>{log$2("[transition]",{event:I,context:$})}}}),useSpaceMachine=$=>useMachine(spaceMachine,{...$,context:{...$==null?void 0:$.context}}),activeActionKey="dxos:react-shell/space-manager/active-action",SpaceManager=$=>{const{space:I,target:U}=$,{t:q}=useTranslation("os"),G=reactClient.useConfig(),K=echo.useSpaceInvitations(I==null?void 0:I.key),Y=React.useCallback(X=>{const Z=clientProtocol.InvitationEncoder.encode(X);X.state===Invitation.State.CONNECTING&&log$2.info(JSON.stringify({invitationCode:Z,authCode:X.authCode}))},[]),J={inviteOne:{label:q("invite one label"),description:q("invite one description"),icon:react.UserPlus,onClick:React.useCallback(()=>{var Z,Q,ee,te;const X=(Z=I.share)==null?void 0:Z.call(I,{type:Invitation.Type.INTERACTIVE,authMethod:Invitation.AuthMethod.SHARED_SECRET,multiUse:!1,target:U});X&&((te=(ee=(Q=G.values.runtime)==null?void 0:Q.app)==null?void 0:ee.env)==null?void 0:te.DX_ENVIRONMENT)!=="production"&&X.subscribe(Y)},[I])},inviteMany:{label:q("invite many label"),description:q("invite many description"),icon:react.UsersThree,onClick:React.useCallback(()=>{var Z,Q,ee,te;const X=(Z=I.share)==null?void 0:Z.call(I,{type:Invitation.Type.INTERACTIVE,authMethod:Invitation.AuthMethod.NONE,multiUse:!0,target:U});X&&((te=(ee=(Q=G.values.runtime)==null?void 0:Q.app)==null?void 0:ee.env)==null?void 0:te.DX_ENVIRONMENT)!=="production"&&X.subscribe(Y)},[I])}};return React.createElement(SpaceManagerImpl,{...$,invitations:K,inviteActions:J})},headingFragment="pis-3 pie-1 plb-1 mbe-1 font-medium",SpaceManagerImpl=$=>{const{active:I,space:U,createInvitationUrl:q,send:G,inviteActions:K,invitations:Y,showInactiveInvitations:J,SpaceMemberList:X=SpaceMemberList,InvitationList:Z=InvitationList}=$,{t:Q}=useTranslation("os"),ee=K??{noopInvite:{label:Q("create space invitation label"),description:"",icon:react.Placeholder,onClick:()=>{}}},[te,ne]=React.useState(localStorage.getItem(activeActionKey)??"inviteOne"),ie=ce=>{ne(ce),localStorage.setItem(activeActionKey,ce)},oe=J?Y:Y==null?void 0:Y.filter(ce=>![Invitation.State.CANCELLED].includes(ce.get().state));return React.createElement(React.Fragment,null,React.createElement(ScrollArea.Root,{classNames:"grow shrink basis-28 -mli-2"},React.createElement(ScrollArea.Viewport,{classNames:"is-full pie-2"},!!(oe!=null&&oe.length)&&React.createElement(React.Fragment,null,React.createElement("h3",{className:mx(headingFragment,descriptionText)},Q("invitation list heading")),React.createElement(Z,{className:"mb-2",send:G,invitations:oe??[],onClickRemove:ce=>ce.cancel(),createInvitationUrl:q}),React.createElement("h3",{className:mx(headingFragment,descriptionText,"mbs-2")},Q("space member list heading"))),React.createElement(X,{spaceKey:U.key,includeSelf:!0})),React.createElement(ScrollArea.Scrollbar,{orientation:"vertical"},React.createElement(ScrollArea.Thumb,null))),React.createElement(Actions,null,React.createElement(BifurcatedAction,{disabled:!I,actions:ee,activeAction:te,onChangeActiveAction:ie,"data-testid":"spaces-panel.create-invitation"})))},SpacePanelHeading=({titleId:$,space:I,onDone:U})=>{const{t:q}=useTranslation("os"),G=I.properties.name;return React.createElement(Heading,{titleId:$,title:q("space panel heading"),corner:React.createElement(CloseButton,{"data-testid":"identity-panel-done",onDone:U})},React.createElement("div",{role:"none",className:"flex gap-4 items-center justify-center mlb-4"},React.createElement(react.Planet,{size:32,weight:"light"}),React.createElement("div",{className:"block text-start font-light text-xl"},G??I.key.truncate())))},SpacePanelImpl=$=>{const{titleId:I,activeView:U,space:q,target:G,SpaceManager:K=SpaceManager,InvitationManager:Y=InvitationManager,...J}=$;return React.createElement(DensityProvider,{density:"fine"},React.createElement(SpacePanelHeading,{...J,titleId:I,space:q}),React.createElement(Viewport.Root,{activeView:U},React.createElement(Viewport.Views,null,React.createElement(Viewport.View,{id:"space manager",classNames:stepStyles},React.createElement(K,{active:U==="space manager",space:q,target:G,...J})),React.createElement(Viewport.View,{id:"space invitation manager",classNames:stepStyles},React.createElement(Y,{active:U==="space invitation manager",...J,invitationUrl:$.invitationUrl})))))},SpacePanelWithInvitationImpl=({invitation:$,...I})=>{const U=useInvitationStatus($);return React.createElement(SpacePanelImpl,{...I,...U,invitationUrl:I.createInvitationUrl(U.invitationCode)})},SpacePanel=({titleId:$,createInvitationUrl:I=q=>q,...U})=>{const q=useId("spacePanel__heading",$),[G,K,Y]=useSpaceMachine({context:{space:U.space}});React.useEffect(()=>Y.subscribe(Q=>{log$2("[state]",Q)}).unsubscribe,[Y]);const J=React.useMemo(()=>{switch(!0){case G.matches("managingSpace"):return"space manager";case G.matches("managingSpaceInvitation"):return"space invitation manager";default:return"never"}},[G]),X={...U,activeView:J,send:K,titleId:q,createInvitationUrl:I};return G.context.invitation?React.createElement(SpacePanelWithInvitationImpl,{...X,invitation:G.context.invitation}):React.createElement(SpacePanelImpl,{...X})},StatusPanel=({titleId:$})=>{const{t:I}=useTranslation("os");return React.createElement("div",{className:"grid place-items-center p-2 gap-2"},React.createElement("p",{id:$,className:"font-medium text-center"},I("resetting message")),React.createElement(Status,{indeterminate:!0},I("resetting message")))},IdentityDialog=$=>{const I=useId("identityDialog__title",$.title);return React.createElement(Dialog.Root,{defaultOpen:!0,onOpenChange:U=>{var q;return U||((q=$.onDone)==null?void 0:q.call($))}},React.createElement(Dialog.Portal,null,React.createElement(Dialog.Overlay,null,React.createElement(Dialog.Content,{"aria-labelledby":I,onOpenAutoFocus:U=>U.preventDefault()},React.createElement(ClipboardProvider,null,React.createElement(IdentityPanel,{...$,titleId:I,doneActionParent:React.createElement(Dialog.Close,{asChild:!0})}))))))},JoinDialog=$=>{const I=useId("joinDialog__title"),{height:U}=useVisualViewport();return React.createElement(AlertDialog.Root,{defaultOpen:!0,onOpenChange:q=>{var G;return q||($.onExit?$.onExit():(G=$.onDone)==null?void 0:G.call($,null))}},React.createElement(AlertDialog.Portal,null,React.createElement(AlertDialog.Overlay,{classNames:"backdrop-blur",...U&&{style:{blockSize:`${U}px`}}},React.createElement(AlertDialog.Content,{"aria-labelledby":I},React.createElement(JoinPanel,{...$,titleId:I,exitActionParent:React.createElement(AlertDialog.Cancel,{asChild:!0}),doneActionParent:React.createElement(AlertDialog.Action,{asChild:!0})})))))};var createRoot,m=$7SXl2$reactdom;if(process.env.NODE_ENV==="production")createRoot=m.createRoot,m.hydrateRoot;else{var i=m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;createRoot=function($,I){i.usingClientEntryPoint=!0;try{return m.createRoot($,I)}finally{i.usingClientEntryPoint=!1}}}const SpaceDialog=$=>{const I=useId("spaceDialog__title");return React.createElement(Dialog.Root,{defaultOpen:!0,onOpenChange:U=>{var q;return U||((q=$.onDone)==null?void 0:q.call($))}},React.createElement(Dialog.Portal,null,React.createElement(Dialog.Overlay,null,React.createElement(Dialog.Content,{"aria-labelledby":I},React.createElement(ClipboardProvider,null,React.createElement(SpacePanel,{...$,titleId:I,doneActionParent:React.createElement(Dialog.Close,{asChild:!0})}))))))},StatusDialog=()=>{const $=useId("statusDialog__title");return React.createElement(AlertDialog.Root,{open:!0},React.createElement(AlertDialog.Portal,null,React.createElement(AlertDialog.Overlay,null,React.createElement(AlertDialog.Content,{"aria-labelledby":$},React.createElement(StatusPanel,{titleId:$})))))},Shell=({runtime:$,origin:I})=>{const[{layout:U,invitationCode:q,spaceKey:G,target:K},Y]=React.useState({layout:$.layout,invitationCode:$.invitationCode,spaceKey:$.spaceKey,target:$.target}),J=reactClient.useClient(),X=echo.useSpace(G);switch(React.useEffect(()=>$.layoutUpdate.on(Z=>Y(Z)),[$]),React.useEffect(()=>{if(U===reactClient.ShellLayout.SPACE&&!X){log$2.warn("No space found for shell space invitations.");const Z=setTimeout(async()=>{await $.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})});return()=>clearTimeout(Z)}},[$,U,X]),U){case reactClient.ShellLayout.STATUS:return React.createElement(StatusDialog,null);case reactClient.ShellLayout.INITIALIZE_IDENTITY:case reactClient.ShellLayout.INITIALIZE_IDENTITY_FROM_INVITATION:return React.createElement(JoinDialog,{mode:"halo-only",initialDisposition:U===reactClient.ShellLayout.INITIALIZE_IDENTITY_FROM_INVITATION?"accept-halo-invitation":"default",initialInvitationCode:q,onCancelResetStorage:()=>$.setLayout({layout:reactClient.ShellLayout.IDENTITY}),onDone:()=>{$.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})}});case reactClient.ShellLayout.IDENTITY:case reactClient.ShellLayout.SHARE_IDENTITY:case reactClient.ShellLayout.EDIT_PROFILE:return React.createElement(IdentityDialog,{createInvitationUrl:Z=>`${I}?deviceInvitationCode=${Z}`,onResetStorage:async()=>($.setLayout({layout:reactClient.ShellLayout.STATUS}),await J.reset(),$.setAppContext({display:reactClient.ShellDisplay.NONE,reload:!0})),onJoinNewIdentity:async()=>($.setLayout({layout:reactClient.ShellLayout.STATUS}),await J.reset(),$.setLayout({layout:reactClient.ShellLayout.INITIALIZE_IDENTITY_FROM_INVITATION})),onDone:async()=>{await $.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})},initialDisposition:U===reactClient.ShellLayout.SHARE_IDENTITY?"manage-device-invitation":"default"});case reactClient.ShellLayout.SPACE:return X?React.createElement(SpaceDialog,{space:X,target:K,createInvitationUrl:Z=>`${I}?spaceInvitationCode=${Z}`,onDone:async()=>{await $.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})}}):null;case reactClient.ShellLayout.JOIN_SPACE:return React.createElement(JoinDialog,{initialInvitationCode:q,onDone:async Z=>{const Q=(Z==null?void 0:Z.target)??void 0;await $.setAppContext({display:reactClient.ShellDisplay.NONE,spaceKey:(Z==null?void 0:Z.spaceKey)??void 0,target:Q}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})},onExit:async()=>{await $.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})}});default:return null}},os={"manage profile label":"Manage identity","identity offline description":"Offline","sidebar label":"DXOS sidebar","copy invitation code label":"Copy URL","copy success label":"Copied","copy self public key label":"Copy public key","open share panel label":"View QR code","joining space heading":"Joining space","join space heading":"Enter space invitation","halo heading":"Initialize device identity","exit label":"Exit","identity selector title":"Join as","identity radio group title":"Select an identity you’ve associated with this device already","add identity label":"Add","continue label":"Continue","back label":"Back","next label":"Next","close label":"Close","auth choices label":"Choose an identity","create identity label":"Create an identity","create identity description":"Create a new identity.","recover identity label":"Use a seed phrase","recover identity description":"Enter your seed phrase to log in manually.","join identity label":"Use another device","join identity description":"Add this device to an identity you’re already logged into on another device.","deselect identity label":"Back to identities","addition method chooser title":"An identity is required to continue","new identity input label":"Set display name","recover identity input label":"Type or paste your seed phrase","failed to create identity message":"Failed to create an identity.","failed to recover identity message":"Failed to recover an identity from the provided seed phrase.","failed to authenticate message":"Incorrect PIN.","identity added label":"Created identity & added to this device:","join space as identity heading":"<part>as </part><part><icon/><label>{{labelValue}}</label></part>","error status label":"Failed","timeout status label":"Timed out","cancelled status label":"Cancelled","init status label":"Ready to connect","connecting status label":"Connecting…","connected status label":"Enter confirmation PIN","authenticating status label":"Enter confirmation PIN","success status label":"Success","cancel label":"Cancel","done label":"Done","reset label":"Start over","auth code input label":"Enter the verification code","invitation input label":"Paste an invitation code or URL","create device invitation label":"Add device","create space invitation label":"Invite","qr label":"Scan to accept invitation","empty invitations message":"No pending invitations","empty device list message":"No devices authenticated other than this device.","show all spaces label":"All spaces","all spaces label":"All spaces","create space label":"Create a new space","join space label":"Join a space","show current space label":"Current space","view space invitations label":"View space invitations","toggle sidebar label":"Open/close sidebar","open sidebar label":"Open sidebar","close sidebar label":"Close sidebar","welcome message":"Welcome","selecting identity heading":"Selecting identity","devices heading":"Devices","identity heading":"Profile settings","choose add device label":"Add device","choose devices label":"Manage devices","choose profile label":"Edit profile","choose sign out label":"Reset storage","choose join new identity label":"Join existing device","empty space members message":"There is nobody in this space yet.","back to all invitations label":"Back to all invitations","invitation heading":"Invitation","invitation list heading":"Invitations","device invitation list heading":"Pending device invitations","space invitation list heading":"Pending invitations","device list heading":"Devices","space member list heading":"Members","space panel heading":"Space membership","auth code message":"Enter the following auth code on the joining device.","display name input label":"Display name","display name input placeholder":"Enter a display name","invite one label":"Invite one","invite one description":"Only one user may join.","invite one qr label":"Single-use","invite one list item label":"Active single-use invitation","invite many label":"Invite many","invite many description":"Anyone with the link can join.","invite many qr label":"Multiple-use","invite many list item label":"Active multiple-use invitation","invite options label":"Change the active invite option.","reset in progress label":"Resetting...","confirm label":"Confirm","reset storage input label":"This will clear this device and all associated data. Type {{confirmationValue}} and confirm to continue.","join new identity input label":"In order to join an existing device, storage on this device must be cleared first. Type {{confirmationValue}} to continue.","failed to reset identity message":"Failed to reset identity.","confirmation value":"CONFIRM","sign out chooser title":"Danger zone","sign out chooser message":"Proceeding with the action below will erase all data on this device.","join new identity label":"Join a new identity","reset device label":"Reset storage","reset device confirm message":"Are you sure you want to reset your device? All data will be lost.","emoji and color label":"Emoji and color","clear label":"Use default","select emoji label":"Choose an emoji to use in your avatar","select hue label":"Choose a hue to use in your avatar","resetting message":"One moment while things are reset…","red label":"Red","orange label":"Orange","amber label":"Amber","yellow label":"Yellow","lime label":"Lime","green label":"Green","emerald label":"Emerald","teal label":"Teal","cyan label":"Cyan","sky label":"Sky","blue label":"Blue","indigo label":"Indigo","violet label":"Violet","purple label":"Purple","fuchsia label":"Fuchsia","pink label":"Pink","rose label":"Rose","current device tag label":"This device","device name placeholder":"{{platform}} on {{os}}","more options label":"More options","disconnect label":"Currently online. Click to go offline.","connect label":"Currently offline. Click to go online.","edit device label":"Edit device name & avatar","agent heading":"Agent","agent message title":"About creating an agent","agent message body":"Creating an agent helps keep your devices and peers in-sync. An agent is like any other device, but since it’s always online your changes will sync even when all your physical devices are asleep.","create agent label":"Start an agent","destroy agent label":"Shut down agent","agent device label":"Your agent"},enUS=Object.freeze(Object.defineProperty({__proto__:null,os},Symbol.toStringTag,{value:"Module"})),osTranslations={"en-US":enUS},runShell=async($=new reactClient.Config)=>{const I=new reactClient.ClientServicesProxy(createIFramePort({channel:clientProtocol.DEFAULT_CLIENT_CHANNEL})),U=new reactClient.Client({config:$,services:I}),q=new clientServices.ShellRuntimeImpl(createIFramePort({channel:clientProtocol.DEFAULT_SHELL_CHANNEL}));await Promise.all([q.open(),U.initialize()]),createRoot(document.getElementById("root")).render(React.createElement(React.StrictMode,null,React.createElement(ThemeProvider,{tx:defaultTx,resourceExtensions:[osTranslations]},React.createElement(reactClient.ClientContext.Provider,{value:{client:U,status:reactClient.SystemStatus.ACTIVE}},React.createElement(ClipboardProvider,null,React.createElement(Tooltip.Provider,null,React.createElement(Shell,{runtime:q,origin:location.origin})))))))};React.createContext({});function _ts_decorate($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file="/home/runner/work/dxos/dxos/packages/core/mesh/websocket-rpc/src/client.ts",WebsocketRpcClient=class{constructor($){this._params=$,this._connectTrigger=new Trigger,this.connected=new Event$1,this.disconnected=new Event$1,this.error=new Event$1,this._rpc=createProtoRpcPeer({requested:this._params.requested,exposed:this._params.exposed,handlers:this._params.handlers,port:{send:I=>{this._socket.send(I)},subscribe:I=>{this._socket.onmessage=async U=>{typeof Blob<"u"&&U.data instanceof Blob?I(export_Buffer.from(await U.data.arrayBuffer())):I(U.data)}}}})}get url(){return this._params.url}async open(){this._socket=new WebSocket2(this._params.url),this._socket.onopen=async()=>{log$2("Socket open",void 0,{F:__dxlog_file,L:55,S:this,C:($,I)=>$(...I)});try{await this._rpc.open(),log$2(`RPC open ${this._params.url}`,void 0,{F:__dxlog_file,L:58,S:this,C:($,I)=>$(...I)}),this.connected.emit(),this._connectTrigger.wake()}catch($){this.error.emit($)}},this._socket.onclose=async()=>{log$2(`Disconnected ${this._params.url}`,void 0,{F:__dxlog_file,L:67,S:this,C:($,I)=>$(...I)}),this.disconnected.emit(),await this.close()},this._socket.onerror=$=>{log$2.error($.message??"Socket error",{url:this._params.url},{F:__dxlog_file,L:73,S:this,C:(U,q)=>U(...q)});const I=$.error??new Error($.message);this.error.emit(I),this._connectTrigger.throw(I)},await this._connectTrigger.wait()}async close(){var $,I;try{await(($=this._rpc)==null?void 0:$.close())}catch(U){log$2.catch(U,void 0,{F:__dxlog_file,L:86,S:this,C:(q,G)=>q(...G)})}(I=this._socket)==null||I.close()}get rpc(){return this._rpc.rpc}};_ts_decorate([logInfo],WebsocketRpcClient.prototype,"url",null);const index=Object.freeze(Object.defineProperty({__proto__:null,WebsocketRpcClient},Symbol.toStringTag,{value:"Module"}));exports.runShell=runShell,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|
|
1001
|
+
`}return rt.substring(0,rt.length-1)},Ve.renderTo2dContext=function(Ae,Re){Re=Re||2;for(var Ce=Ve.getModuleCount(),ge=0;ge<Ce;ge++)for(var ye=0;ye<Ce;ye++)Ae.fillStyle=Ve.isDark(ge,ye)?"black":"white",Ae.fillRect(ge*Re,ye*Re,Re,Re)},Ve};q.stringToBytesFuncs={default:function(pe){for(var ve=[],me=0;me<pe.length;me+=1){var be=pe.charCodeAt(me);ve.push(be&255)}return ve}},q.stringToBytes=q.stringToBytesFuncs.default,q.createStringToBytes=function(pe,ve){var me=function(){for(var _e=se(pe),Se=function(){var it=_e.read();if(it==-1)throw"eof";return it},xe=0,ke={};;){var De=_e.read();if(De==-1)break;var Be=Se(),Ve=Se(),nt=Se(),ot=String.fromCharCode(De<<8|Be),ft=Ve<<8|nt;ke[ot]=ft,xe+=1}if(xe!=ve)throw xe+" != "+ve;return ke}(),be=63;return function(_e){for(var Se=[],xe=0;xe<_e.length;xe+=1){var ke=_e.charCodeAt(xe);if(ke<128)Se.push(ke);else{var De=me[_e.charAt(xe)];typeof De=="number"?(De&255)==De?Se.push(De):(Se.push(De>>>8),Se.push(De&255)):Se.push(be)}}return Se}};var G={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},K={L:1,M:0,Q:3,H:2},Y={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},J=function(){var pe=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],ve=1335,me=7973,be=21522,_e={},Se=function(xe){for(var ke=0;xe!=0;)ke+=1,xe>>>=1;return ke};return _e.getBCHTypeInfo=function(xe){for(var ke=xe<<10;Se(ke)-Se(ve)>=0;)ke^=ve<<Se(ke)-Se(ve);return(xe<<10|ke)^be},_e.getBCHTypeNumber=function(xe){for(var ke=xe<<12;Se(ke)-Se(me)>=0;)ke^=me<<Se(ke)-Se(me);return xe<<12|ke},_e.getPatternPosition=function(xe){return pe[xe-1]},_e.getMaskFunction=function(xe){switch(xe){case Y.PATTERN000:return function(ke,De){return(ke+De)%2==0};case Y.PATTERN001:return function(ke,De){return ke%2==0};case Y.PATTERN010:return function(ke,De){return De%3==0};case Y.PATTERN011:return function(ke,De){return(ke+De)%3==0};case Y.PATTERN100:return function(ke,De){return(Math.floor(ke/2)+Math.floor(De/3))%2==0};case Y.PATTERN101:return function(ke,De){return ke*De%2+ke*De%3==0};case Y.PATTERN110:return function(ke,De){return(ke*De%2+ke*De%3)%2==0};case Y.PATTERN111:return function(ke,De){return(ke*De%3+(ke+De)%2)%2==0};default:throw"bad maskPattern:"+xe}},_e.getErrorCorrectPolynomial=function(xe){for(var ke=Z([1],0),De=0;De<xe;De+=1)ke=ke.multiply(Z([1,X.gexp(De)],0));return ke},_e.getLengthInBits=function(xe,ke){if(1<=ke&&ke<10)switch(xe){case G.MODE_NUMBER:return 10;case G.MODE_ALPHA_NUM:return 9;case G.MODE_8BIT_BYTE:return 8;case G.MODE_KANJI:return 8;default:throw"mode:"+xe}else if(ke<27)switch(xe){case G.MODE_NUMBER:return 12;case G.MODE_ALPHA_NUM:return 11;case G.MODE_8BIT_BYTE:return 16;case G.MODE_KANJI:return 10;default:throw"mode:"+xe}else if(ke<41)switch(xe){case G.MODE_NUMBER:return 14;case G.MODE_ALPHA_NUM:return 13;case G.MODE_8BIT_BYTE:return 16;case G.MODE_KANJI:return 12;default:throw"mode:"+xe}else throw"type:"+ke},_e.getLostPoint=function(xe){for(var ke=xe.getModuleCount(),De=0,Be=0;Be<ke;Be+=1)for(var Ve=0;Ve<ke;Ve+=1){for(var nt=0,ot=xe.isDark(Be,Ve),ft=-1;ft<=1;ft+=1)if(!(Be+ft<0||ke<=Be+ft))for(var it=-1;it<=1;it+=1)Ve+it<0||ke<=Ve+it||ft==0&&it==0||ot==xe.isDark(Be+ft,Ve+it)&&(nt+=1);nt>5&&(De+=3+nt-5)}for(var Be=0;Be<ke-1;Be+=1)for(var Ve=0;Ve<ke-1;Ve+=1){var ut=0;xe.isDark(Be,Ve)&&(ut+=1),xe.isDark(Be+1,Ve)&&(ut+=1),xe.isDark(Be,Ve+1)&&(ut+=1),xe.isDark(Be+1,Ve+1)&&(ut+=1),(ut==0||ut==4)&&(De+=3)}for(var Be=0;Be<ke;Be+=1)for(var Ve=0;Ve<ke-6;Ve+=1)xe.isDark(Be,Ve)&&!xe.isDark(Be,Ve+1)&&xe.isDark(Be,Ve+2)&&xe.isDark(Be,Ve+3)&&xe.isDark(Be,Ve+4)&&!xe.isDark(Be,Ve+5)&&xe.isDark(Be,Ve+6)&&(De+=40);for(var Ve=0;Ve<ke;Ve+=1)for(var Be=0;Be<ke-6;Be+=1)xe.isDark(Be,Ve)&&!xe.isDark(Be+1,Ve)&&xe.isDark(Be+2,Ve)&&xe.isDark(Be+3,Ve)&&xe.isDark(Be+4,Ve)&&!xe.isDark(Be+5,Ve)&&xe.isDark(Be+6,Ve)&&(De+=40);for(var et=0,Ve=0;Ve<ke;Ve+=1)for(var Be=0;Be<ke;Be+=1)xe.isDark(Be,Ve)&&(et+=1);var Ue=Math.abs(100*et/ke/ke-50)/5;return De+=Ue*10,De},_e}(),X=function(){for(var pe=new Array(256),ve=new Array(256),me=0;me<8;me+=1)pe[me]=1<<me;for(var me=8;me<256;me+=1)pe[me]=pe[me-4]^pe[me-5]^pe[me-6]^pe[me-8];for(var me=0;me<255;me+=1)ve[pe[me]]=me;var be={};return be.glog=function(_e){if(_e<1)throw"glog("+_e+")";return ve[_e]},be.gexp=function(_e){for(;_e<0;)_e+=255;for(;_e>=256;)_e-=255;return pe[_e]},be}();function Z(pe,ve){if(typeof pe.length>"u")throw pe.length+"/"+ve;var me=function(){for(var _e=0;_e<pe.length&&pe[_e]==0;)_e+=1;for(var Se=new Array(pe.length-_e+ve),xe=0;xe<pe.length-_e;xe+=1)Se[xe]=pe[xe+_e];return Se}(),be={};return be.getAt=function(_e){return me[_e]},be.getLength=function(){return me.length},be.multiply=function(_e){for(var Se=new Array(be.getLength()+_e.getLength()-1),xe=0;xe<be.getLength();xe+=1)for(var ke=0;ke<_e.getLength();ke+=1)Se[xe+ke]^=X.gexp(X.glog(be.getAt(xe))+X.glog(_e.getAt(ke)));return Z(Se,0)},be.mod=function(_e){if(be.getLength()-_e.getLength()<0)return be;for(var Se=X.glog(be.getAt(0))-X.glog(_e.getAt(0)),xe=new Array(be.getLength()),ke=0;ke<be.getLength();ke+=1)xe[ke]=be.getAt(ke);for(var ke=0;ke<_e.getLength();ke+=1)xe[ke]^=X.gexp(X.glog(_e.getAt(ke))+Se);return Z(xe,0).mod(_e)},be}var Q=function(){var pe=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],ve=function(_e,Se){var xe={};return xe.totalCount=_e,xe.dataCount=Se,xe},me={},be=function(_e,Se){switch(Se){case K.L:return pe[(_e-1)*4+0];case K.M:return pe[(_e-1)*4+1];case K.Q:return pe[(_e-1)*4+2];case K.H:return pe[(_e-1)*4+3];default:return}};return me.getRSBlocks=function(_e,Se){var xe=be(_e,Se);if(typeof xe>"u")throw"bad rs block @ typeNumber:"+_e+"/errorCorrectionLevel:"+Se;for(var ke=xe.length/3,De=[],Be=0;Be<ke;Be+=1)for(var Ve=xe[Be*3+0],nt=xe[Be*3+1],ot=xe[Be*3+2],ft=0;ft<Ve;ft+=1)De.push(ve(nt,ot));return De},me}(),ee=function(){var pe=[],ve=0,me={};return me.getBuffer=function(){return pe},me.getAt=function(be){var _e=Math.floor(be/8);return(pe[_e]>>>7-be%8&1)==1},me.put=function(be,_e){for(var Se=0;Se<_e;Se+=1)me.putBit((be>>>_e-Se-1&1)==1)},me.getLengthInBits=function(){return ve},me.putBit=function(be){var _e=Math.floor(ve/8);pe.length<=_e&&pe.push(0),be&&(pe[_e]|=128>>>ve%8),ve+=1},me},te=function(pe){var ve=G.MODE_NUMBER,me=pe,be={};be.getMode=function(){return ve},be.getLength=function(xe){return me.length},be.write=function(xe){for(var ke=me,De=0;De+2<ke.length;)xe.put(_e(ke.substring(De,De+3)),10),De+=3;De<ke.length&&(ke.length-De==1?xe.put(_e(ke.substring(De,De+1)),4):ke.length-De==2&&xe.put(_e(ke.substring(De,De+2)),7))};var _e=function(xe){for(var ke=0,De=0;De<xe.length;De+=1)ke=ke*10+Se(xe.charAt(De));return ke},Se=function(xe){if("0"<=xe&&xe<="9")return xe.charCodeAt(0)-48;throw"illegal char :"+xe};return be},ne=function(pe){var ve=G.MODE_ALPHA_NUM,me=pe,be={};be.getMode=function(){return ve},be.getLength=function(Se){return me.length},be.write=function(Se){for(var xe=me,ke=0;ke+1<xe.length;)Se.put(_e(xe.charAt(ke))*45+_e(xe.charAt(ke+1)),11),ke+=2;ke<xe.length&&Se.put(_e(xe.charAt(ke)),6)};var _e=function(Se){if("0"<=Se&&Se<="9")return Se.charCodeAt(0)-48;if("A"<=Se&&Se<="Z")return Se.charCodeAt(0)-65+10;switch(Se){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+Se}};return be},ie=function(pe){var ve=G.MODE_8BIT_BYTE,me=q.stringToBytes(pe),be={};return be.getMode=function(){return ve},be.getLength=function(_e){return me.length},be.write=function(_e){for(var Se=0;Se<me.length;Se+=1)_e.put(me[Se],8)},be},oe=function(pe){var ve=G.MODE_KANJI,me=q.stringToBytesFuncs.SJIS;if(!me)throw"sjis not supported.";(function(Se,xe){var ke=me(Se);if(ke.length!=2||(ke[0]<<8|ke[1])!=xe)throw"sjis not supported."})("友",38726);var be=me(pe),_e={};return _e.getMode=function(){return ve},_e.getLength=function(Se){return~~(be.length/2)},_e.write=function(Se){for(var xe=be,ke=0;ke+1<xe.length;){var De=(255&xe[ke])<<8|255&xe[ke+1];if(33088<=De&&De<=40956)De-=33088;else if(57408<=De&&De<=60351)De-=49472;else throw"illegal char at "+(ke+1)+"/"+De;De=(De>>>8&255)*192+(De&255),Se.put(De,13),ke+=2}if(ke<xe.length)throw"illegal char at "+(ke+1)},_e},ce=function(){var pe=[],ve={};return ve.writeByte=function(me){pe.push(me&255)},ve.writeShort=function(me){ve.writeByte(me),ve.writeByte(me>>>8)},ve.writeBytes=function(me,be,_e){be=be||0,_e=_e||me.length;for(var Se=0;Se<_e;Se+=1)ve.writeByte(me[Se+be])},ve.writeString=function(me){for(var be=0;be<me.length;be+=1)ve.writeByte(me.charCodeAt(be))},ve.toByteArray=function(){return pe},ve.toString=function(){var me="";me+="[";for(var be=0;be<pe.length;be+=1)be>0&&(me+=","),me+=pe[be];return me+="]",me},ve},fe=function(){var pe=0,ve=0,me=0,be="",_e={},Se=function(ke){be+=String.fromCharCode(xe(ke&63))},xe=function(ke){if(!(ke<0)){if(ke<26)return 65+ke;if(ke<52)return 97+(ke-26);if(ke<62)return 48+(ke-52);if(ke==62)return 43;if(ke==63)return 47}throw"n:"+ke};return _e.writeByte=function(ke){for(pe=pe<<8|ke&255,ve+=8,me+=1;ve>=6;)Se(pe>>>ve-6),ve-=6},_e.flush=function(){if(ve>0&&(Se(pe<<6-ve),pe=0,ve=0),me%3!=0)for(var ke=3-me%3,De=0;De<ke;De+=1)be+="="},_e.toString=function(){return be},_e},se=function(pe){var ve=pe,me=0,be=0,_e=0,Se={};Se.read=function(){for(;_e<8;){if(me>=ve.length){if(_e==0)return-1;throw"unexpected end of file./"+_e}var ke=ve.charAt(me);if(me+=1,ke=="=")return _e=0,-1;if(ke.match(/^\s$/))continue;be=be<<6|xe(ke.charCodeAt(0)),_e+=6}var De=be>>>_e-8&255;return _e-=8,De};var xe=function(ke){if(65<=ke&&ke<=90)return ke-65;if(97<=ke&&ke<=122)return ke-97+26;if(48<=ke&&ke<=57)return ke-48+52;if(ke==43)return 62;if(ke==47)return 63;throw"c:"+ke};return Se},de=function(pe,ve){var me=pe,be=ve,_e=new Array(pe*ve),Se={};Se.setPixel=function(Be,Ve,nt){_e[Ve*me+Be]=nt},Se.write=function(Be){Be.writeString("GIF87a"),Be.writeShort(me),Be.writeShort(be),Be.writeByte(128),Be.writeByte(0),Be.writeByte(0),Be.writeByte(0),Be.writeByte(0),Be.writeByte(0),Be.writeByte(255),Be.writeByte(255),Be.writeByte(255),Be.writeString(","),Be.writeShort(0),Be.writeShort(0),Be.writeShort(me),Be.writeShort(be),Be.writeByte(0);var Ve=2,nt=ke(Ve);Be.writeByte(Ve);for(var ot=0;nt.length-ot>255;)Be.writeByte(255),Be.writeBytes(nt,ot,255),ot+=255;Be.writeByte(nt.length-ot),Be.writeBytes(nt,ot,nt.length-ot),Be.writeByte(0),Be.writeString(";")};var xe=function(Be){var Ve=Be,nt=0,ot=0,ft={};return ft.write=function(it,ut){if(it>>>ut)throw"length over";for(;nt+ut>=8;)Ve.writeByte(255&(it<<nt|ot)),ut-=8-nt,it>>>=8-nt,ot=0,nt=0;ot=it<<nt|ot,nt=nt+ut},ft.flush=function(){nt>0&&Ve.writeByte(ot)},ft},ke=function(Be){for(var Ve=1<<Be,nt=(1<<Be)+1,ot=Be+1,ft=De(),it=0;it<Ve;it+=1)ft.add(String.fromCharCode(it));ft.add(String.fromCharCode(Ve)),ft.add(String.fromCharCode(nt));var ut=ce(),et=xe(ut);et.write(Ve,ot);var Ue=0,We=String.fromCharCode(_e[Ue]);for(Ue+=1;Ue<_e.length;){var tt=String.fromCharCode(_e[Ue]);Ue+=1,ft.contains(We+tt)?We=We+tt:(et.write(ft.indexOf(We),ot),ft.size()<4095&&(ft.size()==1<<ot&&(ot+=1),ft.add(We+tt)),We=tt)}return et.write(ft.indexOf(We),ot),et.write(nt,ot),et.flush(),ut.toByteArray()},De=function(){var Be={},Ve=0,nt={};return nt.add=function(ot){if(nt.contains(ot))throw"dup key:"+ot;Be[ot]=Ve,Ve+=1},nt.size=function(){return Ve},nt.indexOf=function(ot){return Be[ot]},nt.contains=function(ot){return typeof Be[ot]<"u"},nt};return Se},ue=function(pe,ve,me){for(var be=de(pe,ve),_e=0;_e<ve;_e+=1)for(var Se=0;Se<pe;Se+=1)be.setPixel(Se,_e,me(Se,_e));var xe=ce();be.write(xe);for(var ke=fe(),De=xe.toByteArray(),Be=0;Be<De.length;Be+=1)ke.writeByte(De[Be]);return ke.flush(),"data:image/gif;base64,"+ke};return q}();(function(){U.stringToBytesFuncs["UTF-8"]=function(q){function G(K){for(var Y=[],J=0;J<K.length;J++){var X=K.charCodeAt(J);X<128?Y.push(X):X<2048?Y.push(192|X>>6,128|X&63):X<55296||X>=57344?Y.push(224|X>>12,128|X>>6&63,128|X&63):(J++,X=65536+((X&1023)<<10|K.charCodeAt(J)&1023),Y.push(240|X>>18,128|X>>12&63,128|X>>6&63,128|X&63))}return Y}return G(q)}})(),function(q){$.exports=q()}(function(){return U})})(qrcode);var qrcodeExports=qrcode.exports;const qrGenerator=getDefaultExportFromCjs(qrcodeExports);var __defProp=Object.defineProperty,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__defNormalProp=($,I,U)=>I in $?__defProp($,I,{enumerable:!0,configurable:!0,writable:!0,value:U}):$[I]=U,__spreadValues=($,I)=>{for(var U in I||(I={}))__hasOwnProp.call(I,U)&&__defNormalProp($,U,I[U]);if(__getOwnPropSymbols)for(var U of __getOwnPropSymbols(I))__propIsEnum.call(I,U)&&__defNormalProp($,U,I[U]);return $},__objRest=($,I)=>{var U={};for(var q in $)__hasOwnProp.call($,q)&&I.indexOf(q)<0&&(U[q]=$[q]);if($!=null&&__getOwnPropSymbols)for(var q of __getOwnPropSymbols($))I.indexOf(q)<0&&__propIsEnum.call($,q)&&(U[q]=$[q]);return U},VIEWPORT_SIZE=1e3,RE_CODE_LENGTH_OVERFLOW=/code length overflow/i;qrGenerator.stringToBytes=qrGenerator.stringToBytesFuncs["UTF-8"];var createQrCode=($,I,U)=>{U=Math.max(1,U);for(let q=U;q<=40;q+=1)try{const G=qrGenerator(q,I);G.addData($),G.make();const K=G.getModuleCount();return{text:$,level:I,version:q,moduleCount:K,isDark:(J,X)=>J>=0&&J<K&&X>=0&&X<K&&G.isDark(J,X)}}catch(G){if(!(q<40&&RE_CODE_LENGTH_OVERFLOW.test(String(G))))throw G}return null},round=Math.round,drawM=($,I)=>`M ${round($)} ${round(I)}`,drawL=($,I)=>`L ${round($)} ${round(I)}`,drawA=($,I,U)=>`A ${round(U)} ${round(U)} 0 0 1 ${round($)} ${round(I)}`,drawDark=($,I,U,q,G,K,Y,J,X)=>{const Z=[];return K?Z.push(drawM($+G,I)):Z.push(drawM($,I)),Y?Z.push(drawL(U-G,I),drawA(U,I+G,G)):Z.push(drawL(U,I)),J?Z.push(drawL(U,q-G),drawA(U-G,q,G)):Z.push(drawL(U,q)),X?Z.push(drawL($+G,q),drawA($,q-G,G)):Z.push(drawL($,q)),K?Z.push(drawL($,I+G),drawA($+G,I,G)):Z.push(drawL($,I)),Z.join(" ")},drawLight=($,I,U,q,G,K,Y,J,X)=>{const Z=[];return K&&Z.push(drawM($+G,I),drawL($,I),drawL($,I+G),drawA($+G,I,G)),Y&&Z.push(drawM(U,I+G),drawL(U,I),drawL(U-G,I),drawA(U,I+G,G)),J&&Z.push(drawM(U-G,q),drawL(U,q),drawL(U,q-G),drawA(U-G,q,G)),X&&Z.push(drawM($,q-G),drawL($,q),drawL($+G,q),drawA($,q-G,G)),Z.join(" ")},drawMod=($,I,U,q,G)=>{const K=G*U,Y=q*U,J=K+U,X=Y+U,Z=I*.005*U,Q=$.isDark,ee=q-1,te=q+1,ne=G-1,ie=G+1,oe=Q(q,G),ce=Q(ee,ne),fe=Q(ee,G),se=Q(ee,ie),de=Q(q,ie),ue=Q(te,ie),pe=Q(te,G),ve=Q(te,ne),me=Q(q,ne);return oe?drawDark(K,Y,J,X,Z,!fe&&!me,!fe&&!de,!pe&&!de,!pe&&!me):drawLight(K,Y,J,X,Z,fe&&me&&ce,fe&&de&&se,pe&&de&&ue,pe&&me&&ve)},createPath=($,I)=>{if(!$)return"";const U=$.moduleCount,q=VIEWPORT_SIZE/U,G=[];for(let K=0;K<U;K+=1)for(let Y=0;Y<U;Y+=1)G.push(drawMod($,I,q,K,Y));return G.join(" ")},QR=$=>{var I=$,{color:U="#000",backgroundColor:q,cutout:G=!1,cutoutElement:K,errorCorrectionLevel:Y="Q",rounding:J=0,children:X}=I,Z=__objRest(I,["color","backgroundColor","cutout","cutoutElement","errorCorrectionLevel","rounding","children"]),Q,ee;const te=React.useMemo(()=>createQrCode(X,Y,1),[X,Y]);if(!te)return null;const ne=(Q=te==null?void 0:te.moduleCount)!=null?Q:1,oe=VIEWPORT_SIZE/((ee=te==null?void 0:te.moduleCount)!=null?ee:1)*(Math.floor(ne*.18)*2-1)+2,ce=(VIEWPORT_SIZE-oe)/2;return React__namespace.createElement("svg",__spreadValues({xmlns:"http://www.w3.org/2000/svg",viewBox:`0 0 ${VIEWPORT_SIZE} ${VIEWPORT_SIZE}`},Z),G?React__namespace.createElement("mask",{id:"react-qr-rounded__mask"},React__namespace.createElement("rect",{x:"0",y:"0",width:VIEWPORT_SIZE,height:VIEWPORT_SIZE,fill:"#fff"}),React__namespace.createElement("rect",{x:ce,y:ce,width:oe,height:oe,rx:J,ry:J,fill:"#000"})):null,q?React__namespace.createElement("rect",{x:"0",y:"0",width:VIEWPORT_SIZE,height:VIEWPORT_SIZE,fill:q}):null,React__namespace.createElement("path",{fill:U,d:createPath(te,J),mask:G?"url(#react-qr-rounded__mask)":void 0}),K?React__namespace.createElement("foreignObject",{x:ce,y:ce,width:oe,height:oe},React__namespace.createElement("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",width:"100%",overflow:"hidden",borderRadius:J}},K)):null)};const invitationStatusValue=new Map([[Invitation.State.ERROR,-3],[Invitation.State.TIMEOUT,-2],[Invitation.State.CANCELLED,-1],[Invitation.State.INIT,0],[Invitation.State.CONNECTING,1],[Invitation.State.CONNECTED,2],[Invitation.State.READY_FOR_AUTHENTICATION,3],[Invitation.State.AUTHENTICATING,4],[Invitation.State.SUCCESS,5]]),InvitationManagerView=({children:$,...I})=>React.createElement(Viewport.View,{...I,classNames:"grow flex flex-col justify-around items-center"},$),InvitationManager=({invitationUrl:$,active:I,send:U,status:q,multiUse:G,authCode:K,id:Y="0"})=>{const{t:J}=useTranslation("os"),X=useId("invitation-manager__qr-code"),Z=G?0:invitationStatusValue.get(q)??0,Q=Z===3,ee=hexToEmoji(Y),te=React.useMemo(()=>{switch(!0){case Z===5:case Z<0:return"showing final";case Z===3:return"showing auth code";default:return"showing qr"}},[Z]);return React.createElement(React.Fragment,null,React.createElement(Viewport.Root,{activeView:te,classNames:"grow plb-1"},React.createElement(Viewport.Views,null,React.createElement(InvitationManagerView,{id:"showing qr",emoji:ee},React.createElement("p",{className:"text-sm mlb-1 font-normal text-center"},J(G?"invite many qr label":"invite one qr label")),React.createElement("div",{role:"none",className:mx(descriptionText,"is-full max-is-[14rem] relative")},React.createElement(QR,{rounding:100,backgroundColor:"transparent",color:"currentColor",className:mx("is-full bs-full p-2",Q&&"invisible"),"aria-labelledby":X,errorCorrectionLevel:"Q",cutout:!0},$??"never"),React.createElement(Centered,null,React.createElement(Emoji,{text:ee}))),React.createElement("span",{id:X,className:"sr-only"},J("qr label")),React.createElement(CopyButton,{variant:"ghost",value:$??"never"})),React.createElement(InvitationManagerView,{id:"showing auth code"},React.createElement(Label,null,J("auth code message")),React.createElement(AuthCode,{code:K,large:!0,classNames:"text-black dark:text-white"}),React.createElement(Label,null,"Be sure the other device is showing this symbol:"),ee&&React.createElement(Emoji,{text:ee})),React.createElement(InvitationManagerView,{id:"showing final"},Z>0?React.createElement(react.Check,{className:mx("m-1.5",getSize(6))}):React.createElement(react.X,{className:mx("m-1.5",getSize(6))})))),React.createElement(Actions,{classNames:"mbs-4"},React.createElement(Action,{disabled:!I,onClick:()=>U==null?void 0:U({type:"deselectInvitation"})},J("back label"))))},ConfirmReset=({active:$,onCancel:I,onConfirm:U,mode:q})=>{const{t:G}=useTranslation("os"),[K,Y]=React.useState(""),[J,X]=React.useState(!1),Z=async()=>(X(!0),U==null?void 0:U().then(()=>X(!1),Q=>{log$2.catch(Q),Y(G("failed to reset identity message")),X(!1)}));return React.createElement(ConfirmResetImpl,{disabled:!$,pending:J,validationMessage:K,onConfirm:Z,onCancel:I,mode:q})},ConfirmResetImpl=({disabled:$,pending:I,validationMessage:U,onConfirm:q,onCancel:G,mode:K})=>{const{t:Y}=useTranslation("os"),J=Y("confirmation value"),[X,Z]=React.useState(""),Q=K==="join new identity"?"join-new-identity":"reset-storage";return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col gap-2 justify-center"},React.createElement(Message$1.Root,{valence:"error"},React.createElement(Message$1.Title,null,React.createElement(react.Warning,{className:mx(getSize(6),"inline mie-2")}),Y("sign out chooser title")),React.createElement(Message$1.Body,null,Y("sign out chooser message"))),React.createElement(Input,{validationMessage:U,label:React.createElement(StepHeading,{className:"text-start mlb-2"},Y(K==="join new identity"?"join new identity input label":"reset storage input label",{confirmationValue:J})),disabled:$,"data-testid":`${Q}.reset-identity-input`,placeholder:J,onChange:({target:{value:ee}})=>Z(ee)})),React.createElement(Actions,null,G&&React.createElement(Action,{disabled:$,onClick:G,"data-testid":`${Q}.reset-identity-cancel`},Y("cancel label")),q&&React.createElement(Action,{variant:"destructive",disabled:$||I||X!==J,onClick:q,"data-testid":`${Q}.reset-identity-confirm`},Y(I?"reset in progress label":"reset device label"))))},viewStyles="pbs-1 pbe-3 pli-3",getHueValue=$=>{var I,U;return((U=(I=$==null?void 0:$.profile)==null?void 0:I.data)==null?void 0:U.hue)||hexToHue(($==null?void 0:$.identityKey.toHex())??"0")},getEmojiValue=$=>{var I,U;return((U=(I=$==null?void 0:$.profile)==null?void 0:I.data)==null?void 0:U.emoji)||hexToEmoji(($==null?void 0:$.identityKey.toHex())??"0")},IdentityHeading=({titleId:$,title:I,identity:U,onDone:q,onUpdateProfile:G,connectionState:K,onChangeConnectionState:Y})=>{var pe,ve;const J=keyToFallback(U.identityKey),{t:X}=useTranslation("os"),[Z,Q]=React.useState(((pe=U.profile)==null?void 0:pe.displayName)??""),[ee,te]=React.useState(getEmojiValue(U)),[ne,ie]=React.useState(getHueValue(U)),{textValue:oe,setTextValue:ce}=useClipboardContext(),fe=U.identityKey.toHex(),se=oe===fe,de=async()=>{const me={...Z&&{displayName:Z},...(ee||ne)&&{data:{...ee&&{emoji:ee},...ne&&{hue:ne}}}};return G==null?void 0:G(me)};React.useEffect(()=>{de()},[ee,ne]);const ue=K===ConnectionState$2.ONLINE;return React.createElement(Heading,{titleId:$,title:I,corner:React.createElement(CloseButton,{onDone:q})},React.createElement(Avatar.Root,{size:16,variant:"circle",status:ue?"active":"error",hue:ne||J.hue},React.createElement(Toolbar.Root,{classNames:"grid grid-cols-[1fr_var(--rail-action)_min-content_var(--rail-action)_1fr] items-center gap-2"},React.createElement(Tooltip.Root,null,React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:"bs-[--rail-action] is-[--rail-action] justify-self-end",onClick:()=>Y==null?void 0:Y(ue?ConnectionState$2.OFFLINE:ConnectionState$2.ONLINE)},React.createElement("span",{className:"sr-only"},X(ue?"disconnect label":"connect label")),ue?React.createElement(react.PlugsConnected,{className:getSize(5)}):React.createElement(react.Plugs,{className:getSize(5)}))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},X(ue?"disconnect label":"connect label"),React.createElement(Tooltip.Arrow,null)))),React.createElement(EmojiPickerToolbarButton,{emoji:ee,onChangeEmoji:te,classNames:"bs-[--rail-action]"}),React.createElement(Avatar.Frame,{classNames:"relative z-[2] -mli-4 chromatic-ignore"},React.createElement(Avatar.Fallback,{text:ee||J.emoji})),React.createElement(HuePickerToolbarButton,{hue:ne,onChangeHue:ie,classNames:"bs-[--rail-action]"}),React.createElement(Tooltip.Root,null,React.createElement(Tooltip.Trigger,{asChild:!0},React.createElement(Toolbar.Button,{classNames:"bs-[--rail-action] justify-self-start","data-testid":"update-profile-form-copy-key",onClick:()=>ce(fe)},React.createElement("span",{className:"sr-only"},X(se?"copy success label":"copy self public key label")),React.createElement(react.CopySimple,{className:getSize(5)}))),React.createElement(Tooltip.Portal,null,React.createElement(Tooltip.Content,{side:"bottom",classNames:"z-50"},X(se?"copy success label":"copy self public key label"),React.createElement(Tooltip.Arrow,null))))),React.createElement(Avatar.Label,{classNames:"sr-only","data-testid":"identityHeading.displayName"},((ve=U.profile)==null?void 0:ve.displayName)??generateName(U.identityKey.toHex())),React.createElement(Input$1.Root,null,React.createElement(Input$1.Label,{srOnly:!0},X("display name input label")),React.createElement(Input$1.TextInput,{variant:"subdued","data-testid":"display-name-input",placeholder:X("display name input placeholder"),classNames:"mbs-2 text-center font-light text-xl",value:Z,onChange:({target:{value:me}})=>{Q(me)},onBlur:de}))))},IdentityPanelImpl=$=>{const{identity:I,titleId:U,activeView:q,onUpdateProfile:G,onResetStorage:K,onJoinNewIdentity:Y,IdentityActionChooser:J=IdentityActionChooser,InvitationManager:X=InvitationManager,connectionState:Z,onChangeConnectionState:Q,onDone:ee,...te}=$,{t:ne}=useTranslation("os"),ie=React.useMemo(()=>{switch(q){case"device invitation manager":return ne("choose add device label");default:return ne("identity heading")}},[q,ne]),oe=()=>{var ce;return(ce=te.send)==null?void 0:ce.call(te,"unchooseAction")};return React.createElement(DensityProvider,{density:"fine"},React.createElement(IdentityHeading,{identity:I,titleId:U,title:ie,onDone:ee,onUpdateProfile:G,connectionState:Z,onChangeConnectionState:Q}),React.createElement(Viewport.Root,{activeView:q},React.createElement(Viewport.Views,null,React.createElement(Viewport.View,{id:"identity action chooser",classNames:viewStyles},React.createElement(J,{active:q==="identity action chooser",...te})),React.createElement(Viewport.View,{id:"device invitation manager",classNames:viewStyles},React.createElement(X,{active:q==="device invitation manager",...te,invitationUrl:te.createInvitationUrl(te.invitationCode)})),React.createElement(Viewport.View,{classNames:viewStyles,id:"confirm join new identity"},React.createElement(ConfirmReset,{active:q==="confirm join new identity",...te,mode:"join new identity",onConfirm:Y,onCancel:oe})),React.createElement(Viewport.View,{classNames:viewStyles,id:"confirm reset storage"},React.createElement(ConfirmReset,{active:q==="confirm reset storage",...te,mode:"reset storage",onConfirm:K,onCancel:oe})))))},IdentityPanelWithInvitationImpl=({invitation:$,...I})=>{const U=useInvitationStatus($);return React.createElement(IdentityPanelImpl,{...I,...U})},IdentityPanel=({titleId:$,createInvitationUrl:I=G=>G,initialDisposition:U="default",...q})=>{const G=useId("identityPanel__heading",$),K=reactClient.useClient(),Y=halo.useDevices(),J=halo.useIdentity(),X=halo.useHaloInvitations(),Z=useAgentHandlers({client:K,identity:J,invitations:X});if(!J)return log$2.error("IdentityPanel rendered with no active identity."),null;const[Q,ee,te]=useIdentityMachine(K,{context:{initialDisposition:U}}),{swarm:ne}=useNetworkStatus(),ie=async se=>K==null?void 0:K.mesh.updateConfig(se);React.useEffect(()=>te.subscribe(de=>{log$2("[state]",de)}).unsubscribe,[te]);const oe=React.useMemo(()=>{switch(!0){case Q.matches("choosingAction"):return"identity action chooser";case Q.matches("managingDeviceInvitation"):return"device invitation manager";case Q.matches("confirmingResetStorage"):return"confirm reset storage";case Q.matches("confirmingJoinNewIdentity"):return"confirm join new identity";default:return"identity action chooser"}},[Q]),fe={...q,identity:J,devices:Y,activeView:oe,send:ee,titleId:G,createInvitationUrl:I,onUpdateProfile:async se=>{ee({type:"updateProfile"}),await K.halo.updateProfile(se)},connectionState:ne,onChangeConnectionState:ie,...Z};return Q.context.invitation?React.createElement(IdentityPanelWithInvitationImpl,{...fe,invitation:Q.context.invitation}):React.createElement(IdentityPanelImpl,{...fe})},JoinHeading=React.forwardRef(({mode:$,titleId:I,onExit:U,exitActionParent:q},G)=>{const{t:K}=useTranslation("os"),Y=React.createElement(Button,{variant:"ghost",...U&&{onClick:U},classNames:mx(descriptionText,"plb-0 pli-2 absolute block-start-0 inline-end-0 z-[1]"),"data-testid":"join-exit"},React.createElement(react.X,{weight:"bold",className:getSize(4)}),React.createElement("span",{className:"sr-only"},K("exit label")));return React.createElement(Heading,{ref:G,titleId:I,title:K($==="halo-only"?"selecting identity heading":"joining space heading"),...$==="halo-only"?{titleSrOnly:!0}:{corner:q?React.cloneElement(q,{},Y):Y},titleSrOnly:$==="halo-only"})}),getInvitationSubscribable=($,I)=>(log$2("[subscribing to invitation]",I),{subscribe:(U,q,G)=>I.subscribe(K=>{switch(K.state){case Invitation.State.CONNECTING:return log$2("[invitation connecting]",{Kind:$,invitation:K}),U({type:`connecting${$}Invitation`,invitation:K});case Invitation.State.CONNECTED:return log$2("[invitation connected]",{Kind:$,invitation:K}),U({type:`connected${$}Invitation`,invitation:K});case Invitation.State.READY_FOR_AUTHENTICATION:return log$2("[invitation ready for authentication]",{Kind:$,invitation:K}),U({type:`readyForAuthentication${$}Invitation`,invitation:K});case Invitation.State.AUTHENTICATING:return log$2("[invitation authenticating]",{Kind:$,invitation:K}),U({type:`authenticating${$}Invitation`,invitation:K});case Invitation.State.SUCCESS:return log$2("[invitation success]",{Kind:$,invitation:K}),U({type:`success${$}Invitation`,invitation:K}),G==null?void 0:G();case Invitation.State.CANCELLED:return log$2.warn("[invitation cancelled]",{Kind:$}),U({type:`fail${$}Invitation`,reason:"cancelled"});case Invitation.State.TIMEOUT:return log$2.error("[invitation timeout]",{Kind:$}),U({type:`fail${$}Invitation`,reason:"timeout"})}},K=>K instanceof reactClient.AlreadyJoinedError?(log$2("[already joined]",{Kind:$,error:K}),U({type:`success${$}Invitation`,invitation:I.get()}),G==null?void 0:G()):(log$2.error("[invitation errored]",{Kind:$,error:K}),U({type:`fail${$}Invitation`,reason:"error"}),q==null?void 0:q(K)))}),acceptingInvitationTemplate=($,I)=>({initial:`unknown${$}`,states:{[`unknown${$}`]:{always:[{cond:({mode:q})=>q==="halo-only"&&$==="Space",target:"#join.finishingJoiningHalo"},{cond:q=>!!q[$.toLowerCase()].unredeemedCode,target:`acceptingRedeemed${$}Invitation`,actions:[`redeem${$}InvitationCode`,`invalidate${$}InvitationCode`,"log"]},{target:`inputting${$}InvitationCode`,actions:"log"}]},[`inputting${$}InvitationCode`]:{},[`acceptingRedeemed${$}Invitation`]:{invoke:{src:q=>q[$.toLowerCase()].invitationSubscribable},initial:`unknown${$}Invitation`,states:{[`unknown${$}Invitation`]:{always:[{cond:q=>{var G,K;if($!=="Space")return!1;{const Y=(K=(G=q.space.invitation)==null?void 0:G.spaceKey)==null?void 0:K.toHex(),J=q.space.succeededKeys;return Y?!!(J!=null&&J.has(Y)):!1}},target:I,actions:"log"},{cond:q=>{const G=q[$.toLowerCase()].invitation;return!G||(G==null?void 0:G.state)===Invitation.State.CONNECTING},target:`connecting${$}Invitation`,actions:"log"},{target:`inputting${$}VerificationCode`,actions:"log"}]},[`connecting${$}Invitation`]:{},[`inputting${$}VerificationCode`]:{},[`authenticating${$}VerificationCode`]:{on:{[`readyForAuthentication${$}Invitation`]:{target:`authenticationFailing${$}VerificationCode`,actions:["setInvitation","log"]}}},[`authenticationFailing${$}VerificationCode`]:{},[`failing${$}Invitation`]:{},[`success${$}Invitation`]:{}},on:{[`reset${$}Invitation`]:{target:`#join${$==="Halo"?".choosingIdentity":""}.accepting${$}Invitation.unknown${$}`,actions:["resetInvitation","log"]},[`connecting${$}Invitation`]:{target:`.connecting${$}Invitation`,actions:["setInvitation","log"]},[`connected${$}Invitation`]:{target:`.connecting${$}Invitation`,actions:["setInvitation","log"]},[`readyForAuthentication${$}Invitation`]:{target:`.inputting${$}VerificationCode`,actions:["setInvitation","log"]},[`authenticating${$}Invitation`]:{target:`.authenticating${$}VerificationCode`,actions:["setInvitation","log"]},[`success${$}Invitation`]:{target:I,actions:["setInvitation","log"]},[`fail${$}Invitation`]:{target:`.failing${$}Invitation`,actions:[assign({[$.toLowerCase()]:(q,G)=>({...q[$.toLowerCase()],failReason:G.reason})}),"log"]}}}},on:{[`set${$}InvitationCode`]:{target:`.acceptingRedeemed${$}Invitation`,actions:[assign({[$.toLowerCase()]:(q,G)=>({...q[$.toLowerCase()],unredeemedCode:G.code,succeededKeys:G.succeededKeys})}),`redeem${$}InvitationCode`,`invalidate${$}InvitationCode`,"log"]}}}),joinMachine=createMachine({id:"join",predictableActionArguments:!0,context:{initialDisposition:"default",mode:"default",identity:null,halo:{},space:{}},initial:"unknown",states:{unknown:{always:[{cond:"existingIdentity",target:"resettingIdentity",actions:"log"},{cond:"initiallyAcceptingHaloInvitation",target:"#join.choosingIdentity.acceptingHaloInvitation",actions:"log"},{cond:"noSelectedIdentity",target:"choosingIdentity",actions:"log"},{target:"acceptingSpaceInvitation",actions:"log"}]},choosingIdentity:{initial:"unknownAuthMethod",states:{unknownAuthMethod:{always:[{cond:"hasHaloUnredeemedCode",target:"acceptingHaloInvitation",actions:"log"},{target:"choosingAuthMethod",actions:"log"}]},choosingAuthMethod:{},recoveringIdentity:{},creatingIdentity:{},acceptingHaloInvitation:acceptingInvitationTemplate("Halo","#join.acceptingSpaceInvitation"),confirmingAddedIdentity:{}},on:{recoverIdentity:{target:".recoveringIdentity",actions:"log"},createIdentity:{target:".creatingIdentity",actions:"log"},acceptHaloInvitation:{target:".acceptingHaloInvitation",actions:"log"},addIdentity:{target:".confirmingAddedIdentity",actions:"log"},selectIdentity:{target:"acceptingSpaceInvitation",actions:["setIdentity","log"]},deselectAuthMethod:{target:".choosingAuthMethod",actions:"log"}}},resettingIdentity:{},acceptingSpaceInvitation:acceptingInvitationTemplate("Space","#join.finishingJoiningSpace"),finishingJoiningSpace:{type:"final"},finishingJoiningHalo:{type:"final"}},on:{resetIdentity:{target:"choosingIdentity",actions:"unsetIdentity"}}},{guards:{existingIdentity:({identity:$,mode:I},U)=>I==="halo-only"&&!!$,noSelectedIdentity:({identity:$},I)=>!$,initiallyAcceptingHaloInvitation:({identity:$,initialDisposition:I},U)=>!$&&I==="accept-halo-invitation",hasHaloUnredeemedCode:({halo:$},I)=>!!$.unredeemedCode,noSpaceInvitation:({space:$},I)=>!$.invitation&&!$.unredeemedCode},actions:{setIdentity:assign({identity:($,I)=>I.identity}),unsetIdentity:assign({identity:()=>null}),resetInvitation:assign({halo:($,I)=>I.type!=="resetHaloInvitation"?$.halo:($.halo.invitationObservable&&$.halo.invitationObservable.cancel(),{...$.halo,invitation:void 0,invitationObservable:void 0,invitationSubscribable:void 0}),space:($,I)=>I.type!=="resetSpaceInvitation"?$.space:($.space.invitationObservable&&$.space.invitationObservable.cancel(),{...$.space,invitation:void 0,invitationObservable:void 0,invitationSubscribable:void 0})}),setInvitation:assign({halo:($,I)=>I.type.includes("Halo")?{...$.halo,invitation:I.invitation}:$.halo,space:($,I)=>I.type.includes("Space")?{...$.space,invitation:I.invitation}:$.space}),log:($,I)=>{log$2("[transition]",{event:I,haloInvitation:$.halo.invitation,spaceInvitation:$.space.invitation})}}}),defaultCodeFromUrl=($,I)=>{try{const U=new URLSearchParams(I.substring(I.lastIndexOf("?")));return U.get(`${$}InvitationCode`)??U.get(`${$}Invitation`)??U.get("invitationCode")??U.get("invitation")??I}catch(U){return log$2.catch(U),I}},useJoinMachine=($,I)=>{const U=React.useCallback(({halo:Y})=>{if(Y.unredeemedCode)try{const J=clientProtocol.InvitationEncoder.decode(defaultCodeFromUrl("halo",Y.unredeemedCode)),X=$.halo.join(J);return{...Y,invitationObservable:X,invitationSubscribable:getInvitationSubscribable("Halo",X)}}catch(J){return log$2.error("Could not redeem device invitation code",J),Y}else return Y},[$]),q=React.useCallback(({space:Y})=>{if(Y.unredeemedCode)try{const J=clientProtocol.InvitationEncoder.decode(defaultCodeFromUrl("space",Y.unredeemedCode)),X=$.spaces.join(J);return{...Y,invitationObservable:X,invitationSubscribable:getInvitationSubscribable("Space",X)}}catch(J){return log$2.error("Could not redeem space invitation code",J),Y}else return Y},[$]),G=React.useCallback(({halo:Y})=>{var J;return Y.unredeemedCode?((J=I==null?void 0:I.onInvalidateInvitationCode)==null||J.call(I,Y.unredeemedCode),{...Y,unredeemedCode:void 0}):Y},[I==null?void 0:I.onInvalidateInvitationCode]),K=React.useCallback(({space:Y})=>{var J;return Y.unredeemedCode?((J=I==null?void 0:I.onInvalidateInvitationCode)==null||J.call(I,Y.unredeemedCode),{...Y,unredeemedCode:void 0}):Y},[I==null?void 0:I.onInvalidateInvitationCode]);return useMachine(joinMachine,{...I,actions:{...I==null?void 0:I.actions,redeemHaloInvitationCode:assign({halo:U}),redeemSpaceInvitationCode:assign({space:q}),invalidateHaloInvitationCode:assign({halo:G}),invalidateSpaceInvitationCode:assign({space:K})}})},AdditionMethodChooser=$=>{const I=!$.active,{send:U}=$,{t:q}=useTranslation("os"),G={disabled:I,after:React.createElement(react.CaretRight,{className:getSize(4),weight:"bold"}),slots:{label:{className:"text-sm"}}};return React.createElement(React.Fragment,null,React.createElement(StepHeading,null,q("addition method chooser title")),React.createElement("div",{role:"none",className:"flex flex-col gap-1 grow"},React.createElement(CompoundButton,{...G,description:q("create identity description"),before:React.createElement(react.Plus,{className:getSize(6)}),onClick:()=>U({type:"createIdentity"}),"data-autofocus":"choosingAuthMethod","data-testid":"identity-chooser.create-identity"},q("create identity label")),React.createElement(CompoundButton,{...G,description:q("join identity description"),before:React.createElement(react.QrCode,{className:getSize(6)}),onClick:()=>U({type:"acceptHaloInvitation"}),"data-testid":"identity-chooser.join-identity"},q("join identity label")),React.createElement(CompoundButton,{...G,disabled:!0,description:q("recover identity description"),before:React.createElement(react.Textbox,{className:getSize(6)}),onClick:()=>U({type:"recoverIdentity"}),"data-testid":"identity-chooser.recover-identity"},q("recover identity label"))))},IdentityAdded=$=>{var ie,oe,ce,fe,se,de;const{mode:I,addedIdentity:U,active:q,send:G,onDone:K,doneActionParent:Y}=$,J=!q,{t:X}=useTranslation("os"),Z=(U==null?void 0:U.identityKey.toHex())??"0",Q=hexToFallback(Z),ee=useId("identityListItem__label"),te=((ie=U==null?void 0:U.profile)==null?void 0:ie.displayName)??(U&&generateName(Z)),ne=React.createElement(Action,{...K&&{onClick:()=>K(null)},disabled:J,"data-autofocus":"confirmingAddedIdentity","data-testid":"identity-added-done"},React.createElement("span",null,X("done label")));return React.createElement(React.Fragment,null,React.createElement(StepHeading,null,X("identity added label")),React.createElement("div",{role:"none",className:"grow flex flex-col items-center justify-center text-center gap-2"},React.createElement(Avatar.Root,{status:"active",labelId:ee,hue:((ce=(oe=U==null?void 0:U.profile)==null?void 0:oe.data)==null?void 0:ce.hue)||Q.hue},React.createElement(Avatar.Frame,null,React.createElement(Avatar.Fallback,{text:((se=(fe=U==null?void 0:U.profile)==null?void 0:fe.data)==null?void 0:se.emoji)||Q.emoji})),React.createElement(Avatar.Label,{classNames:mx("text-lg truncate",!((de=U==null?void 0:U.profile)!=null&&de.displayName)&&"font-mono")},te))),React.createElement(Actions,null,I==="halo-only"?Y?React.cloneElement(Y,{},ne):ne:React.createElement(Action,{variant:"primary",disabled:J||!U,onClick:()=>U&&G({type:"selectIdentity",identity:U}),"data-autofocus":"confirmingAddedIdentity"},X("continue label"))))},IdentityInput=$=>{const{send:I,method:U}=$,q=U==="recover identity",G=reactClient.useClient(),{t:K}=useTranslation("os"),[Y,J]=React.useState(""),X=Z=>{G.halo.createIdentity({[q?"seedphrase":"displayName"]:Z}).then(Q=>{I==null||I({type:"selectIdentity",identity:Q})},Q=>{log$2.catch(Q),J(K(q?"failed to recover identity message":"failed to create identity message"))})};return React.createElement(IdentityInputImpl,{...$,onDisplayNameConfirm:X,validationMessage:Y})},IdentityInputImpl=$=>{const{method:I,send:U,active:q,onDisplayNameConfirm:G,validationMessage:K}=$,Y=!q,{t:J}=useTranslation("os"),[X,Z]=React.useState(""),Q=I==="recover identity";return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},React.createElement(Input,{validationMessage:K,label:React.createElement(StepHeading,null,J(Q?"recover identity input label":"new identity input label")),disabled:Y,"data-testid":"identity-input",placeholder:Q?"Type your recovery phrase":"Type a display name",onChange:({target:{value:ee}})=>Z(ee)})),React.createElement(Actions,null,React.createElement(Action,{variant:"ghost",disabled:Y,onClick:()=>U==null?void 0:U({type:"deselectAuthMethod"}),"data-testid":`${I==="recover identity"?"recover":"create"}-identity-input-back`},J("back label")),React.createElement(Action,{variant:"primary",disabled:Y,onClick:()=>G==null?void 0:G(X),"data-testid":`${I==="recover identity"?"recover":"create"}-identity-input-continue`},J("continue label"))))},InvitationAccepted=$=>{const{active:I,Kind:U,doneActionParent:q,onDone:G}=$,K=!I,{t:Y}=useTranslation("os"),J=React.createElement(Action,{variant:"primary",onClick:G,disabled:K,"data-autofocus":`success${U}Invitation finishingJoining${U}`,"data-testid":`${U.toLowerCase()}-invitation-accepted-done`},Y("done label"));return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},React.createElement("p",{className:"text-center text-sm font-normal"},Y("welcome message"))),React.createElement(Actions,null,q?React.cloneElement(q,{},J):J))},invitationCodeFromUrl=$=>{try{const I=new URLSearchParams($.substring($.lastIndexOf("?")));return I.get("spaceInvitationCode")??I.get("deviceInvitationCode")??$}catch(I){return log$2.catch(I),$}},InvitationInput=$=>{const{Kind:I,active:U,send:q,unredeemedCode:G,onExit:K,exitActionParent:Y,onDone:J,doneActionParent:X,succeededKeys:Z}=$,Q=!U,{t:ee}=useTranslation("os"),[te,ne]=React.useState(G??"");React.useEffect(()=>{G&&ne(G??"")},[G]);const ie=()=>{te.trim().length!==0&&q({type:`set${I}InvitationCode`,code:invitationCodeFromUrl(te),...I==="Space"&&{succeededKeys:Z}})},oe=React.createElement(Action,{variant:"ghost",disabled:Q,...K?{onClick:()=>K()}:{onClick:()=>J==null?void 0:J(null)},"data-testid":"join-exit"},ee("cancel label"));return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},React.createElement(Input,{label:React.createElement(StepHeading,null,ee("invitation input label")),placeholder:"Type an invitation code",disabled:Q,value:te,onChange:({target:{value:ce}})=>ne(ce),"data-autofocus":`inputting${I}InvitationCode`,"data-testid":`${I.toLowerCase()}-invitation-input`,onKeyUp:({key:ce})=>ce==="Enter"&&ie()})),React.createElement(Actions,null,I==="Halo"?React.createElement(Action,{variant:"ghost",disabled:Q,onClick:()=>q({type:"deselectAuthMethod"}),"data-testid":`${I.toLowerCase()}-invitation-input-back`},ee("back label")):Y?React.cloneElement(Y,{},oe):X?React.cloneElement(X,{},oe):oe,React.createElement(Action,{variant:"primary",disabled:Q,onClick:ie,"data-testid":`${I.toLowerCase()}-invitation-input-continue`},ee("continue label"))))},InvitationActions=({invitationState:$,onInvitationCancel:I,active:U,send:q,Kind:G,failReason:K})=>{const{t:Y}=useTranslation("os");return K?React.createElement(React.Fragment,null,React.createElement(StepHeading,{className:descriptionText},Y(K==="timeout"?"timeout status label":K==="cancelled"?"cancelled status label":"error status label")),React.createElement("div",{role:"none",className:"grow"}),React.createElement(Actions,null,React.createElement(Action,{disabled:!U,onClick:()=>q({type:`reset${G}Invitation`}),"data-testid":"invitation-rescuer-reset"},Y("reset label")))):React.createElement(React.Fragment,null,React.createElement(StepHeading,{className:descriptionText},Y("connecting status label")),React.createElement("div",{role:"none",className:"grow"}),React.createElement(Actions,null,React.createElement(Action,{disabled:!0,classNames:"order-2","data-testid":"next"},Y("next label")),React.createElement(Action,{disabled:!U,onClick:I,"data-testid":"invitation-rescuer-cancel"},Y("cancel label"))))},InvitationRescuer=$=>{const{Kind:I,invitationState:U,active:q,send:G}=$,{t:K}=useTranslation("os");return React.createElement(React.Fragment,null,typeof U>"u"?React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},React.createElement(StepHeading,{className:descriptionText},"There was a problem joining the space")),React.createElement(Actions,null,React.createElement(Action,{disabled:!q,"data-testid":"invitation-rescuer-blank-reset",onClick:()=>G({type:`reset${I}Invitation`})},K("reset label")))):React.createElement(InvitationActions,{...$}))},pinLength=6,InvitationAuthenticator=({failed:$,Kind:I,active:U,pending:q,invitationId:G,onInvitationAuthenticate:K,onInvitationCancel:Y})=>{const J=!U||q,{t:X}=useTranslation("os"),Z=I.toLowerCase(),[Q,ee]=React.useState(""),te=({target:{value:ne}})=>{var ie;ee(ne),ne.length===pinLength&&((ie=document.querySelector(`[data-autofocus-pinlength="${Z}"]`))==null||ie.focus())};return React.createElement(React.Fragment,null,React.createElement("div",{role:"none",className:"grow flex flex-col justify-center"},G&&React.createElement(Emoji,{text:hexToEmoji(G)}),React.createElement(Input$1.Root,{...$&&{validationValence:"error"}},React.createElement(Input$1.Label,{asChild:!0},React.createElement(StepHeading,null,X("auth code input label"))),React.createElement(Input$1.PinInput,{disabled:J,length:pinLength,onChange:te,inputMode:"numeric",autoComplete:"off",pattern:"\\d*","data-autofocus":`connecting${I}Invitation inputting${I}VerificationCode authenticationFailing${I}VerificationCode authenticating${I}VerificationCode`,"data-prevent-ios-autofocus":!0,"data-testid":`${Z}-auth-code-input`,"data-1p-ignore":!0}),$&&React.createElement(Input$1.DescriptionAndValidation,{classNames:"text-center"},React.createElement(Input$1.Validation,null,X("failed to authenticate message"))))),React.createElement(Actions,null,React.createElement(Action,{variant:"ghost",disabled:J,onClick:()=>Y==null?void 0:Y(),"data-testid":`${Z}-invitation-authenticator-cancel`},X("cancel label")),React.createElement(Action,{variant:"primary",disabled:J,onClick:()=>K==null?void 0:K(Q),"data-autofocus-pinlength":Z,"data-testid":`${Z}-invitation-authenticator-next`},X("next label"))))},stepStyles="pbs-1 pbe-3 pli-3",JoinPanelImpl=$=>{const{titleId:I,send:U,activeView:q,failed:G,mode:K,unredeemedCodes:Y,invitationStates:J,succeededKeys:X,failReasons:Z,onExit:Q,onHaloDone:ee,onSpaceDone:te,exitActionParent:ne,doneActionParent:ie,onHaloInvitationCancel:oe,onSpaceInvitationCancel:ce,onHaloInvitationAuthenticate:fe,onSpaceInvitationAuthenticate:se,onCancelResetStorage:de,onConfirmResetStorage:ue,IdentityInput:pe=IdentityInput,ConfirmReset:ve=ConfirmReset}=$;return React.createElement(DensityProvider,{density:"fine"},K!=="halo-only"&&React.createElement(JoinHeading,{titleId:I,mode:K,onExit:Q,exitActionParent:ne}),React.createElement(Viewport.Root,{focusManaged:!0,activeView:q},React.createElement(Viewport.Views,null,React.createElement(Viewport.View,{classNames:stepStyles,id:"addition method chooser"},React.createElement(AdditionMethodChooser,{send:U,active:q==="addition method chooser"})),React.createElement(Viewport.View,{classNames:stepStyles,id:"reset storage confirmation"},React.createElement(ve,{send:U,active:q==="reset identity confirmation",onCancel:de,onConfirm:ue})),React.createElement(Viewport.View,{classNames:stepStyles,id:"create identity input"},React.createElement(pe,{send:U,method:"create identity",active:q==="create identity input"})),React.createElement(Viewport.View,{classNames:stepStyles,id:"recover identity input"},React.createElement(pe,{send:U,method:"recover identity",active:q==="recover identity input"})),React.createElement(Viewport.View,{classNames:stepStyles,id:"halo invitation input"},React.createElement(InvitationInput,{send:U,Kind:"Halo",active:q==="halo invitation input",...(Y==null?void 0:Y.Halo)&&{unredeemedCode:Y.Halo},...(X==null?void 0:X.Halo)&&{succeededKeys:X.Halo}})),React.createElement(Viewport.View,{classNames:stepStyles,id:"halo invitation rescuer"},React.createElement(InvitationRescuer,{send:U,Kind:"Halo",active:q==="halo invitation rescuer",invitationState:J==null?void 0:J.Halo,onInvitationCancel:oe,failReason:Z==null?void 0:Z.Halo})),React.createElement(Viewport.View,{classNames:stepStyles,id:"halo invitation authenticator"},React.createElement(InvitationAuthenticator,{send:U,Kind:"Halo",active:q==="halo invitation authenticator",onInvitationCancel:oe,onInvitationAuthenticate:fe,...G.has("Halo")&&{failed:!0}})),React.createElement(Viewport.View,{classNames:stepStyles,id:"halo invitation accepted"},React.createElement(InvitationAccepted,{send:U,Kind:"Halo",active:q==="halo invitation accepted",doneActionParent:ie,onDone:ee})),React.createElement(Viewport.View,{classNames:stepStyles,id:"identity added"},React.createElement(IdentityAdded,{send:U,mode:K,active:q==="identity added",doneActionParent:ie,onDone:ee})),React.createElement(Viewport.View,{classNames:stepStyles,id:"space invitation input"},React.createElement(InvitationInput,{send:U,Kind:"Space",active:q==="space invitation input",...(Y==null?void 0:Y.Space)&&{unredeemedCode:Y.Space},...(X==null?void 0:X.Space)&&{succeededKeys:X.Space},onExit:Q,exitActionParent:ne})),React.createElement(Viewport.View,{classNames:stepStyles,id:"space invitation rescuer"},React.createElement(InvitationRescuer,{send:U,Kind:"Space",active:q==="space invitation rescuer",invitationState:J==null?void 0:J.Space,onInvitationCancel:ce,failReason:Z==null?void 0:Z.Space})),React.createElement(Viewport.View,{classNames:stepStyles,id:"space invitation authenticator"},React.createElement(InvitationAuthenticator,{send:U,Kind:"Space",active:q==="space invitation authenticator",onInvitationCancel:ce,onInvitationAuthenticate:se,...G.has("Space")&&{failed:!0}})),React.createElement(Viewport.View,{classNames:stepStyles,id:"space invitation accepted"},React.createElement(InvitationAccepted,{send:U,Kind:"Space",active:q==="space invitation accepted",doneActionParent:ie,onDone:te})))))},JoinPanel=({titleId:$,mode:I="default",initialDisposition:U="default",initialInvitationCode:q,exitActionParent:G,onExit:K,doneActionParent:Y,onDone:J,onCancelResetStorage:X})=>{const Z=reactClient.useClient(),Q=halo.useIdentity(),{hasIosKeyboard:ee}=useThemeContext(),te=useId("joinPanel__heading",$),[ne,ie,oe]=useJoinMachine(Z,{context:{mode:I,initialDisposition:U,identity:Q,...q&&{[I==="halo-only"?"halo":"space"]:{unredeemedCode:q}}}});React.useEffect(()=>oe.subscribe(xe=>{log$2("[state]",xe)}).unsubscribe,[oe]),React.useEffect(()=>{const Se=ne.configuration[0].id.split("."),xe=Se[Se.length-1],ke=xe==="finishingJoining"?"successSpaceInvitation":xe,De=document.querySelector(`[data-autofocus~="${ke}"]`);De&&!(ee&&De.hasAttribute("data-prevent-ios-autofocus"))&&De.focus()},[ne.value,ee]);const ce=React.useMemo(()=>{switch(!0){case ne.matches({choosingIdentity:"choosingAuthMethod"}):return"addition method chooser";case ne.matches("resettingIdentity"):return"reset identity confirmation";case ne.matches({choosingIdentity:"creatingIdentity"}):return"create identity input";case ne.matches({choosingIdentity:"recoveringIdentity"}):return"recover identity input";case ne.matches({choosingIdentity:{acceptingHaloInvitation:"inputtingHaloInvitationCode"}}):return"halo invitation input";case[{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"connectingHaloInvitation"}}},{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"failingHaloInvitation"}}}].some(ne.matches):return"halo invitation rescuer";case[{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"inputtingHaloVerificationCode"}}},{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"authenticatingHaloVerificationCode"}}},{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"authenticationFailingHaloVerificationCode"}}}].some(ne.matches):return"halo invitation authenticator";case[{choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"successHaloInvitation"}}},"finishingJoiningHalo"].some(ne.matches):return"halo invitation accepted";case ne.matches({choosingIdentity:"confirmingAddedIdentity"}):return"identity added";case ne.matches({acceptingSpaceInvitation:"inputtingSpaceInvitationCode"}):return"space invitation input";case[{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"connectingSpaceInvitation"}},{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"failingSpaceInvitation"}}].some(ne.matches):return"space invitation rescuer";case[{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"inputtingSpaceVerificationCode"}},{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"authenticatingSpaceVerificationCode"}},{acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"authenticationFailingSpaceVerificationCode"}}].some(ne.matches):return"space invitation authenticator";case ne.matches("finishingJoiningSpace"):return"space invitation accepted";default:return"never"}},[ne]),fe=React.useMemo(()=>{const Se=new Set;switch(!0){case ne.matches({choosingIdentity:{acceptingHaloInvitation:{acceptingRedeemedHaloInvitation:"authenticationFailingHaloVerificationCode"}}}):Se.add("Halo");break;case ne.matches({acceptingSpaceInvitation:{acceptingRedeemedSpaceInvitation:"authenticationFailingSpaceVerificationCode"}}):Se.add("Space");break}return Se},[ne]),se=React.useMemo(()=>({Halo:ne.context.halo.unredeemedCode,Space:ne.context.space.unredeemedCode}),[ne]),de=reactClient.useMulticastObservable(Z.spaces),ue=React.useMemo(()=>({Space:de?new Set(de.map(({key:Se})=>Se.toHex())):void 0}),[de]),pe=React.useMemo(()=>{var Se,xe;return{Halo:(Se=ne.context.halo.invitationObservable)==null?void 0:Se.get().state,Space:(xe=ne.context.space.invitationObservable)==null?void 0:xe.get().state}},[ne]),ve=React.useMemo(()=>({Halo:ne.context.halo.failReason,Space:ne.context.space.failReason}),[ne]),me=React.useCallback(()=>{var Se,xe,ke,De;J==null||J({identityKey:((Se=ne.context.halo.invitation)==null?void 0:Se.identityKey)??null,swarmKey:((xe=ne.context.halo.invitation)==null?void 0:xe.swarmKey)??null,spaceKey:((ke=ne.context.halo.invitation)==null?void 0:ke.spaceKey)??null,target:((De=ne.context.halo.invitation)==null?void 0:De.target)??null})},[ne,J]),be=React.useCallback(()=>{var Se,xe,ke,De;J==null||J({identityKey:((Se=ne.context.space.invitation)==null?void 0:Se.identityKey)??null,swarmKey:((xe=ne.context.space.invitation)==null?void 0:xe.swarmKey)??null,spaceKey:((ke=ne.context.space.invitation)==null?void 0:ke.spaceKey)??null,target:((De=ne.context.space.invitation)==null?void 0:De.target)??null})},[ne,J]),_e=React.useCallback(()=>Z.reset().then(()=>{ie({type:"resetIdentity"})}),[Z,ie]);return React.createElement(JoinPanelImpl,{titleId:te,mode:I,send:ie,activeView:ce,failed:fe,failReasons:ve,pending:["connecting","authenticating"].some(Se=>ne==null?void 0:ne.configuration[0].id.includes(Se)),unredeemedCodes:se,invitationStates:pe,succeededKeys:ue,identity:Q,onExit:K,exitActionParent:G,doneActionParent:Y,onHaloDone:me,onSpaceDone:be,onHaloInvitationCancel:()=>{var Se;return(Se=ne.context.halo.invitationObservable)==null?void 0:Se.cancel()},onSpaceInvitationCancel:()=>{var Se;return(Se=ne.context.space.invitationObservable)==null?void 0:Se.cancel()},onHaloInvitationAuthenticate:Se=>{var xe;return ie({type:"authenticateHaloVerificationCode"}),(xe=ne.context.halo.invitationObservable)==null?void 0:xe.authenticate(Se)},onSpaceInvitationAuthenticate:Se=>{var xe;return ie({type:"authenticateSpaceVerificationCode"}),(xe=ne.context.space.invitationObservable)==null?void 0:xe.authenticate(Se)},onConfirmResetStorage:_e,onCancelResetStorage:X})},spaceMachine=createMachine({id:"space",predictableActionArguments:!0,context:{space:null},initial:"managingSpace",states:{managingSpace:{},managingSpaceInvitation:{}},on:{deselectInvitation:{target:".managingSpace",actions:["unsetInvitation","log"]},selectInvitation:{target:".managingSpaceInvitation",actions:["setInvitation","log"]}}},{actions:{setInvitation:assign({invitation:($,I)=>(I==null?void 0:I.invitation)??null}),unsetInvitation:assign({invitation:()=>{}}),log:($,I)=>{log$2("[transition]",{event:I,context:$})}}}),useSpaceMachine=$=>useMachine(spaceMachine,{...$,context:{...$==null?void 0:$.context}}),activeActionKey="dxos:react-shell/space-manager/active-action",SpaceManager=$=>{const{space:I,target:U}=$,{t:q}=useTranslation("os"),G=reactClient.useConfig(),K=echo.useSpaceInvitations(I==null?void 0:I.key),Y=React.useCallback(X=>{const Z=clientProtocol.InvitationEncoder.encode(X);X.state===Invitation.State.CONNECTING&&log$2.info(JSON.stringify({invitationCode:Z,authCode:X.authCode}))},[]),J={inviteOne:{label:q("invite one label"),description:q("invite one description"),icon:react.UserPlus,onClick:React.useCallback(()=>{var Z,Q,ee,te;const X=(Z=I.share)==null?void 0:Z.call(I,{type:Invitation.Type.INTERACTIVE,authMethod:Invitation.AuthMethod.SHARED_SECRET,multiUse:!1,target:U});X&&((te=(ee=(Q=G.values.runtime)==null?void 0:Q.app)==null?void 0:ee.env)==null?void 0:te.DX_ENVIRONMENT)!=="production"&&X.subscribe(Y)},[I])},inviteMany:{label:q("invite many label"),description:q("invite many description"),icon:react.UsersThree,onClick:React.useCallback(()=>{var Z,Q,ee,te;const X=(Z=I.share)==null?void 0:Z.call(I,{type:Invitation.Type.INTERACTIVE,authMethod:Invitation.AuthMethod.NONE,multiUse:!0,target:U});X&&((te=(ee=(Q=G.values.runtime)==null?void 0:Q.app)==null?void 0:ee.env)==null?void 0:te.DX_ENVIRONMENT)!=="production"&&X.subscribe(Y)},[I])}};return React.createElement(SpaceManagerImpl,{...$,invitations:K,inviteActions:J})},headingFragment="pis-3 pie-1 plb-1 mbe-1 font-medium",SpaceManagerImpl=$=>{const{active:I,space:U,createInvitationUrl:q,send:G,inviteActions:K,invitations:Y,showInactiveInvitations:J,SpaceMemberList:X=SpaceMemberList,InvitationList:Z=InvitationList}=$,{t:Q}=useTranslation("os"),ee=K??{noopInvite:{label:Q("create space invitation label"),description:"",icon:react.Placeholder,onClick:()=>{}}},[te,ne]=React.useState(localStorage.getItem(activeActionKey)??"inviteOne"),ie=ce=>{ne(ce),localStorage.setItem(activeActionKey,ce)},oe=J?Y:Y==null?void 0:Y.filter(ce=>![Invitation.State.CANCELLED].includes(ce.get().state));return React.createElement(React.Fragment,null,React.createElement(ScrollArea.Root,{classNames:"grow shrink basis-28 -mli-2"},React.createElement(ScrollArea.Viewport,{classNames:"is-full pie-2"},!!(oe!=null&&oe.length)&&React.createElement(React.Fragment,null,React.createElement("h3",{className:mx(headingFragment,descriptionText)},Q("invitation list heading")),React.createElement(Z,{className:"mb-2",send:G,invitations:oe??[],onClickRemove:ce=>ce.cancel(),createInvitationUrl:q}),React.createElement("h3",{className:mx(headingFragment,descriptionText,"mbs-2")},Q("space member list heading"))),React.createElement(X,{spaceKey:U.key,includeSelf:!0})),React.createElement(ScrollArea.Scrollbar,{orientation:"vertical"},React.createElement(ScrollArea.Thumb,null))),React.createElement(Actions,null,React.createElement(BifurcatedAction,{disabled:!I,actions:ee,activeAction:te,onChangeActiveAction:ie,"data-testid":"spaces-panel.create-invitation"})))},SpacePanelHeading=({titleId:$,space:I,onDone:U})=>{const{t:q}=useTranslation("os"),G=I.properties.name;return React.createElement(Heading,{titleId:$,title:q("space panel heading"),corner:React.createElement(CloseButton,{"data-testid":"identity-panel-done",onDone:U})},React.createElement("div",{role:"none",className:"flex gap-4 items-center justify-center mlb-4"},React.createElement(react.Planet,{size:32,weight:"light"}),React.createElement("div",{className:"block text-start font-light text-xl"},G??I.key.truncate())))},SpacePanelImpl=$=>{const{titleId:I,activeView:U,space:q,target:G,SpaceManager:K=SpaceManager,InvitationManager:Y=InvitationManager,...J}=$;return React.createElement(DensityProvider,{density:"fine"},React.createElement(SpacePanelHeading,{...J,titleId:I,space:q}),React.createElement(Viewport.Root,{activeView:U},React.createElement(Viewport.Views,null,React.createElement(Viewport.View,{id:"space manager",classNames:stepStyles},React.createElement(K,{active:U==="space manager",space:q,target:G,...J})),React.createElement(Viewport.View,{id:"space invitation manager",classNames:stepStyles},React.createElement(Y,{active:U==="space invitation manager",...J,invitationUrl:$.invitationUrl})))))},SpacePanelWithInvitationImpl=({invitation:$,...I})=>{const U=useInvitationStatus($);return React.createElement(SpacePanelImpl,{...I,...U,invitationUrl:I.createInvitationUrl(U.invitationCode)})},SpacePanel=({titleId:$,createInvitationUrl:I=q=>q,...U})=>{const q=useId("spacePanel__heading",$),[G,K,Y]=useSpaceMachine({context:{space:U.space}});React.useEffect(()=>Y.subscribe(Q=>{log$2("[state]",Q)}).unsubscribe,[Y]);const J=React.useMemo(()=>{switch(!0){case G.matches("managingSpace"):return"space manager";case G.matches("managingSpaceInvitation"):return"space invitation manager";default:return"never"}},[G]),X={...U,activeView:J,send:K,titleId:q,createInvitationUrl:I};return G.context.invitation?React.createElement(SpacePanelWithInvitationImpl,{...X,invitation:G.context.invitation}):React.createElement(SpacePanelImpl,{...X})},StatusPanel=({titleId:$})=>{const{t:I}=useTranslation("os");return React.createElement("div",{className:"grid place-items-center p-2 gap-2"},React.createElement("p",{id:$,className:"font-medium text-center"},I("resetting message")),React.createElement(Status,{indeterminate:!0},I("resetting message")))},IdentityDialog=$=>{const I=useId("identityDialog__title",$.title);return React.createElement(Dialog.Root,{defaultOpen:!0,onOpenChange:U=>{var q;return U||((q=$.onDone)==null?void 0:q.call($))}},React.createElement(Dialog.Portal,null,React.createElement(Dialog.Overlay,null,React.createElement(Dialog.Content,{"aria-labelledby":I,onOpenAutoFocus:U=>U.preventDefault()},React.createElement(ClipboardProvider,null,React.createElement(IdentityPanel,{...$,titleId:I,doneActionParent:React.createElement(Dialog.Close,{asChild:!0})}))))))},JoinDialog=$=>{const I=useId("joinDialog__title"),{height:U}=useVisualViewport();return React.createElement(AlertDialog.Root,{defaultOpen:!0,onOpenChange:q=>{var G;return q||($.onExit?$.onExit():(G=$.onDone)==null?void 0:G.call($,null))}},React.createElement(AlertDialog.Portal,null,React.createElement(AlertDialog.Overlay,{classNames:"backdrop-blur",...U&&{style:{blockSize:`${U}px`}}},React.createElement(AlertDialog.Content,{"aria-labelledby":I},React.createElement(JoinPanel,{...$,titleId:I,exitActionParent:React.createElement(AlertDialog.Cancel,{asChild:!0}),doneActionParent:React.createElement(AlertDialog.Action,{asChild:!0})})))))};var createRoot,m=$7SXl2$reactdom;if(process.env.NODE_ENV==="production")createRoot=m.createRoot,m.hydrateRoot;else{var i=m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;createRoot=function($,I){i.usingClientEntryPoint=!0;try{return m.createRoot($,I)}finally{i.usingClientEntryPoint=!1}}}const SpaceDialog=$=>{const I=useId("spaceDialog__title");return React.createElement(Dialog.Root,{defaultOpen:!0,onOpenChange:U=>{var q;return U||((q=$.onDone)==null?void 0:q.call($))}},React.createElement(Dialog.Portal,null,React.createElement(Dialog.Overlay,null,React.createElement(Dialog.Content,{"aria-labelledby":I},React.createElement(ClipboardProvider,null,React.createElement(SpacePanel,{...$,titleId:I,doneActionParent:React.createElement(Dialog.Close,{asChild:!0})}))))))},StatusDialog=()=>{const $=useId("statusDialog__title");return React.createElement(AlertDialog.Root,{open:!0},React.createElement(AlertDialog.Portal,null,React.createElement(AlertDialog.Overlay,null,React.createElement(AlertDialog.Content,{"aria-labelledby":$},React.createElement(StatusPanel,{titleId:$})))))},Shell=({runtime:$,origin:I})=>{const[{layout:U,invitationCode:q,spaceKey:G,target:K},Y]=React.useState({layout:$.layout,invitationCode:$.invitationCode,spaceKey:$.spaceKey,target:$.target}),J=reactClient.useClient(),X=echo.useSpace(G);switch(React.useEffect(()=>$.layoutUpdate.on(Z=>Y(Z)),[$]),React.useEffect(()=>{if(U===reactClient.ShellLayout.SPACE&&!X){log$2.warn("No space found for shell space invitations.");const Z=setTimeout(async()=>{await $.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})});return()=>clearTimeout(Z)}},[$,U,X]),U){case reactClient.ShellLayout.STATUS:return React.createElement(StatusDialog,null);case reactClient.ShellLayout.INITIALIZE_IDENTITY:case reactClient.ShellLayout.INITIALIZE_IDENTITY_FROM_INVITATION:return React.createElement(JoinDialog,{mode:"halo-only",initialDisposition:U===reactClient.ShellLayout.INITIALIZE_IDENTITY_FROM_INVITATION?"accept-halo-invitation":"default",initialInvitationCode:q,onCancelResetStorage:()=>$.setLayout({layout:reactClient.ShellLayout.IDENTITY}),onDone:()=>{$.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})}});case reactClient.ShellLayout.IDENTITY:case reactClient.ShellLayout.SHARE_IDENTITY:case reactClient.ShellLayout.EDIT_PROFILE:return React.createElement(IdentityDialog,{createInvitationUrl:Z=>`${I}?deviceInvitationCode=${Z}`,onResetStorage:async()=>($.setLayout({layout:reactClient.ShellLayout.STATUS}),await J.reset(),$.setAppContext({display:reactClient.ShellDisplay.NONE,reload:!0})),onJoinNewIdentity:async()=>($.setLayout({layout:reactClient.ShellLayout.STATUS}),await J.reset(),$.setLayout({layout:reactClient.ShellLayout.INITIALIZE_IDENTITY_FROM_INVITATION})),onDone:async()=>{await $.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})},initialDisposition:U===reactClient.ShellLayout.SHARE_IDENTITY?"manage-device-invitation":"default"});case reactClient.ShellLayout.SPACE:return X?React.createElement(SpaceDialog,{space:X,target:K,createInvitationUrl:Z=>`${I}?spaceInvitationCode=${Z}`,onDone:async()=>{await $.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})}}):null;case reactClient.ShellLayout.JOIN_SPACE:return React.createElement(JoinDialog,{initialInvitationCode:q,onDone:async Z=>{const Q=(Z==null?void 0:Z.target)??void 0;await $.setAppContext({display:reactClient.ShellDisplay.NONE,spaceKey:(Z==null?void 0:Z.spaceKey)??void 0,target:Q}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})},onExit:async()=>{await $.setAppContext({display:reactClient.ShellDisplay.NONE}),$.setLayout({layout:reactClient.ShellLayout.DEFAULT})}});default:return null}},os={"manage profile label":"Manage identity","identity offline description":"Offline","sidebar label":"DXOS sidebar","copy invitation code label":"Copy URL","copy success label":"Copied","copy self public key label":"Copy public key","open share panel label":"View QR code","joining space heading":"Joining space","join space heading":"Enter space invitation","halo heading":"Initialize device identity","exit label":"Exit","identity selector title":"Join as","identity radio group title":"Select an identity you’ve associated with this device already","add identity label":"Add","continue label":"Continue","back label":"Back","next label":"Next","close label":"Close","auth choices label":"Choose an identity","create identity label":"Create an identity","create identity description":"Create a new identity.","recover identity label":"Use a seed phrase","recover identity description":"Enter your seed phrase to log in manually.","join identity label":"Use another device","join identity description":"Add this device to an identity you’re already logged into on another device.","deselect identity label":"Back to identities","addition method chooser title":"An identity is required to continue","new identity input label":"Set display name","recover identity input label":"Type or paste your seed phrase","failed to create identity message":"Failed to create an identity.","failed to recover identity message":"Failed to recover an identity from the provided seed phrase.","failed to authenticate message":"Incorrect PIN.","identity added label":"Created identity & added to this device:","join space as identity heading":"<part>as </part><part><icon/><label>{{labelValue}}</label></part>","error status label":"Failed","timeout status label":"Timed out","cancelled status label":"Cancelled","init status label":"Ready to connect","connecting status label":"Connecting…","connected status label":"Enter confirmation PIN","authenticating status label":"Enter confirmation PIN","success status label":"Success","cancel label":"Cancel","done label":"Done","reset label":"Start over","auth code input label":"Enter the verification code","invitation input label":"Paste an invitation code or URL","create device invitation label":"Add device","create space invitation label":"Invite","qr label":"Scan to accept invitation","empty invitations message":"No pending invitations","empty device list message":"No devices authenticated other than this device.","show all spaces label":"All spaces","all spaces label":"All spaces","create space label":"Create a new space","join space label":"Join a space","show current space label":"Current space","view space invitations label":"View space invitations","toggle sidebar label":"Open/close sidebar","open sidebar label":"Open sidebar","close sidebar label":"Close sidebar","welcome message":"Welcome","selecting identity heading":"Selecting identity","devices heading":"Devices","identity heading":"Profile settings","choose add device label":"Add device","choose devices label":"Manage devices","choose profile label":"Edit profile","choose sign out label":"Reset storage","choose join new identity label":"Join existing device","empty space members message":"There is nobody in this space yet.","back to all invitations label":"Back to all invitations","invitation heading":"Invitation","invitation list heading":"Invitations","device invitation list heading":"Pending device invitations","space invitation list heading":"Pending invitations","device list heading":"Devices","space member list heading":"Members","space panel heading":"Space membership","auth code message":"Enter the following auth code on the joining device.","display name input label":"Display name","display name input placeholder":"Enter a display name","invite one label":"Invite one","invite one description":"Only one user may join.","invite one qr label":"Single-use","invite one list item label":"Active single-use invitation","invite many label":"Invite many","invite many description":"Anyone with the link can join.","invite many qr label":"Multiple-use","invite many list item label":"Active multiple-use invitation","invite options label":"Change the active invite option.","reset in progress label":"Resetting...","confirm label":"Confirm","reset storage input label":"This will clear this device and all associated data. Type {{confirmationValue}} and confirm to continue.","join new identity input label":"In order to join an existing device, storage on this device must be cleared first. Type {{confirmationValue}} to continue.","failed to reset identity message":"Failed to reset identity.","confirmation value":"CONFIRM","sign out chooser title":"Danger zone","sign out chooser message":"Proceeding with the action below will erase all data on this device.","join new identity label":"Join a new identity","reset device label":"Reset storage","reset device confirm message":"Are you sure you want to reset your device? All data will be lost.","emoji and color label":"Emoji and color","clear label":"Use default","select emoji label":"Choose an emoji to use in your avatar","select hue label":"Choose a hue to use in your avatar","resetting message":"One moment while things are reset…","red label":"Red","orange label":"Orange","amber label":"Amber","yellow label":"Yellow","lime label":"Lime","green label":"Green","emerald label":"Emerald","teal label":"Teal","cyan label":"Cyan","sky label":"Sky","blue label":"Blue","indigo label":"Indigo","violet label":"Violet","purple label":"Purple","fuchsia label":"Fuchsia","pink label":"Pink","rose label":"Rose","current device tag label":"This device","device name placeholder":"{{platform}} on {{os}}","more options label":"More options","disconnect label":"Currently online. Click to go offline.","connect label":"Currently offline. Click to go online.","edit device label":"Edit device name & avatar","agent heading":"Agent","agent message title":"About creating an agent","agent message body":"Creating an agent helps keep your devices and peers in-sync. An agent is like any other device, but since it’s always online your changes will sync even when all your physical devices are asleep.","create agent label":"Start an agent","destroy agent label":"Shut down agent","agent device label":"Your agent"},enUS=Object.freeze(Object.defineProperty({__proto__:null,os},Symbol.toStringTag,{value:"Module"})),osTranslations={"en-US":enUS},runShell=async($=new reactClient.Config)=>{const I=new reactClient.ClientServicesProxy(createIFramePort({channel:clientProtocol.DEFAULT_CLIENT_CHANNEL})),U=new reactClient.Client({config:$,services:I}),q=new clientServices.ShellRuntimeImpl(createIFramePort({channel:clientProtocol.DEFAULT_SHELL_CHANNEL}));await Promise.all([q.open(),U.initialize()]),createRoot(document.getElementById("root")).render(React.createElement(React.StrictMode,null,React.createElement(ThemeProvider,{tx:defaultTx,resourceExtensions:[osTranslations]},React.createElement(reactClient.ClientContext.Provider,{value:{client:U,status:reactClient.SystemStatus.ACTIVE}},React.createElement(ClipboardProvider,null,React.createElement(Tooltip.Provider,null,React.createElement(Shell,{runtime:q,origin:location.origin})))))))};React.createContext({});var __dxlog_file="/home/runner/work/dxos/dxos/packages/core/mesh/websocket-rpc/src/token-auth.ts",WebSocketWithTokenAuth=class extends WebSocket3{constructor($,I){const U=export_Buffer.from(I).toString("base64").replace(/=*$/,""),q=[`base64url.bearer.authorization.dxos.org.${U}`];super($,q),log$2("encodedToken",{encodedToken:U},{F:__dxlog_file,L:55,S:this,C:(G,K)=>G(...K)})}};function _ts_decorate($,I,U,q){var G=arguments.length,K=G<3?I:q===null?q=Object.getOwnPropertyDescriptor(I,U):q,Y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate($,I,U,q);else for(var J=$.length-1;J>=0;J--)(Y=$[J])&&(K=(G<3?Y(K):G>3?Y(I,U,K):Y(I,U))||K);return G>3&&K&&Object.defineProperty(I,U,K),K}var __dxlog_file2="/home/runner/work/dxos/dxos/packages/core/mesh/websocket-rpc/src/client.ts",WebsocketRpcClient=class{constructor($){this._params=$,this._connectTrigger=new Trigger,this.connected=new Event$1,this.disconnected=new Event$1,this.error=new Event$1,this._rpc=createProtoRpcPeer({requested:this._params.requested,exposed:this._params.exposed,handlers:this._params.handlers,port:{send:I=>{this._socket.send(I)},subscribe:I=>{this._socket.onmessage=async U=>{typeof Blob<"u"&&U.data instanceof Blob?I(export_Buffer.from(await U.data.arrayBuffer())):I(U.data)}}}})}get url(){return this._params.url}async open(){this._params.authenticationToken?this._socket=new WebSocketWithTokenAuth(this._params.url,this._params.authenticationToken):this._socket=new WebSocket3(this._params.url),this._socket.onopen=async()=>{log$2("Socket open",void 0,{F:__dxlog_file2,L:61,S:this,C:($,I)=>$(...I)});try{await this._rpc.open(),log$2(`RPC open ${this._params.url}`,void 0,{F:__dxlog_file2,L:64,S:this,C:($,I)=>$(...I)}),this.connected.emit(),this._connectTrigger.wake()}catch($){this.error.emit($)}},this._socket.onclose=async()=>{log$2(`Disconnected ${this._params.url}`,void 0,{F:__dxlog_file2,L:73,S:this,C:($,I)=>$(...I)}),this.disconnected.emit(),await this.close()},this._socket.onerror=$=>{log$2.error($.message??"Socket error",{url:this._params.url},{F:__dxlog_file2,L:80,S:this,C:(U,q)=>U(...q)});const I=$.error??new Error($.message);this.error.emit(I),this._connectTrigger.throw(I)},await this._connectTrigger.wait()}async close(){var $,I;try{await(($=this._rpc)==null?void 0:$.close())}catch(U){log$2.catch(U,void 0,{F:__dxlog_file2,L:93,S:this,C:(q,G)=>q(...G)})}(I=this._socket)==null||I.close()}get rpc(){return this._rpc.rpc}};_ts_decorate([logInfo],WebsocketRpcClient.prototype,"url",null);const index=Object.freeze(Object.defineProperty({__proto__:null,WebSocketWithTokenAuth,WebsocketRpcClient},Symbol.toStringTag,{value:"Module"}));exports.runShell=runShell,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})});
|
|
1002
1002
|
//# sourceMappingURL=shell.umd.js.map
|