@swapkit/wallet-hardware 6.2.0 → 6.3.0

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.
Files changed (77) hide show
  1. package/dist/THIRD_PARTY_LICENSES.md +4 -4
  2. package/dist/{chunk-rydhx4se.js → chunk-0k1b2ddn.js} +3 -3
  3. package/dist/{chunk-rydhx4se.js.map → chunk-0k1b2ddn.js.map} +2 -2
  4. package/dist/{chunk-j3n6fbqh.js → chunk-2tzsz8f3.js} +4 -4
  5. package/dist/{chunk-j3n6fbqh.js.map → chunk-2tzsz8f3.js.map} +1 -1
  6. package/dist/{chunk-2jddegc1.js → chunk-410fpx61.js} +4 -4
  7. package/dist/{chunk-2jddegc1.js.map → chunk-410fpx61.js.map} +1 -1
  8. package/dist/chunk-8mkdjmw2.js +4 -0
  9. package/dist/chunk-8mkdjmw2.js.map +10 -0
  10. package/dist/{chunk-7kwtpk70.js → chunk-96p7njae.js} +3 -3
  11. package/dist/{chunk-7kwtpk70.js.map → chunk-96p7njae.js.map} +2 -2
  12. package/dist/{chunk-g6rrzxcx.js → chunk-97nsp4z6.js} +3 -3
  13. package/dist/{chunk-g6rrzxcx.js.map → chunk-97nsp4z6.js.map} +1 -1
  14. package/dist/{chunk-kaw35ae2.js → chunk-9a9gn4pb.js} +3 -3
  15. package/dist/{chunk-a47dwwv6.js.map → chunk-9a9gn4pb.js.map} +1 -1
  16. package/dist/chunk-a39rm9nv.js +4 -0
  17. package/dist/{chunk-42xrtarj.js.map → chunk-a39rm9nv.js.map} +5 -5
  18. package/dist/chunk-c8mwf9cn.js +4 -0
  19. package/dist/{chunk-kaw35ae2.js.map → chunk-c8mwf9cn.js.map} +1 -1
  20. package/dist/{chunk-b7htg03t.js → chunk-dhhmywmb.js} +4 -4
  21. package/dist/{chunk-b7htg03t.js.map → chunk-dhhmywmb.js.map} +1 -1
  22. package/dist/{chunk-x28a37pz.js → chunk-dsa641rq.js} +3 -3
  23. package/dist/{chunk-x28a37pz.js.map → chunk-dsa641rq.js.map} +2 -2
  24. package/dist/{chunk-7rbvcts9.js → chunk-grj9nvte.js} +3 -3
  25. package/dist/{chunk-7rbvcts9.js.map → chunk-grj9nvte.js.map} +1 -1
  26. package/dist/{chunk-tecse0bj.js → chunk-napm4102.js} +3 -3
  27. package/dist/{chunk-tecse0bj.js.map → chunk-napm4102.js.map} +1 -1
  28. package/dist/{chunk-a47dwwv6.js → chunk-nb08g045.js} +3 -3
  29. package/dist/{chunk-sp3dq5hr.js.map → chunk-nb08g045.js.map} +1 -1
  30. package/dist/chunk-npe2r2ge.js +4 -0
  31. package/dist/{chunk-tm5gk51g.js.map → chunk-npe2r2ge.js.map} +1 -1
  32. package/dist/chunk-p9mwkgye.js +4 -0
  33. package/dist/{chunk-s2akss77.js.map → chunk-p9mwkgye.js.map} +14 -12
  34. package/dist/{chunk-b093ajcq.js → chunk-qjp8j8e5.js} +3 -3
  35. package/dist/{chunk-b093ajcq.js.map → chunk-qjp8j8e5.js.map} +1 -1
  36. package/dist/{chunk-71kfnwdp.js → chunk-r1fk1sx9.js} +3 -3
  37. package/dist/{chunk-71kfnwdp.js.map → chunk-r1fk1sx9.js.map} +1 -1
  38. package/dist/{chunk-5xg0xc0g.js → chunk-ta7bqmy3.js} +3 -3
  39. package/dist/{chunk-5xg0xc0g.js.map → chunk-ta7bqmy3.js.map} +1 -1
  40. package/dist/{chunk-545s1tsc.js → chunk-tgvgr630.js} +3 -3
  41. package/dist/{chunk-545s1tsc.js.map → chunk-tgvgr630.js.map} +2 -2
  42. package/dist/{chunk-035dayv6.js → chunk-v8x9ptxs.js} +3 -3
  43. package/dist/{chunk-035dayv6.js.map → chunk-v8x9ptxs.js.map} +1 -1
  44. package/dist/{chunk-mzan0m09.js → chunk-wm89desc.js} +20 -20
  45. package/dist/{chunk-mzan0m09.js.map → chunk-wm89desc.js.map} +12 -10
  46. package/dist/{chunk-a6vcbcyd.js → chunk-wtyhjt5e.js} +3 -3
  47. package/dist/{chunk-a6vcbcyd.js.map → chunk-wtyhjt5e.js.map} +1 -1
  48. package/dist/{chunk-s5a5v0m1.js → chunk-xskdbz15.js} +3 -3
  49. package/dist/{chunk-s5a5v0m1.js.map → chunk-xskdbz15.js.map} +2 -2
  50. package/dist/{chunk-sbebfr50.js → chunk-ytjqb1sd.js} +3 -3
  51. package/dist/{chunk-sbebfr50.js.map → chunk-ytjqb1sd.js.map} +1 -1
  52. package/dist/{chunk-ys51wj1c.js → chunk-zbesf7sy.js} +3 -3
  53. package/dist/{chunk-ys51wj1c.js.map → chunk-zbesf7sy.js.map} +1 -1
  54. package/dist/keepkey/index.js +2 -2
  55. package/dist/keepkey/index.js.map +1 -1
  56. package/dist/ledger/index.cjs +28 -28
  57. package/dist/ledger/index.cjs.map +28 -24
  58. package/dist/ledger/index.js +2 -2
  59. package/dist/ledger/index.js.map +4 -4
  60. package/dist/trezor/index.cjs +2 -2
  61. package/dist/trezor/index.cjs.map +5 -4
  62. package/dist/trezor/index.js +2 -2
  63. package/dist/trezor/index.js.map +3 -3
  64. package/dist/types/ledger/clients/zcash.d.ts.map +1 -1
  65. package/dist/types/trezor/hypercoreSigner.d.ts +22 -0
  66. package/dist/types/trezor/hypercoreSigner.d.ts.map +1 -0
  67. package/dist/types/trezor/index.d.ts +2 -2
  68. package/dist/types/trezor/index.d.ts.map +1 -1
  69. package/package.json +12 -12
  70. package/src/ledger/clients/zcash.ts +16 -6
  71. package/src/ledger/index.ts +2 -2
  72. package/src/trezor/hypercoreSigner.ts +96 -0
  73. package/src/trezor/index.ts +72 -16
  74. package/dist/chunk-42xrtarj.js +0 -4
  75. package/dist/chunk-s2akss77.js +0 -4
  76. package/dist/chunk-sp3dq5hr.js +0 -4
  77. package/dist/chunk-tm5gk51g.js +0 -4
@@ -1,4 +1,4 @@
1
- import{Xd as k1,Zd as v}from"./chunk-kaw35ae2.js";var O6=v(()=>{/*! *****************************************************************************
1
+ import{$d as u,Zd as k1}from"./chunk-9a9gn4pb.js";var O6=u(()=>{/*! *****************************************************************************
2
2
  Copyright (C) Microsoft. All rights reserved.
3
3
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4
4
  this file except in compliance with the License. You may obtain a copy of the
@@ -11,26 +11,26 @@ MERCHANTABLITY OR NON-INFRINGEMENT.
11
11
 
12
12
  See the Apache Version 2.0 License for specific language governing permissions
13
13
  and limitations under the License.
14
- ***************************************************************************** */var t5;(function(q){(function(J){var Z=typeof globalThis==="object"?globalThis:typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:z(),Q=$(q);if(typeof Z.Reflect<"u")Q=$(Z.Reflect,Q);if(J(Q,Z),typeof Z.Reflect>"u")Z.Reflect=q;function $(X,w){return function(F,_){if(Object.defineProperty(X,F,{configurable:!0,writable:!0,value:_}),w)w(F,_)}}function W(){try{return Function("return this;")()}catch(X){}}function Y(){try{return(0,eval)("(function() { return this; })()")}catch(X){}}function z(){return W()||Y()}})(function(J,Z){var Q=Object.prototype.hasOwnProperty,$=typeof Symbol==="function",W=$&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",Y=$&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",z=typeof Object.create==="function",X={__proto__:[]}instanceof Array,w=!z&&!X,F={create:z?function(){return f9(Object.create(null))}:X?function(){return f9({__proto__:null})}:function(){return f9({})},has:w?function(H,V){return Q.call(H,V)}:function(H,V){return V in H},get:w?function(H,V){return Q.call(H,V)?H[V]:void 0}:function(H,V){return H[V]}},_=Object.getPrototypeOf(Function),G=typeof Map==="function"&&typeof Map.prototype.entries==="function"?Map:AY(),B=typeof Set==="function"&&typeof Set.prototype.entries==="function"?Set:RY(),A=typeof WeakMap==="function"?WeakMap:PY(),f=$?Symbol.for("@reflect-metadata:registry"):void 0,e=jY(),p0=IY(e);function R0(H,V,D,U){if(!h(D)){if(!c5(H))throw TypeError();if(!G0(V))throw TypeError();if(!G0(U)&&!h(U)&&!Qq(U))throw TypeError();if(Qq(U))U=void 0;return D=$1(D),GY(H,V,D,U)}else{if(!c5(H))throw TypeError();if(!p5(V))throw TypeError();return HY(H,V)}}J("decorate",R0);function C9(H,V){function D(U,b){if(!G0(U))throw TypeError();if(!h(b)&&!UY(b))throw TypeError();u5(H,V,U,b)}return D}J("metadata",C9);function $Y(H,V,D,U){if(!G0(D))throw TypeError();if(!h(U))U=$1(U);return u5(H,V,D,U)}J("defineMetadata",$Y);function WY(H,V,D){if(!G0(V))throw TypeError();if(!h(D))D=$1(D);return h5(H,V,D)}J("hasMetadata",WY);function YY(H,V,D){if(!G0(V))throw TypeError();if(!h(D))D=$1(D);return b9(H,V,D)}J("hasOwnMetadata",YY);function zY(H,V,D){if(!G0(V))throw TypeError();if(!h(D))D=$1(D);return v5(H,V,D)}J("getMetadata",zY);function wY(H,V,D){if(!G0(V))throw TypeError();if(!h(D))D=$1(D);return y5(H,V,D)}J("getOwnMetadata",wY);function XY(H,V){if(!G0(H))throw TypeError();if(!h(V))V=$1(V);return g5(H,V)}J("getMetadataKeys",XY);function FY(H,V){if(!G0(H))throw TypeError();if(!h(V))V=$1(V);return m5(H,V)}J("getOwnMetadataKeys",FY);function _Y(H,V,D){if(!G0(V))throw TypeError();if(!h(D))D=$1(D);if(!G0(V))throw TypeError();if(!h(D))D=$1(D);var U=gq(V,D,!1);if(h(U))return!1;return U.OrdinaryDeleteMetadata(H,V,D)}J("deleteMetadata",_Y);function HY(H,V){for(var D=H.length-1;D>=0;--D){var U=H[D],b=U(V);if(!h(b)&&!Qq(b)){if(!p5(b))throw TypeError();V=b}}return V}function GY(H,V,D,U){for(var b=H.length-1;b>=0;--b){var N0=H[b],P0=N0(V,D,U);if(!h(P0)&&!Qq(P0)){if(!G0(P0))throw TypeError();U=P0}}return U}function h5(H,V,D){var U=b9(H,V,D);if(U)return!0;var b=M9(V);if(!Qq(b))return h5(H,b,D);return!1}function b9(H,V,D){var U=gq(V,D,!1);if(h(U))return!1;return d5(U.OrdinaryHasOwnMetadata(H,V,D))}function v5(H,V,D){var U=b9(H,V,D);if(U)return y5(H,V,D);var b=M9(V);if(!Qq(b))return v5(H,b,D);return}function y5(H,V,D){var U=gq(V,D,!1);if(h(U))return;return U.OrdinaryGetOwnMetadata(H,V,D)}function u5(H,V,D,U){var b=gq(D,U,!0);b.OrdinaryDefineOwnMetadata(H,V,D,U)}function g5(H,V){var D=m5(H,V),U=M9(H);if(U===null)return D;var b=g5(U,V);if(b.length<=0)return D;if(D.length<=0)return b;var N0=new B,P0=[];for(var c=0,L=D;c<L.length;c++){var x=L[c],O=N0.has(x);if(!O)N0.add(x),P0.push(x)}for(var C=0,s=b;C<s.length;C++){var x=s[C],O=N0.has(x);if(!O)N0.add(x),P0.push(x)}return P0}function m5(H,V){var D=gq(H,V,!1);if(!D)return[];return D.OrdinaryOwnMetadataKeys(H,V)}function l5(H){if(H===null)return 1;switch(typeof H){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return H===null?1:6;default:return 6}}function h(H){return H===void 0}function Qq(H){return H===null}function NY(H){return typeof H==="symbol"}function G0(H){return typeof H==="object"?H!==null:typeof H==="function"}function VY(H,V){switch(l5(H)){case 0:return H;case 1:return H;case 2:return H;case 3:return H;case 4:return H;case 5:return H}var D=V===3?"string":V===5?"number":"default",U=s5(H,W);if(U!==void 0){var b=U.call(H,D);if(G0(b))throw TypeError();return b}return BY(H,D==="default"?"number":D)}function BY(H,V){if(V==="string"){var D=H.toString;if($q(D)){var U=D.call(H);if(!G0(U))return U}var b=H.valueOf;if($q(b)){var U=b.call(H);if(!G0(U))return U}}else{var b=H.valueOf;if($q(b)){var U=b.call(H);if(!G0(U))return U}var N0=H.toString;if($q(N0)){var U=N0.call(H);if(!G0(U))return U}}throw TypeError()}function d5(H){return!!H}function DY(H){return""+H}function $1(H){var V=VY(H,3);if(NY(V))return V;return DY(V)}function c5(H){return Array.isArray?Array.isArray(H):H instanceof Object?H instanceof Array:Object.prototype.toString.call(H)==="[object Array]"}function $q(H){return typeof H==="function"}function p5(H){return typeof H==="function"}function UY(H){switch(l5(H)){case 3:return!0;case 4:return!0;default:return!1}}function T9(H,V){return H===V||H!==H&&V!==V}function s5(H,V){var D=H[V];if(D===void 0||D===null)return;if(!$q(D))throw TypeError();return D}function n5(H){var V=s5(H,Y);if(!$q(V))throw TypeError();var D=V.call(H);if(!G0(D))throw TypeError();return D}function i5(H){return H.value}function a5(H){var V=H.next();return V.done?!1:V}function o5(H){var V=H.return;if(V)V.call(H)}function M9(H){var V=Object.getPrototypeOf(H);if(typeof H!=="function"||H===_)return V;if(V!==_)return V;var D=H.prototype,U=D&&Object.getPrototypeOf(D);if(U==null||U===Object.prototype)return V;var b=U.constructor;if(typeof b!=="function")return V;if(b===H)return V;return b}function KY(){var H;if(!h(f)&&typeof Z.Reflect<"u"&&!(f in Z.Reflect)&&typeof Z.Reflect.defineMetadata==="function")H=LY(Z.Reflect);var V,D,U,b=new A,N0={registerProvider:P0,getProvider:L,setProvider:O};return N0;function P0(C){if(!Object.isExtensible(N0))throw Error("Cannot add provider to a frozen registry.");switch(!0){case H===C:break;case h(V):V=C;break;case V===C:break;case h(D):D=C;break;case D===C:break;default:if(U===void 0)U=new B;U.add(C);break}}function c(C,s){if(!h(V)){if(V.isProviderFor(C,s))return V;if(!h(D)){if(D.isProviderFor(C,s))return V;if(!h(U)){var Q0=n5(U);while(!0){var V0=a5(Q0);if(!V0)return;var q1=i5(V0);if(q1.isProviderFor(C,s))return o5(Q0),q1}}}}if(!h(H)&&H.isProviderFor(C,s))return H;return}function L(C,s){var Q0=b.get(C),V0;if(!h(Q0))V0=Q0.get(s);if(!h(V0))return V0;if(V0=c(C,s),!h(V0)){if(h(Q0))Q0=new G,b.set(C,Q0);Q0.set(s,V0)}return V0}function x(C){if(h(C))throw TypeError();return V===C||D===C||!h(U)&&U.has(C)}function O(C,s,Q0){if(!x(Q0))throw Error("Metadata provider not registered.");var V0=L(C,s);if(V0!==Q0){if(!h(V0))return!1;var q1=b.get(C);if(h(q1))q1=new G,b.set(C,q1);q1.set(s,Q0)}return!0}}function jY(){var H;if(!h(f)&&G0(Z.Reflect)&&Object.isExtensible(Z.Reflect))H=Z.Reflect[f];if(h(H))H=KY();if(!h(f)&&G0(Z.Reflect)&&Object.isExtensible(Z.Reflect))Object.defineProperty(Z.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:H});return H}function IY(H){var V=new A,D={isProviderFor:function(x,O){var C=V.get(x);if(h(C))return!1;return C.has(O)},OrdinaryDefineOwnMetadata:P0,OrdinaryHasOwnMetadata:b,OrdinaryGetOwnMetadata:N0,OrdinaryOwnMetadataKeys:c,OrdinaryDeleteMetadata:L};return e.registerProvider(D),D;function U(x,O,C){var s=V.get(x),Q0=!1;if(h(s)){if(!C)return;s=new G,V.set(x,s),Q0=!0}var V0=s.get(O);if(h(V0)){if(!C)return;if(V0=new G,s.set(O,V0),!H.setProvider(x,O,D)){if(s.delete(O),Q0)V.delete(x);throw Error("Wrong provider for target.")}}return V0}function b(x,O,C){var s=U(O,C,!1);if(h(s))return!1;return d5(s.has(x))}function N0(x,O,C){var s=U(O,C,!1);if(h(s))return;return s.get(x)}function P0(x,O,C,s){var Q0=U(C,s,!0);Q0.set(x,O)}function c(x,O){var C=[],s=U(x,O,!1);if(h(s))return C;var Q0=s.keys(),V0=n5(Q0),q1=0;while(!0){var r5=a5(V0);if(!r5)return C.length=q1,C;var EY=i5(r5);try{C[q1]=EY}catch(xY){try{o5(V0)}finally{throw xY}}q1++}}function L(x,O,C){var s=U(O,C,!1);if(h(s))return!1;if(!s.delete(x))return!1;if(s.size===0){var Q0=V.get(O);if(!h(Q0)){if(Q0.delete(C),Q0.size===0)V.delete(Q0)}}return!0}}function LY(H){var{defineMetadata:V,hasOwnMetadata:D,getOwnMetadata:U,getOwnMetadataKeys:b,deleteMetadata:N0}=H,P0=new A,c={isProviderFor:function(L,x){var O=P0.get(L);if(!h(O)&&O.has(x))return!0;if(b(L,x).length){if(h(O))O=new B,P0.set(L,O);return O.add(x),!0}return!1},OrdinaryDefineOwnMetadata:V,OrdinaryHasOwnMetadata:D,OrdinaryGetOwnMetadata:U,OrdinaryOwnMetadataKeys:b,OrdinaryDeleteMetadata:N0};return c}function gq(H,V,D){var U=e.getProvider(H,V);if(!h(U))return U;if(D){if(e.setProvider(H,V,p0))return p0;throw Error("Illegal state.")}return}function AY(){var H={},V=[],D=function(){function c(L,x,O){this._index=0,this._keys=L,this._values=x,this._selector=O}return c.prototype["@@iterator"]=function(){return this},c.prototype[Y]=function(){return this},c.prototype.next=function(){var L=this._index;if(L>=0&&L<this._keys.length){var x=this._selector(this._keys[L],this._values[L]);if(L+1>=this._keys.length)this._index=-1,this._keys=V,this._values=V;else this._index++;return{value:x,done:!1}}return{value:void 0,done:!0}},c.prototype.throw=function(L){if(this._index>=0)this._index=-1,this._keys=V,this._values=V;throw L},c.prototype.return=function(L){if(this._index>=0)this._index=-1,this._keys=V,this._values=V;return{value:L,done:!0}},c}(),U=function(){function c(){this._keys=[],this._values=[],this._cacheKey=H,this._cacheIndex=-2}return Object.defineProperty(c.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),c.prototype.has=function(L){return this._find(L,!1)>=0},c.prototype.get=function(L){var x=this._find(L,!1);return x>=0?this._values[x]:void 0},c.prototype.set=function(L,x){var O=this._find(L,!0);return this._values[O]=x,this},c.prototype.delete=function(L){var x=this._find(L,!1);if(x>=0){var O=this._keys.length;for(var C=x+1;C<O;C++)this._keys[C-1]=this._keys[C],this._values[C-1]=this._values[C];if(this._keys.length--,this._values.length--,T9(L,this._cacheKey))this._cacheKey=H,this._cacheIndex=-2;return!0}return!1},c.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=H,this._cacheIndex=-2},c.prototype.keys=function(){return new D(this._keys,this._values,b)},c.prototype.values=function(){return new D(this._keys,this._values,N0)},c.prototype.entries=function(){return new D(this._keys,this._values,P0)},c.prototype["@@iterator"]=function(){return this.entries()},c.prototype[Y]=function(){return this.entries()},c.prototype._find=function(L,x){if(!T9(this._cacheKey,L)){this._cacheIndex=-1;for(var O=0;O<this._keys.length;O++)if(T9(this._keys[O],L)){this._cacheIndex=O;break}}if(this._cacheIndex<0&&x)this._cacheIndex=this._keys.length,this._keys.push(L),this._values.push(void 0);return this._cacheIndex},c}();return U;function b(c,L){return c}function N0(c,L){return L}function P0(c,L){return[c,L]}}function RY(){var H=function(){function V(){this._map=new G}return Object.defineProperty(V.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),V.prototype.has=function(D){return this._map.has(D)},V.prototype.add=function(D){return this._map.set(D,D),this},V.prototype.delete=function(D){return this._map.delete(D)},V.prototype.clear=function(){this._map.clear()},V.prototype.keys=function(){return this._map.keys()},V.prototype.values=function(){return this._map.keys()},V.prototype.entries=function(){return this._map.entries()},V.prototype["@@iterator"]=function(){return this.keys()},V.prototype[Y]=function(){return this.keys()},V}();return H}function PY(){var H=16,V=F.create(),D=U();return function(){function L(){this._key=U()}return L.prototype.has=function(x){var O=b(x,!1);return O!==void 0?F.has(O,this._key):!1},L.prototype.get=function(x){var O=b(x,!1);return O!==void 0?F.get(O,this._key):void 0},L.prototype.set=function(x,O){var C=b(x,!0);return C[this._key]=O,this},L.prototype.delete=function(x){var O=b(x,!1);return O!==void 0?delete O[this._key]:!1},L.prototype.clear=function(){this._key=U()},L}();function U(){var L;do L="@@WeakMap@@"+c();while(F.has(V,L));return V[L]=!0,L}function b(L,x){if(!Q.call(L,D)){if(!x)return;Object.defineProperty(L,D,{value:F.create()})}return L[D]}function N0(L,x){for(var O=0;O<x;++O)L[O]=Math.random()*255|0;return L}function P0(L){if(typeof Uint8Array==="function"){var x=new Uint8Array(L);if(typeof crypto<"u")crypto.getRandomValues(x);else if(typeof msCrypto<"u")msCrypto.getRandomValues(x);else N0(x,L);return x}return N0(Array(L),L)}function c(){var L=P0(H);L[6]=L[6]&79|64,L[8]=L[8]&191|128;var x="";for(var O=0;O<H;++O){var C=L[O];if(O===4||O===6||O===8)x+="-";if(C<16)x+="0";x+=C.toString(16).toLowerCase()}return x}}function f9(H){return H.__=void 0,delete H.__,H}})})(t5||(t5={}))});var dq=v((pH,QZ)=>{var fY=Number.MAX_SAFE_INTEGER||9007199254740991,SY=["major","premajor","minor","preminor","patch","prepatch","prerelease"];QZ.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:fY,RELEASE_TYPES:SY,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var cq=v((sH,$Z)=>{var hY=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...q)=>console.error("SEMVER",...q):()=>{};$Z.exports=hY});var Xq=v((W1,WZ)=>{var{MAX_SAFE_COMPONENT_LENGTH:u9,MAX_SAFE_BUILD_LENGTH:vY,MAX_LENGTH:yY}=dq(),uY=cq();W1=WZ.exports={};var gY=W1.re=[],mY=W1.safeRe=[],P=W1.src=[],lY=W1.safeSrc=[],E=W1.t={},dY=0,g9="[a-zA-Z0-9-]",cY=[["\\s",1],["\\d",yY],[g9,vY]],pY=(q)=>{for(let[J,Z]of cY)q=q.split(`${J}*`).join(`${J}{0,${Z}}`).split(`${J}+`).join(`${J}{1,${Z}}`);return q},g=(q,J,Z)=>{let Q=pY(J),$=dY++;uY(q,$,J),E[q]=$,P[$]=J,lY[$]=Q,gY[$]=new RegExp(J,Z?"g":void 0),mY[$]=new RegExp(Q,Z?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*");g("NUMERICIDENTIFIERLOOSE","\\d+");g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${g9}*`);g("MAINVERSION",`(${P[E.NUMERICIDENTIFIER]})\\.(${P[E.NUMERICIDENTIFIER]})\\.(${P[E.NUMERICIDENTIFIER]})`);g("MAINVERSIONLOOSE",`(${P[E.NUMERICIDENTIFIERLOOSE]})\\.(${P[E.NUMERICIDENTIFIERLOOSE]})\\.(${P[E.NUMERICIDENTIFIERLOOSE]})`);g("PRERELEASEIDENTIFIER",`(?:${P[E.NONNUMERICIDENTIFIER]}|${P[E.NUMERICIDENTIFIER]})`);g("PRERELEASEIDENTIFIERLOOSE",`(?:${P[E.NONNUMERICIDENTIFIER]}|${P[E.NUMERICIDENTIFIERLOOSE]})`);g("PRERELEASE",`(?:-(${P[E.PRERELEASEIDENTIFIER]}(?:\\.${P[E.PRERELEASEIDENTIFIER]})*))`);g("PRERELEASELOOSE",`(?:-?(${P[E.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${P[E.PRERELEASEIDENTIFIERLOOSE]})*))`);g("BUILDIDENTIFIER",`${g9}+`);g("BUILD",`(?:\\+(${P[E.BUILDIDENTIFIER]}(?:\\.${P[E.BUILDIDENTIFIER]})*))`);g("FULLPLAIN",`v?${P[E.MAINVERSION]}${P[E.PRERELEASE]}?${P[E.BUILD]}?`);g("FULL",`^${P[E.FULLPLAIN]}$`);g("LOOSEPLAIN",`[v=\\s]*${P[E.MAINVERSIONLOOSE]}${P[E.PRERELEASELOOSE]}?${P[E.BUILD]}?`);g("LOOSE",`^${P[E.LOOSEPLAIN]}$`);g("GTLT","((?:<|>)?=?)");g("XRANGEIDENTIFIERLOOSE",`${P[E.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);g("XRANGEIDENTIFIER",`${P[E.NUMERICIDENTIFIER]}|x|X|\\*`);g("XRANGEPLAIN",`[v=\\s]*(${P[E.XRANGEIDENTIFIER]})(?:\\.(${P[E.XRANGEIDENTIFIER]})(?:\\.(${P[E.XRANGEIDENTIFIER]})(?:${P[E.PRERELEASE]})?${P[E.BUILD]}?)?)?`);g("XRANGEPLAINLOOSE",`[v=\\s]*(${P[E.XRANGEIDENTIFIERLOOSE]})(?:\\.(${P[E.XRANGEIDENTIFIERLOOSE]})(?:\\.(${P[E.XRANGEIDENTIFIERLOOSE]})(?:${P[E.PRERELEASELOOSE]})?${P[E.BUILD]}?)?)?`);g("XRANGE",`^${P[E.GTLT]}\\s*${P[E.XRANGEPLAIN]}$`);g("XRANGELOOSE",`^${P[E.GTLT]}\\s*${P[E.XRANGEPLAINLOOSE]}$`);g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${u9}})(?:\\.(\\d{1,${u9}}))?(?:\\.(\\d{1,${u9}}))?`);g("COERCE",`${P[E.COERCEPLAIN]}(?:$|[^\\d])`);g("COERCEFULL",P[E.COERCEPLAIN]+`(?:${P[E.PRERELEASE]})?(?:${P[E.BUILD]})?(?:$|[^\\d])`);g("COERCERTL",P[E.COERCE],!0);g("COERCERTLFULL",P[E.COERCEFULL],!0);g("LONETILDE","(?:~>?)");g("TILDETRIM",`(\\s*)${P[E.LONETILDE]}\\s+`,!0);W1.tildeTrimReplace="$1~";g("TILDE",`^${P[E.LONETILDE]}${P[E.XRANGEPLAIN]}$`);g("TILDELOOSE",`^${P[E.LONETILDE]}${P[E.XRANGEPLAINLOOSE]}$`);g("LONECARET","(?:\\^)");g("CARETTRIM",`(\\s*)${P[E.LONECARET]}\\s+`,!0);W1.caretTrimReplace="$1^";g("CARET",`^${P[E.LONECARET]}${P[E.XRANGEPLAIN]}$`);g("CARETLOOSE",`^${P[E.LONECARET]}${P[E.XRANGEPLAINLOOSE]}$`);g("COMPARATORLOOSE",`^${P[E.GTLT]}\\s*(${P[E.LOOSEPLAIN]})$|^$`);g("COMPARATOR",`^${P[E.GTLT]}\\s*(${P[E.FULLPLAIN]})$|^$`);g("COMPARATORTRIM",`(\\s*)${P[E.GTLT]}\\s*(${P[E.LOOSEPLAIN]}|${P[E.XRANGEPLAIN]})`,!0);W1.comparatorTrimReplace="$1$2$3";g("HYPHENRANGE",`^\\s*(${P[E.XRANGEPLAIN]})\\s+-\\s+(${P[E.XRANGEPLAIN]})\\s*$`);g("HYPHENRANGELOOSE",`^\\s*(${P[E.XRANGEPLAINLOOSE]})\\s+-\\s+(${P[E.XRANGEPLAINLOOSE]})\\s*$`);g("STAR","(<|>)?=?\\s*\\*");g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var v6=v((nH,YZ)=>{var sY=Object.freeze({loose:!0}),nY=Object.freeze({}),iY=(q)=>{if(!q)return nY;if(typeof q!=="object")return sY;return q};YZ.exports=iY});var m9=v((iH,XZ)=>{var zZ=/^[0-9]+$/,wZ=(q,J)=>{let Z=zZ.test(q),Q=zZ.test(J);if(Z&&Q)q=+q,J=+J;return q===J?0:Z&&!Q?-1:Q&&!Z?1:q<J?-1:1},aY=(q,J)=>wZ(J,q);XZ.exports={compareIdentifiers:wZ,rcompareIdentifiers:aY}});var b0=v((aH,_Z)=>{var y6=cq(),{MAX_LENGTH:FZ,MAX_SAFE_INTEGER:u6}=dq(),{safeRe:g6,t:m6}=Xq(),oY=v6(),{compareIdentifiers:Fq}=m9();class J1{constructor(q,J){if(J=oY(J),q instanceof J1)if(q.loose===!!J.loose&&q.includePrerelease===!!J.includePrerelease)return q;else q=q.version;else if(typeof q!=="string")throw TypeError(`Invalid version. Must be a string. Got type "${typeof q}".`);if(q.length>FZ)throw TypeError(`version is longer than ${FZ} characters`);y6("SemVer",q,J),this.options=J,this.loose=!!J.loose,this.includePrerelease=!!J.includePrerelease;let Z=q.trim().match(J.loose?g6[m6.LOOSE]:g6[m6.FULL]);if(!Z)throw TypeError(`Invalid Version: ${q}`);if(this.raw=q,this.major=+Z[1],this.minor=+Z[2],this.patch=+Z[3],this.major>u6||this.major<0)throw TypeError("Invalid major version");if(this.minor>u6||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>u6||this.patch<0)throw TypeError("Invalid patch version");if(!Z[4])this.prerelease=[];else this.prerelease=Z[4].split(".").map((Q)=>{if(/^[0-9]+$/.test(Q)){let $=+Q;if($>=0&&$<u6)return $}return Q});this.build=Z[5]?Z[5].split("."):[],this.format()}format(){if(this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length)this.version+=`-${this.prerelease.join(".")}`;return this.version}toString(){return this.version}compare(q){if(y6("SemVer.compare",this.version,this.options,q),!(q instanceof J1)){if(typeof q==="string"&&q===this.version)return 0;q=new J1(q,this.options)}if(q.version===this.version)return 0;return this.compareMain(q)||this.comparePre(q)}compareMain(q){if(!(q instanceof J1))q=new J1(q,this.options);return Fq(this.major,q.major)||Fq(this.minor,q.minor)||Fq(this.patch,q.patch)}comparePre(q){if(!(q instanceof J1))q=new J1(q,this.options);if(this.prerelease.length&&!q.prerelease.length)return-1;else if(!this.prerelease.length&&q.prerelease.length)return 1;else if(!this.prerelease.length&&!q.prerelease.length)return 0;let J=0;do{let Z=this.prerelease[J],Q=q.prerelease[J];if(y6("prerelease compare",J,Z,Q),Z===void 0&&Q===void 0)return 0;else if(Q===void 0)return 1;else if(Z===void 0)return-1;else if(Z===Q)continue;else return Fq(Z,Q)}while(++J)}compareBuild(q){if(!(q instanceof J1))q=new J1(q,this.options);let J=0;do{let Z=this.build[J],Q=q.build[J];if(y6("build compare",J,Z,Q),Z===void 0&&Q===void 0)return 0;else if(Q===void 0)return 1;else if(Z===void 0)return-1;else if(Z===Q)continue;else return Fq(Z,Q)}while(++J)}inc(q,J,Z){if(q.startsWith("pre")){if(!J&&Z===!1)throw Error("invalid increment argument: identifier is empty");if(J){let Q=`-${J}`.match(this.options.loose?g6[m6.PRERELEASELOOSE]:g6[m6.PRERELEASE]);if(!Q||Q[1]!==J)throw Error(`invalid identifier: ${J}`)}}switch(q){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",J,Z);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",J,Z);break;case"prepatch":this.prerelease.length=0,this.inc("patch",J,Z),this.inc("pre",J,Z);break;case"prerelease":if(this.prerelease.length===0)this.inc("patch",J,Z);this.inc("pre",J,Z);break;case"release":if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0)this.major++;this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0)this.minor++;this.patch=0,this.prerelease=[];break;case"patch":if(this.prerelease.length===0)this.patch++;this.prerelease=[];break;case"pre":{let Q=Number(Z)?1:0;if(this.prerelease.length===0)this.prerelease=[Q];else{let $=this.prerelease.length;while(--$>=0)if(typeof this.prerelease[$]==="number")this.prerelease[$]++,$=-2;if($===-1){if(J===this.prerelease.join(".")&&Z===!1)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(Q)}}if(J){let $=[J,Q];if(Z===!1)$=[J];if(Fq(this.prerelease[0],J)===0){if(isNaN(this.prerelease[1]))this.prerelease=$}else this.prerelease=$}break}default:throw Error(`invalid increment argument: ${q}`)}if(this.raw=this.format(),this.build.length)this.raw+=`+${this.build.join(".")}`;return this}}_Z.exports=J1});var l1=v((oH,GZ)=>{var HZ=b0(),rY=(q,J,Z=!1)=>{if(q instanceof HZ)return q;try{return new HZ(q,J)}catch(Q){if(!Z)return null;throw Q}};GZ.exports=rY});var VZ=v((rH,NZ)=>{var tY=l1(),eY=(q,J)=>{let Z=tY(q,J);return Z?Z.version:null};NZ.exports=eY});var DZ=v((tH,BZ)=>{var q4=l1(),J4=(q,J)=>{let Z=q4(q.trim().replace(/^[=v]+/,""),J);return Z?Z.version:null};BZ.exports=J4});var jZ=v((eH,KZ)=>{var UZ=b0(),Z4=(q,J,Z,Q,$)=>{if(typeof Z==="string")$=Q,Q=Z,Z=void 0;try{return new UZ(q instanceof UZ?q.version:q,Z).inc(J,Q,$).version}catch(W){return null}};KZ.exports=Z4});var AZ=v((qG,LZ)=>{var IZ=l1(),Q4=(q,J)=>{let Z=IZ(q,null,!0),Q=IZ(J,null,!0),$=Z.compare(Q);if($===0)return null;let W=$>0,Y=W?Z:Q,z=W?Q:Z,X=!!Y.prerelease.length;if(!!z.prerelease.length&&!X){if(!z.patch&&!z.minor)return"major";if(z.compareMain(Y)===0){if(z.minor&&!z.patch)return"minor";return"patch"}}let F=X?"pre":"";if(Z.major!==Q.major)return F+"major";if(Z.minor!==Q.minor)return F+"minor";if(Z.patch!==Q.patch)return F+"patch";return"prerelease"};LZ.exports=Q4});var PZ=v((JG,RZ)=>{var $4=b0(),W4=(q,J)=>new $4(q,J).major;RZ.exports=W4});var xZ=v((ZG,EZ)=>{var Y4=b0(),z4=(q,J)=>new Y4(q,J).minor;EZ.exports=z4});var OZ=v((QG,kZ)=>{var w4=b0(),X4=(q,J)=>new w4(q,J).patch;kZ.exports=X4});var bZ=v(($G,CZ)=>{var F4=l1(),_4=(q,J)=>{let Z=F4(q,J);return Z&&Z.prerelease.length?Z.prerelease:null};CZ.exports=_4});var a0=v((WG,MZ)=>{var TZ=b0(),H4=(q,J,Z)=>new TZ(q,Z).compare(new TZ(J,Z));MZ.exports=H4});var SZ=v((YG,fZ)=>{var G4=a0(),N4=(q,J,Z)=>G4(J,q,Z);fZ.exports=N4});var vZ=v((zG,hZ)=>{var V4=a0(),B4=(q,J)=>V4(q,J,!0);hZ.exports=B4});var l6=v((wG,uZ)=>{var yZ=b0(),D4=(q,J,Z)=>{let Q=new yZ(q,Z),$=new yZ(J,Z);return Q.compare($)||Q.compareBuild($)};uZ.exports=D4});var mZ=v((XG,gZ)=>{var U4=l6(),K4=(q,J)=>q.sort((Z,Q)=>U4(Z,Q,J));gZ.exports=K4});var dZ=v((FG,lZ)=>{var j4=l6(),I4=(q,J)=>q.sort((Z,Q)=>j4(Q,Z,J));lZ.exports=I4});var pq=v((_G,cZ)=>{var L4=a0(),A4=(q,J,Z)=>L4(q,J,Z)>0;cZ.exports=A4});var d6=v((HG,pZ)=>{var R4=a0(),P4=(q,J,Z)=>R4(q,J,Z)<0;pZ.exports=P4});var l9=v((GG,sZ)=>{var E4=a0(),x4=(q,J,Z)=>E4(q,J,Z)===0;sZ.exports=x4});var d9=v((NG,nZ)=>{var k4=a0(),O4=(q,J,Z)=>k4(q,J,Z)!==0;nZ.exports=O4});var c6=v((VG,iZ)=>{var C4=a0(),b4=(q,J,Z)=>C4(q,J,Z)>=0;iZ.exports=b4});var p6=v((BG,aZ)=>{var T4=a0(),M4=(q,J,Z)=>T4(q,J,Z)<=0;aZ.exports=M4});var c9=v((DG,oZ)=>{var f4=l9(),S4=d9(),h4=pq(),v4=c6(),y4=d6(),u4=p6(),g4=(q,J,Z,Q)=>{switch(J){case"===":if(typeof q==="object")q=q.version;if(typeof Z==="object")Z=Z.version;return q===Z;case"!==":if(typeof q==="object")q=q.version;if(typeof Z==="object")Z=Z.version;return q!==Z;case"":case"=":case"==":return f4(q,Z,Q);case"!=":return S4(q,Z,Q);case">":return h4(q,Z,Q);case">=":return v4(q,Z,Q);case"<":return y4(q,Z,Q);case"<=":return u4(q,Z,Q);default:throw TypeError(`Invalid operator: ${J}`)}};oZ.exports=g4});var tZ=v((UG,rZ)=>{var m4=b0(),l4=l1(),{safeRe:s6,t:n6}=Xq(),d4=(q,J)=>{if(q instanceof m4)return q;if(typeof q==="number")q=String(q);if(typeof q!=="string")return null;J=J||{};let Z=null;if(!J.rtl)Z=q.match(J.includePrerelease?s6[n6.COERCEFULL]:s6[n6.COERCE]);else{let X=J.includePrerelease?s6[n6.COERCERTLFULL]:s6[n6.COERCERTL],w;while((w=X.exec(q))&&(!Z||Z.index+Z[0].length!==q.length)){if(!Z||w.index+w[0].length!==Z.index+Z[0].length)Z=w;X.lastIndex=w.index+w[1].length+w[2].length}X.lastIndex=-1}if(Z===null)return null;let Q=Z[2],$=Z[3]||"0",W=Z[4]||"0",Y=J.includePrerelease&&Z[5]?`-${Z[5]}`:"",z=J.includePrerelease&&Z[6]?`+${Z[6]}`:"";return l4(`${Q}.${$}.${W}${Y}${z}`,J)};rZ.exports=d4});var J7=v((KG,q7)=>{class eZ{constructor(){this.max=1000,this.map=new Map}get(q){let J=this.map.get(q);if(J===void 0)return;else return this.map.delete(q),this.map.set(q,J),J}delete(q){return this.map.delete(q)}set(q,J){if(!this.delete(q)&&J!==void 0){if(this.map.size>=this.max){let Q=this.map.keys().next().value;this.delete(Q)}this.map.set(q,J)}return this}}q7.exports=eZ});var o0=v((jG,W7)=>{var c4=/\s+/g;class sq{constructor(q,J){if(J=s4(J),q instanceof sq)if(q.loose===!!J.loose&&q.includePrerelease===!!J.includePrerelease)return q;else return new sq(q.raw,J);if(q instanceof p9)return this.raw=q.value,this.set=[[q]],this.formatted=void 0,this;if(this.options=J,this.loose=!!J.loose,this.includePrerelease=!!J.includePrerelease,this.raw=q.trim().replace(c4," "),this.set=this.raw.split("||").map((Z)=>this.parseRange(Z.trim())).filter((Z)=>Z.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let Z=this.set[0];if(this.set=this.set.filter((Q)=>!Q7(Q[0])),this.set.length===0)this.set=[Z];else if(this.set.length>1){for(let Q of this.set)if(Q.length===1&&e4(Q[0])){this.set=[Q];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let q=0;q<this.set.length;q++){if(q>0)this.formatted+="||";let J=this.set[q];for(let Z=0;Z<J.length;Z++){if(Z>0)this.formatted+=" ";this.formatted+=J[Z].toString().trim()}}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(q){let Z=((this.options.includePrerelease&&r4)|(this.options.loose&&t4))+":"+q,Q=Z7.get(Z);if(Q)return Q;let $=this.options.loose,W=$?m0[v0.HYPHENRANGELOOSE]:m0[v0.HYPHENRANGE];q=q.replace(W,Xz(this.options.includePrerelease)),$0("hyphen replace",q),q=q.replace(m0[v0.COMPARATORTRIM],i4),$0("comparator trim",q),q=q.replace(m0[v0.TILDETRIM],a4),$0("tilde trim",q),q=q.replace(m0[v0.CARETTRIM],o4),$0("caret trim",q);let Y=q.split(" ").map((F)=>qz(F,this.options)).join(" ").split(/\s+/).map((F)=>wz(F,this.options));if($)Y=Y.filter((F)=>{return $0("loose invalid filter",F,this.options),!!F.match(m0[v0.COMPARATORLOOSE])});$0("range list",Y);let z=new Map,X=Y.map((F)=>new p9(F,this.options));for(let F of X){if(Q7(F))return[F];z.set(F.value,F)}if(z.size>1&&z.has(""))z.delete("");let w=[...z.values()];return Z7.set(Z,w),w}intersects(q,J){if(!(q instanceof sq))throw TypeError("a Range is required");return this.set.some((Z)=>{return $7(Z,J)&&q.set.some((Q)=>{return $7(Q,J)&&Z.every(($)=>{return Q.every((W)=>{return $.intersects(W,J)})})})})}test(q){if(!q)return!1;if(typeof q==="string")try{q=new n4(q,this.options)}catch(J){return!1}for(let J=0;J<this.set.length;J++)if(Fz(this.set[J],q,this.options))return!0;return!1}}W7.exports=sq;var p4=J7(),Z7=new p4,s4=v6(),p9=nq(),$0=cq(),n4=b0(),{safeRe:m0,t:v0,comparatorTrimReplace:i4,tildeTrimReplace:a4,caretTrimReplace:o4}=Xq(),{FLAG_INCLUDE_PRERELEASE:r4,FLAG_LOOSE:t4}=dq(),Q7=(q)=>q.value==="<0.0.0-0",e4=(q)=>q.value==="",$7=(q,J)=>{let Z=!0,Q=q.slice(),$=Q.pop();while(Z&&Q.length)Z=Q.every((W)=>{return $.intersects(W,J)}),$=Q.pop();return Z},qz=(q,J)=>{return $0("comp",q,J),q=Qz(q,J),$0("caret",q),q=Jz(q,J),$0("tildes",q),q=Wz(q,J),$0("xrange",q),q=zz(q,J),$0("stars",q),q},y0=(q)=>!q||q.toLowerCase()==="x"||q==="*",Jz=(q,J)=>{return q.trim().split(/\s+/).map((Z)=>Zz(Z,J)).join(" ")},Zz=(q,J)=>{let Z=J.loose?m0[v0.TILDELOOSE]:m0[v0.TILDE];return q.replace(Z,(Q,$,W,Y,z)=>{$0("tilde",q,Q,$,W,Y,z);let X;if(y0($))X="";else if(y0(W))X=`>=${$}.0.0 <${+$+1}.0.0-0`;else if(y0(Y))X=`>=${$}.${W}.0 <${$}.${+W+1}.0-0`;else if(z)$0("replaceTilde pr",z),X=`>=${$}.${W}.${Y}-${z} <${$}.${+W+1}.0-0`;else X=`>=${$}.${W}.${Y} <${$}.${+W+1}.0-0`;return $0("tilde return",X),X})},Qz=(q,J)=>{return q.trim().split(/\s+/).map((Z)=>$z(Z,J)).join(" ")},$z=(q,J)=>{$0("caret",q,J);let Z=J.loose?m0[v0.CARETLOOSE]:m0[v0.CARET],Q=J.includePrerelease?"-0":"";return q.replace(Z,($,W,Y,z,X)=>{$0("caret",q,$,W,Y,z,X);let w;if(y0(W))w="";else if(y0(Y))w=`>=${W}.0.0${Q} <${+W+1}.0.0-0`;else if(y0(z))if(W==="0")w=`>=${W}.${Y}.0${Q} <${W}.${+Y+1}.0-0`;else w=`>=${W}.${Y}.0${Q} <${+W+1}.0.0-0`;else if(X)if($0("replaceCaret pr",X),W==="0")if(Y==="0")w=`>=${W}.${Y}.${z}-${X} <${W}.${Y}.${+z+1}-0`;else w=`>=${W}.${Y}.${z}-${X} <${W}.${+Y+1}.0-0`;else w=`>=${W}.${Y}.${z}-${X} <${+W+1}.0.0-0`;else if($0("no pr"),W==="0")if(Y==="0")w=`>=${W}.${Y}.${z}${Q} <${W}.${Y}.${+z+1}-0`;else w=`>=${W}.${Y}.${z}${Q} <${W}.${+Y+1}.0-0`;else w=`>=${W}.${Y}.${z} <${+W+1}.0.0-0`;return $0("caret return",w),w})},Wz=(q,J)=>{return $0("replaceXRanges",q,J),q.split(/\s+/).map((Z)=>Yz(Z,J)).join(" ")},Yz=(q,J)=>{q=q.trim();let Z=J.loose?m0[v0.XRANGELOOSE]:m0[v0.XRANGE];return q.replace(Z,(Q,$,W,Y,z,X)=>{$0("xRange",q,Q,$,W,Y,z,X);let w=y0(W),F=w||y0(Y),_=F||y0(z),G=_;if($==="="&&G)$="";if(X=J.includePrerelease?"-0":"",w)if($===">"||$==="<")Q="<0.0.0-0";else Q="*";else if($&&G){if(F)Y=0;if(z=0,$===">")if($=">=",F)W=+W+1,Y=0,z=0;else Y=+Y+1,z=0;else if($==="<=")if($="<",F)W=+W+1;else Y=+Y+1;if($==="<")X="-0";Q=`${$+W}.${Y}.${z}${X}`}else if(F)Q=`>=${W}.0.0${X} <${+W+1}.0.0-0`;else if(_)Q=`>=${W}.${Y}.0${X} <${W}.${+Y+1}.0-0`;return $0("xRange return",Q),Q})},zz=(q,J)=>{return $0("replaceStars",q,J),q.trim().replace(m0[v0.STAR],"")},wz=(q,J)=>{return $0("replaceGTE0",q,J),q.trim().replace(m0[J.includePrerelease?v0.GTE0PRE:v0.GTE0],"")},Xz=(q)=>(J,Z,Q,$,W,Y,z,X,w,F,_,G)=>{if(y0(Q))Z="";else if(y0($))Z=`>=${Q}.0.0${q?"-0":""}`;else if(y0(W))Z=`>=${Q}.${$}.0${q?"-0":""}`;else if(Y)Z=`>=${Z}`;else Z=`>=${Z}${q?"-0":""}`;if(y0(w))X="";else if(y0(F))X=`<${+w+1}.0.0-0`;else if(y0(_))X=`<${w}.${+F+1}.0-0`;else if(G)X=`<=${w}.${F}.${_}-${G}`;else if(q)X=`<${w}.${F}.${+_+1}-0`;else X=`<=${X}`;return`${Z} ${X}`.trim()},Fz=(q,J,Z)=>{for(let Q=0;Q<q.length;Q++)if(!q[Q].test(J))return!1;if(J.prerelease.length&&!Z.includePrerelease){for(let Q=0;Q<q.length;Q++){if($0(q[Q].semver),q[Q].semver===p9.ANY)continue;if(q[Q].semver.prerelease.length>0){let $=q[Q].semver;if($.major===J.major&&$.minor===J.minor&&$.patch===J.patch)return!0}}return!1}return!0}});var nq=v((IG,_7)=>{var iq=Symbol("SemVer ANY");class i6{static get ANY(){return iq}constructor(q,J){if(J=Y7(J),q instanceof i6)if(q.loose===!!J.loose)return q;else q=q.value;if(q=q.trim().split(/\s+/).join(" "),n9("comparator",q,J),this.options=J,this.loose=!!J.loose,this.parse(q),this.semver===iq)this.value="";else this.value=this.operator+this.semver.version;n9("comp",this)}parse(q){let J=this.options.loose?z7[w7.COMPARATORLOOSE]:z7[w7.COMPARATOR],Z=q.match(J);if(!Z)throw TypeError(`Invalid comparator: ${q}`);if(this.operator=Z[1]!==void 0?Z[1]:"",this.operator==="=")this.operator="";if(!Z[2])this.semver=iq;else this.semver=new X7(Z[2],this.options.loose)}toString(){return this.value}test(q){if(n9("Comparator.test",q,this.options.loose),this.semver===iq||q===iq)return!0;if(typeof q==="string")try{q=new X7(q,this.options)}catch(J){return!1}return s9(q,this.operator,this.semver,this.options)}intersects(q,J){if(!(q instanceof i6))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new F7(q.value,J).test(this.value)}else if(q.operator===""){if(q.value==="")return!0;return new F7(this.value,J).test(q.semver)}if(J=Y7(J),J.includePrerelease&&(this.value==="<0.0.0-0"||q.value==="<0.0.0-0"))return!1;if(!J.includePrerelease&&(this.value.startsWith("<0.0.0")||q.value.startsWith("<0.0.0")))return!1;if(this.operator.startsWith(">")&&q.operator.startsWith(">"))return!0;if(this.operator.startsWith("<")&&q.operator.startsWith("<"))return!0;if(this.semver.version===q.semver.version&&this.operator.includes("=")&&q.operator.includes("="))return!0;if(s9(this.semver,"<",q.semver,J)&&this.operator.startsWith(">")&&q.operator.startsWith("<"))return!0;if(s9(this.semver,">",q.semver,J)&&this.operator.startsWith("<")&&q.operator.startsWith(">"))return!0;return!1}}_7.exports=i6;var Y7=v6(),{safeRe:z7,t:w7}=Xq(),s9=c9(),n9=cq(),X7=b0(),F7=o0()});var aq=v((LG,H7)=>{var _z=o0(),Hz=(q,J,Z)=>{try{J=new _z(J,Z)}catch(Q){return!1}return J.test(q)};H7.exports=Hz});var N7=v((AG,G7)=>{var Gz=o0(),Nz=(q,J)=>new Gz(q,J).set.map((Z)=>Z.map((Q)=>Q.value).join(" ").trim().split(" "));G7.exports=Nz});var B7=v((RG,V7)=>{var Vz=b0(),Bz=o0(),Dz=(q,J,Z)=>{let Q=null,$=null,W=null;try{W=new Bz(J,Z)}catch(Y){return null}return q.forEach((Y)=>{if(W.test(Y)){if(!Q||$.compare(Y)===-1)Q=Y,$=new Vz(Q,Z)}}),Q};V7.exports=Dz});var U7=v((PG,D7)=>{var Uz=b0(),Kz=o0(),jz=(q,J,Z)=>{let Q=null,$=null,W=null;try{W=new Kz(J,Z)}catch(Y){return null}return q.forEach((Y)=>{if(W.test(Y)){if(!Q||$.compare(Y)===1)Q=Y,$=new Uz(Q,Z)}}),Q};D7.exports=jz});var I7=v((EG,j7)=>{var i9=b0(),Iz=o0(),K7=pq(),Lz=(q,J)=>{q=new Iz(q,J);let Z=new i9("0.0.0");if(q.test(Z))return Z;if(Z=new i9("0.0.0-0"),q.test(Z))return Z;Z=null;for(let Q=0;Q<q.set.length;++Q){let $=q.set[Q],W=null;if($.forEach((Y)=>{let z=new i9(Y.semver.version);switch(Y.operator){case">":if(z.prerelease.length===0)z.patch++;else z.prerelease.push(0);z.raw=z.format();case"":case">=":if(!W||K7(z,W))W=z;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${Y.operator}`)}}),W&&(!Z||K7(Z,W)))Z=W}if(Z&&q.test(Z))return Z;return null};j7.exports=Lz});var A7=v((xG,L7)=>{var Az=o0(),Rz=(q,J)=>{try{return new Az(q,J).range||"*"}catch(Z){return null}};L7.exports=Rz});var a6=v((kG,x7)=>{var Pz=b0(),E7=nq(),{ANY:Ez}=E7,xz=o0(),kz=aq(),R7=pq(),P7=d6(),Oz=p6(),Cz=c6(),bz=(q,J,Z,Q)=>{q=new Pz(q,Q),J=new xz(J,Q);let $,W,Y,z,X;switch(Z){case">":$=R7,W=Oz,Y=P7,z=">",X=">=";break;case"<":$=P7,W=Cz,Y=R7,z="<",X="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(kz(q,J,Q))return!1;for(let w=0;w<J.set.length;++w){let F=J.set[w],_=null,G=null;if(F.forEach((B)=>{if(B.semver===Ez)B=new E7(">=0.0.0");if(_=_||B,G=G||B,$(B.semver,_.semver,Q))_=B;else if(Y(B.semver,G.semver,Q))G=B}),_.operator===z||_.operator===X)return!1;if((!G.operator||G.operator===z)&&W(q,G.semver))return!1;else if(G.operator===X&&Y(q,G.semver))return!1}return!0};x7.exports=bz});var O7=v((OG,k7)=>{var Tz=a6(),Mz=(q,J,Z)=>Tz(q,J,">",Z);k7.exports=Mz});var b7=v((CG,C7)=>{var fz=a6(),Sz=(q,J,Z)=>fz(q,J,"<",Z);C7.exports=Sz});var f7=v((bG,M7)=>{var T7=o0(),hz=(q,J,Z)=>{return q=new T7(q,Z),J=new T7(J,Z),q.intersects(J,Z)};M7.exports=hz});var h7=v((TG,S7)=>{var vz=aq(),yz=a0();S7.exports=(q,J,Z)=>{let Q=[],$=null,W=null,Y=q.sort((F,_)=>yz(F,_,Z));for(let F of Y)if(vz(F,J,Z)){if(W=F,!$)$=F}else{if(W)Q.push([$,W]);W=null,$=null}if($)Q.push([$,null]);let z=[];for(let[F,_]of Q)if(F===_)z.push(F);else if(!_&&F===Y[0])z.push("*");else if(!_)z.push(`>=${F}`);else if(F===Y[0])z.push(`<=${_}`);else z.push(`${F} - ${_}`);let X=z.join(" || "),w=typeof J.raw==="string"?J.raw:String(J);return X.length<w.length?X:J}});var l7=v((MG,m7)=>{var v7=o0(),o9=nq(),{ANY:a9}=o9,oq=aq(),r9=a0(),uz=(q,J,Z={})=>{if(q===J)return!0;q=new v7(q,Z),J=new v7(J,Z);let Q=!1;q:for(let $ of q.set){for(let W of J.set){let Y=mz($,W,Z);if(Q=Q||Y!==null,Y)continue q}if(Q)return!1}return!0},gz=[new o9(">=0.0.0-0")],y7=[new o9(">=0.0.0")],mz=(q,J,Z)=>{if(q===J)return!0;if(q.length===1&&q[0].semver===a9)if(J.length===1&&J[0].semver===a9)return!0;else if(Z.includePrerelease)q=gz;else q=y7;if(J.length===1&&J[0].semver===a9)if(Z.includePrerelease)return!0;else J=y7;let Q=new Set,$,W;for(let B of q)if(B.operator===">"||B.operator===">=")$=u7($,B,Z);else if(B.operator==="<"||B.operator==="<=")W=g7(W,B,Z);else Q.add(B.semver);if(Q.size>1)return null;let Y;if($&&W){if(Y=r9($.semver,W.semver,Z),Y>0)return null;else if(Y===0&&($.operator!==">="||W.operator!=="<="))return null}for(let B of Q){if($&&!oq(B,String($),Z))return null;if(W&&!oq(B,String(W),Z))return null;for(let A of J)if(!oq(B,String(A),Z))return!1;return!0}let z,X,w,F,_=W&&!Z.includePrerelease&&W.semver.prerelease.length?W.semver:!1,G=$&&!Z.includePrerelease&&$.semver.prerelease.length?$.semver:!1;if(_&&_.prerelease.length===1&&W.operator==="<"&&_.prerelease[0]===0)_=!1;for(let B of J){if(F=F||B.operator===">"||B.operator===">=",w=w||B.operator==="<"||B.operator==="<=",$){if(G){if(B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===G.major&&B.semver.minor===G.minor&&B.semver.patch===G.patch)G=!1}if(B.operator===">"||B.operator===">="){if(z=u7($,B,Z),z===B&&z!==$)return!1}else if($.operator===">="&&!oq($.semver,String(B),Z))return!1}if(W){if(_){if(B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===_.major&&B.semver.minor===_.minor&&B.semver.patch===_.patch)_=!1}if(B.operator==="<"||B.operator==="<="){if(X=g7(W,B,Z),X===B&&X!==W)return!1}else if(W.operator==="<="&&!oq(W.semver,String(B),Z))return!1}if(!B.operator&&(W||$)&&Y!==0)return!1}if($&&w&&!W&&Y!==0)return!1;if(W&&F&&!$&&Y!==0)return!1;if(G||_)return!1;return!0},u7=(q,J,Z)=>{if(!q)return J;let Q=r9(q.semver,J.semver,Z);return Q>0?q:Q<0?J:J.operator===">"&&q.operator===">="?J:q},g7=(q,J,Z)=>{if(!q)return J;let Q=r9(q.semver,J.semver,Z);return Q<0?q:Q>0?J:J.operator==="<"&&q.operator==="<="?J:q};m7.exports=uz});var _q=v((fG,p7)=>{var t9=Xq(),d7=dq(),lz=b0(),c7=m9(),dz=l1(),cz=VZ(),pz=DZ(),sz=jZ(),nz=AZ(),iz=PZ(),az=xZ(),oz=OZ(),rz=bZ(),tz=a0(),ez=SZ(),q3=vZ(),J3=l6(),Z3=mZ(),Q3=dZ(),$3=pq(),W3=d6(),Y3=l9(),z3=d9(),w3=c6(),X3=p6(),F3=c9(),_3=tZ(),H3=nq(),G3=o0(),N3=aq(),V3=N7(),B3=B7(),D3=U7(),U3=I7(),K3=A7(),j3=a6(),I3=O7(),L3=b7(),A3=f7(),R3=h7(),P3=l7();p7.exports={parse:dz,valid:cz,clean:pz,inc:sz,diff:nz,major:iz,minor:az,patch:oz,prerelease:rz,compare:tz,rcompare:ez,compareLoose:q3,compareBuild:J3,sort:Z3,rsort:Q3,gt:$3,lt:W3,eq:Y3,neq:z3,gte:w3,lte:X3,cmp:F3,coerce:_3,Comparator:H3,Range:G3,satisfies:N3,toComparators:V3,maxSatisfying:B3,minSatisfying:D3,minVersion:U3,validRange:K3,outside:j3,gtr:I3,ltr:L3,intersects:A3,simplifyRange:R3,subset:P3,SemVer:lz,re:t9.re,src:t9.src,tokens:t9.t,SEMVER_SPEC_VERSION:d7.SEMVER_SPEC_VERSION,RELEASE_TYPES:d7.RELEASE_TYPES,compareIdentifiers:c7.compareIdentifiers,rcompareIdentifiers:c7.rcompareIdentifiers}});var Pb=k1(O6(),1);class C6{cla;ins;p1;p2;data;constructor(q,J,Z,Q,$){this.cla=q,this.ins=J,this.p1=Z,this.p2=Q,this.data=$??new Uint8Array}getRawApdu(){let q=Uint8Array.from([this.cla,this.ins,this.p1,this.p2,this.data.length]),J=new Uint8Array(q.length+this.data.length);return J.set(q,0),this.data.length>0&&J.set(this.data,q.length),J}}function kY(q){return typeof q=="string"&&/^0x[0-9a-fA-F]*$/.test(q)}function _1(q){if(q.startsWith("0x")&&(q=q.slice(2)),q.length===0)return new Uint8Array;if(q.length%2!==0&&(q="0"+q),/^[0-9a-fA-F]*$/.test(q)===!1)return null;let J=q.match(/.{1,2}/g)?.map((Z)=>parseInt(Z,16));return!J||J.some(isNaN)?null:new Uint8Array(J)}function B0(q,J=!0){return`${J?"0x":""}${Array.from(q,(Z)=>Z.toString(16).padStart(2,"0")).join("")}`}class mq{_tag="ValueOverflow";originalError;message;constructor(q,J=lq){this.message=`Value overflow for ${q}, max is ${J}`}}class Wq{_tag="DataOverflow";message;originalError;constructor(q,J=0){this.message=J===0?`this.data is already full (value: ${q})`:`this.data will overflow with "${q}", remaining bytes: ${J}`}}class b6{_tag="HexaString";message;originalError;constructor(q){this.message=`Invalid encoded hexa string or length is null: ${q}`}}var OY=4294967295;class T6{constructor(q=OY){this.maxPayloadSize=q}data=new Uint8Array;errors=[];build=()=>this.data;tryBuild=()=>this.hasErrors()?void 0:this.data;add8BitUIntToData=(q)=>this.addNumberToData(q,8n,!1,!1);add16BitUIntToData=(q,J=!0)=>this.addNumberToData(q,16n,!1,J);add32BitUIntToData=(q,J=!0)=>this.addNumberToData(q,32n,!1,J);add64BitUIntToData=(q,J=!0)=>this.addNumberToData(q,64n,!1,J);add128BitUIntToData=(q,J=!0)=>this.addNumberToData(q,128n,!1,J);add256BitUIntToData=(q,J=!0)=>this.addNumberToData(q,256n,!1,J);add16BitIntToData=(q,J=!0)=>this.addNumberToData(q,16n,!0,J);add32BitIntToData=(q,J=!0)=>this.addNumberToData(q,32n,!0,J);add64BitIntToData=(q,J=!0)=>this.addNumberToData(q,64n,!0,J);add128BitIntToData=(q,J=!0)=>this.addNumberToData(q,128n,!0,J);add256BitIntToData=(q,J=!0)=>this.addNumberToData(q,256n,!0,J);addBufferToData=(q)=>this.hasEnoughLengthRemaining(q)?(this.data=Uint8Array.from([...this.data,...q]),this):(this.errors.push(new Wq(q.toString())),this);addHexaStringToData=(q)=>{let J=_1(q);return J===null||J.length===0?(this.errors.push(new b6(q)),this):(this.addBufferToData(J),this)};addAsciiStringToData=(q)=>{let J=new TextEncoder().encode(q);return this.addBufferToData(J),this};encodeInLVFromHexa=(q)=>{let J=_1(q);return J===null||J.length===0?(this.errors.push(new b6(q)),this):this.hasEnoughLengthRemaining(J,!0)?(this.add8BitUIntToData(J.length),this.addBufferToData(J),this):(this.errors.push(new Wq(q)),this)};encodeInLVFromBuffer=(q)=>this.hasEnoughLengthRemaining(q,!0)?(this.add8BitUIntToData(q.length),this.addBufferToData(q),this):(this.errors.push(new Wq(q.toString())),this);encodeInLVFromAscii=(q)=>this.hasEnoughLengthRemaining(q,!0)?(this.add8BitUIntToData(q.length),this.addAsciiStringToData(q),this):(this.errors.push(new Wq(q)),this);encodeInTLVFromAscii=(q,J)=>(this.add8BitUIntToData(q),this.encodeInLVFromAscii(J));encodeInTLVFromHexa=(q,J)=>(this.add8BitUIntToData(q),this.encodeInLVFromHexa(J));encodeInTLVFromBuffer=(q,J)=>(this.add8BitUIntToData(q),this.encodeInLVFromBuffer(J));encodeInTLVFromUInt8=(q,J)=>(this.add8BitUIntToData(q),this.add8BitUIntToData(1),this.add8BitUIntToData(J));encodeInTLVFromUInt16=(q,J,Z=!0)=>(this.add8BitUIntToData(q),this.add8BitUIntToData(2),this.add16BitUIntToData(J,Z));encodeInTLVFromUInt32=(q,J,Z=!0)=>(this.add8BitUIntToData(q),this.add8BitUIntToData(4),this.add32BitUIntToData(J,Z));encodeInTLVFromUInt64=(q,J,Z=!0)=>(this.add8BitUIntToData(q),this.add8BitUIntToData(8),this.add64BitUIntToData(J,Z));getAvailablePayloadLength=()=>this.maxPayloadSize-this.data.length;getErrors=()=>this.errors;hasErrors=()=>this.errors.length!==0;hasEnoughLengthRemaining=(q,J=!1)=>this.data.length+q.length+(J?1:0)<=this.maxPayloadSize;addNumberToData(q,J,Z,Q){let $=this.checkBoundsAndConvert(q,J,Z);if($===void 0)return this;let W=Number(J)/8,Y=new Uint8Array(W);if(Q)for(let z=W-1;z>=0;z--)Y[z]=Number($&0xffn),$>>=8n;else for(let z=0;z<W;z++)Y[z]=Number($&0xffn),$>>=8n;return this.addBufferToData(Y)}checkBoundsAndConvert(q,J,Z){if(typeof q=="number"){if(!Number.isInteger(q)||q>Number.MAX_SAFE_INTEGER){this.errors.push(new mq(q.toString()));return}q=BigInt(q)}if(Z){let Q=1n<<J-1n;if(q>=Q||q<-Q){this.errors.push(new mq(q.toString(),Q-1n));return}if(q<0n){let $=(1n<<J)-1n;q=-q,q=(~q&$)+1n}}else{let Q=1n<<J;if(q<0||q>=Q){this.errors.push(new mq(q.toString(),Q-1n));return}}return q}}var lq=255,s_=lq+5;class _0{_ins;_cla;_p1;p2;data=new T6(lq);constructor({ins:q,cla:J,p1:Z,p2:Q}){this._cla=J&255,this._ins=q&255,this._p1=Z&255,this.p2=Q&255}build=()=>new C6(this._cla,this._ins,this._p1,this.p2,this.data.build());add8BitUIntToData=(q)=>(this.data.add8BitUIntToData(q),this);add16BitUIntToData=(q)=>(this.data.add16BitUIntToData(q),this);add32BitUIntToData=(q)=>(this.data.add32BitUIntToData(q),this);add64BitUIntToData=(q,J=!0)=>(this.data.add64BitUIntToData(q,J),this);addBufferToData=(q)=>(this.data.addBufferToData(q),this);addHexaStringToData=(q)=>(this.data.addHexaStringToData(q),this);addAsciiStringToData=(q)=>(this.data.addAsciiStringToData(q),this);encodeInLVFromHexa=(q)=>(this.data.encodeInLVFromHexa(q),this);encodeInLVFromBuffer=(q)=>(this.data.encodeInLVFromBuffer(q),this);encodeInLVFromAscii=(q)=>(this.data.encodeInLVFromAscii(q),this);getAvailablePayloadLength=()=>this.data.getAvailablePayloadLength();getErrors=()=>this.data.getErrors()}class M6{constructor(q){this.buffer=q}index=0;testMinimalLength(q){return q<=this.buffer.length-this.index}extract8BitUInt(){if(!this.outOfRange(1))return this.buffer[this.index++]}extract16BitUInt(q=!0){let J=this.extractNumber(16n,!1,q);return J===void 0?void 0:Number(J)}extract16BitInt(q=!0){let J=this.extractNumber(16n,!0,q);return J===void 0?void 0:Number(J)}extract32BitUInt(q=!0){let J=this.extractNumber(32n,!1,q);return J===void 0?void 0:Number(J)}extract32BitInt(q=!0){let J=this.extractNumber(32n,!0,q);return J===void 0?void 0:Number(J)}extract64BitUInt(q=!0){return this.extractNumber(64n,!1,q)}extract64BitInt(q=!0){return this.extractNumber(64n,!0,q)}extract128BitUInt(q=!0){return this.extractNumber(128n,!1,q)}extract128BitInt(q=!0){return this.extractNumber(128n,!0,q)}extract256BitUInt(q=!0){return this.extractNumber(256n,!1,q)}extract256BitInt(q=!0){return this.extractNumber(256n,!0,q)}extractFieldByLength(q){if(this.outOfRange(q))return;if(q===0)return new Uint8Array;let J=this.buffer.slice(this.index,this.index+q);return this.index+=q,J}extractFieldLVEncoded(){let q=this.extract8BitUInt();if(q===void 0)return;if(q===0)return new Uint8Array;let J=this.extractFieldByLength(q);return J===void 0&&this.index--,J}extractFieldTLVEncoded(){if(this.outOfRange(2))return;let q=this.index,J=this.extract8BitUInt(),Z=this.extractFieldLVEncoded();if(J===void 0||Z===void 0){this.index--;return}let Q=this.index;return{tag:J,value:Z,tlv:this.buffer.slice(q,Q)}}encodeToHexaString(q,J=!1){if(q===void 0||q.length===0)return"";let Z=B0(q);return J?Z:Z.slice(2)}encodeToString(q){let J="",Z=0;if(!q)return J;for(;Z<=q.length;){let Q=q[Z];Q&&(J+=String.fromCharCode(Q)),Z++}return J}getCurrentIndex(){return this.index}resetIndex(){this.index=0}getUnparsedRemainingLength(){return this.buffer.length-this.index}outOfRange(q){return this.index+q>this.buffer.length}extractNumber(q,J,Z){let Q=Number(q)/8;if(this.outOfRange(Q))return;let $=0n;if(Z)for(let W=0;W<Q;W++)$=$<<8n|BigInt(this.buffer[W+this.index]);else for(let W=Q-1;W>=0;W--)$=$<<8n|BigInt(this.buffer[W+this.index]);if(J){let W=1n<<q-1n;$&W&&($-=W<<1n)}return this.index+=Q,$}}class Y0{parser;constructor(q){this.parser=new M6(q.data)}testMinimalLength=(q)=>this.parser.testMinimalLength(q);extract8BitUInt=()=>this.parser.extract8BitUInt();extract16BitUInt=()=>this.parser.extract16BitUInt();extract32BitUInt=()=>this.parser.extract32BitUInt();extractFieldByLength=(q)=>this.parser.extractFieldByLength(q);extractFieldLVEncoded=()=>this.parser.extractFieldLVEncoded();extractFieldTLVEncoded=()=>this.parser.extractFieldTLVEncoded();encodeToHexaString(q,J=!1){return J?this.parser.encodeToHexaString(q,!0):this.parser.encodeToHexaString(q,!1)}encodeToString=(q)=>this.parser.encodeToString(q);getUnparsedRemainingLength=()=>this.parser.getUnparsedRemainingLength()}class H1{_tag="InvalidStatusWordError";originalError;constructor(q){this.originalError=Error(q??"Invalid status word.")}}class Yq{_tag="InvalidResponseFormatError";originalError;constructor(q){this.originalError=Error(q??"Invalid response format.")}}var f6=((q)=>(q.Error="ERROR",q.Success="SUCCESS",q))(f6||{});function CY(q){return"error"in q&&q.error!==void 0}function n0(q){return CY(q)?{status:"ERROR",error:q.error}:{status:"SUCCESS",data:q.data}}function x1(q){return q.status==="SUCCESS"}function T({data:q,error:J}){return J!==void 0?n0({error:J}):n0({data:q})}function n(q){return x1(q)}class m{static isValidStatusCode(q){return q.length===2}static isSuccessResponse({statusCode:q}){return m.isValidStatusCode(q)?q[0]===144&&q[1]===0:!1}static isLockedDeviceResponse({statusCode:q}){return m.isValidStatusCode(q)?q[0]===85&&q[1]===21||q[0]===105&&q[1]===130||q[0]===83&&q[1]===3:!1}static isRefusedByUser({statusCode:q}){return m.isValidStatusCode(q)?q[0]===85&&q[1]===1||q[0]===105&&q[1]===133:!1}static isAppAlreadyInstalled({statusCode:q}){return m.isValidStatusCode(q)?q[0]===106&&q[1]===128||q[0]===106&&q[1]===129||q[0]===106&&q[1]===142||q[0]===106&&q[1]===143:!1}static isOutOfMemory({statusCode:q}){return m.isValidStatusCode(q)?q[0]===106&&q[1]===132||q[0]===106&&q[1]===133||q[0]===81&&q[1]===2||q[0]===81&&q[1]===3:!1}static isApduThatTriggersDisconnection(q){let J=new Map;return J.set("openApp",new Uint8Array([224,216,0,0])),J.set("closeApp",new Uint8Array([176,167,0,0])),Array.from(J.values()).some((Z)=>{for(let Q=0;Q<4;Q++)if(Z[Q]!==q[Q])return!1;return!0})}}class S0{_tag;originalError;errorCode;message;constructor({tag:q,errorCode:J,originalError:Z,message:Q}){this._tag=q,this.originalError=Z,this.errorCode=J,this.message=Q??"An error occured during device exchange."}}class zq{_tag="UnknownDeviceExchangeError";originalError;message;constructor(q){this.originalError=q,this.message="Unexpected device exchange error happened."}}class bY{_tag="DeviceBusyError";originalError;constructor(q){this.originalError=q??Error("Device is busy, please try again later")}}class TY{_tag="InvalidArgumentError";originalError;constructor(q){this.originalError=Error(q??"Invalid argument.")}}var h0=(q,J)=>Object.keys(J).includes(q);class h9 extends S0{constructor(q){super({tag:"GlobalCommandError",...q})}}var S9={5515:{message:"Device is locked.",tag:"DeviceLockedError"},5501:{message:"Action refused on device.",tag:"ActionRefusedError"},5502:{message:"Pin is not set",tag:"PinNotSetError"},5223:{message:"Device internal error",tag:"DeviceInternalError"},"6e00":{message:"CLA not supported",tag:"DeviceInternalError"},"6d00":{message:"INS not supported",tag:"DeviceInternalError"}};class H0{static handle(q){let J=new Y0(q).encodeToHexaString(q.statusCode);return h0(J,S9)?new h9({...S9[J],errorCode:J}):new zq({message:"UnknownError",errorCode:J})}}class wq{name="closeApp";args=void 0;triggersDisconnection=!0;getApdu(){return new _0({cla:176,ins:167,p1:0,p2:0}).build()}parseResponse(q){return m.isSuccessResponse(q)?T({data:void 0}):T({error:H0.handle(q)})}}var e5={"681a":{message:"Invalid LANG_ID value."}};class v9 extends S0{constructor({message:q,errorCode:J}){super({message:q,errorCode:J,tag:"DeleteLanguagePackCommandError"})}}class S6{constructor(q){this.args=q}name="deleteLanguagePack";getApdu(){let q={cla:224,ins:51,p1:this.args.languagePackageId,p2:0};return new _0(q).build()}parseResponse(q){let J=new Y0(q);if(!m.isSuccessResponse(q)){let Z=J.encodeToHexaString(q.statusCode);return h0(Z,e5)?T({error:new v9({...e5[Z],errorCode:Z})}):T({error:H0.handle(q)})}return T({data:void 0})}}class i0{name="getAppAndVersion";args=void 0;getApdu(){return new _0({cla:176,ins:1,p1:0,p2:0}).build()}parseResponse(q){if(!m.isSuccessResponse(q))return T({error:H0.handle(q)});let J=new Y0(q);if(J.extract8BitUInt()!==1)return T({error:new Yq("getAppAndVersion: format not supported")});let Z=J.encodeToString(J.extractFieldLVEncoded()),Q=J.encodeToString(J.extractFieldLVEncoded());if(J.getUnparsedRemainingLength()===0)return T({data:{name:Z,version:Q}});let $=J.extractFieldLVEncoded();return T({data:{name:Z,version:Q,flags:$}})}}var qZ={"662e":{message:"Invalid state, no background image loaded."},"662f":{message:"Invalid state, device is in recovery mode."}};class y9 extends S0{constructor({message:q,errorCode:J}){super({message:q,errorCode:J,tag:"GetBackgroundImageSizeCommandError"})}}class h6{name="getBackgroundImageSize";getApdu(){return new _0({cla:224,ins:100,p1:0,p2:0}).build()}parseResponse(q){let J=new Y0(q);if(!m.isSuccessResponse(q)){let Q=J.encodeToHexaString(q.statusCode);return h0(Q,qZ)?T({error:new y9({...qZ[Q],errorCode:Q})}):T({error:H0.handle(q)})}let Z=J.extract32BitUInt();return Z===void 0?T({error:new H1("Didn't receive any size")}):T({data:Z})}}var JZ=((q)=>(q[q.BATTERY_PERCENTAGE=0]="BATTERY_PERCENTAGE",q[q.BATTERY_VOLTAGE=1]="BATTERY_VOLTAGE",q[q.BATTERY_TEMPERATURE=2]="BATTERY_TEMPERATURE",q[q.BATTERY_CURRENT=3]="BATTERY_CURRENT",q[q.BATTERY_FLAGS=4]="BATTERY_FLAGS",q))(JZ||{}),MY=((q)=>(q[q.NONE=0]="NONE",q[q.USB=1]="USB",q[q.QI=2]="QI",q))(MY||{});class ZZ{name="getBatteryStatus";args;constructor(q){this.args=q}getApdu(){let q={cla:224,ins:16,p1:0,p2:this.args.statusType};return new _0(q).build()}parseResponse(q){if(!m.isSuccessResponse(q))return T({error:H0.handle(q)});let J=new Y0(q),Z=(Q)=>T({error:new Yq(Q)});switch(this.args.statusType){case 0:{let Q=J.extract8BitUInt();return Q===void 0?Z("getBatteryStatus: missing battery percentage in response"):T({data:Q>100?-1:Q})}case 1:{let Q=J.extract16BitUInt();return Q===void 0?Z("getBatteryStatus: missing battery voltage in response"):T({data:Q})}case 2:case 3:{let Q=J.extract8BitUInt();return Q===void 0?Z(this.args.statusType===2?"getBatteryStatus: missing battery temperature in response":"getBatteryStatus: missing battery current in response"):T({data:Q<<24>>24})}case 4:{let Q=J.extract32BitUInt();if(Q===void 0)return Z("getBatteryStatus: missing battery flags in response");let $=!!(Q&8),W=!$&&!!(Q&1);return T({data:{charging:W?2:$?1:0,issueCharging:!!(Q&16),issueTemperature:!!(Q&32),issueBattery:!!(Q&128)}})}default:return Z("getBatteryStatus: unsupported battery status type")}}}var l0=k1(_q(),1);var o=((q)=>(q.NANO_S="nanoS",q.NANO_SP="nanoSP",q.NANO_X="nanoX",q.STAX="stax",q.FLEX="flex",q.APEX="apexp",q))(o||{});class Hq{id;model;name;constructor({id:q,model:J,name:Z}){this.id=q,this.model=J,this.name=Z}}var E3=11415;var rq={Twelve:12,Eighteen:18,TwentyFour:24},D0=((q)=>(q.Unknown="unknown",q.WelcomeScreen1="welcome-screen-1",q.WelcomeScreen2="welcome-screen-2",q.WelcomeScreen3="welcome-screen-3",q.WelcomeScreen4="welcome-screen-4",q.WelcomeScreenReminder="welcome-screen-reminder",q.SetupChoice="setup-choice",q.Pin="pin",q.NewDevice="new-device",q.ConfirmNewDevice="confirm-new-device",q.RestoreRecoveryPhrase="restore-recovery-phrase",q.SafetyWarning="safety-warning",q.DeviceIsReady="device-is-ready",q.ChooseName="choose-name",q.RestoreRecoverBackup="restore-recover-backup",q.SetupRestoreChoice="setup-restore-choice",q.OnboardingStatusCheck="onboarding-status-check",q.RestoreWithRk="restore-with-rk",q))(D0||{});var x3={0:D0.WelcomeScreen1,1:D0.WelcomeScreen2,2:D0.WelcomeScreen3,3:D0.WelcomeScreen4,4:D0.WelcomeScreenReminder,5:D0.SetupChoice,6:D0.Pin,7:D0.NewDevice,8:D0.ConfirmNewDevice,9:D0.RestoreRecoveryPhrase,10:D0.SafetyWarning,11:D0.DeviceIsReady,12:D0.ChooseName,13:D0.RestoreRecoverBackup,14:D0.SetupRestoreChoice,15:D0.OnboardingStatusCheck,16:D0.RestoreWithRk};class e9{seFlags;constructor(q){this.seFlags=new Uint8Array(4),this.seFlags.set(q.subarray(0,this.seFlags.length))}generalDeviceState(){let q=this.seFlags[0]??0;return{isPinValidated:this._checkNthBitInByte(q,1),hasMcuSerialNumber:this._checkNthBitInByte(q,2),hasValidCertificate:this._checkNthBitInByte(q,3),isCustomAuthorityConnectionAllowed:this._checkNthBitInByte(q,4),isSecureConnectionAllowed:this._checkNthBitInByte(q,5),isOnboarded:this._checkNthBitInByte(q,6),isMcuCodeSigned:this._checkNthBitInByte(q,7),isInRecoveryMode:this._checkNthBitInByte(q,8)}}endorsementInformation(){let q=this.seFlags[1]??0;return{hasEndorsementCertificateInSlot1:(q&1)!==0,hasEndorsementCertificateInSlot2:(q&2)!==0}}wordsInformation(){let q=this.seFlags[2]??0,J=q>>5&3;return{numberOfWords:[rq.TwentyFour,rq.Eighteen,rq.Twelve,void 0][J],currentWordIndex:q&31}}onboardingStatus(){let q=this.seFlags[3]??0;return{onboardingState:x3[q]??D0.Unknown}}_checkNthBitInByte(q,J){return(q>>8-J&1)===1}}class T0{name="getOsVersion";args=void 0;getApdu(){return new _0({cla:224,ins:1,p1:0,p2:0}).build()}parseResponse(q,J){if(!m.isSuccessResponse(q))return T({error:H0.handle(q)});let Z=new Y0(q),Q=Z.extract32BitUInt();if(Q===void 0)return T({error:new H1("Missing target ID in OS version")});let $=Z.encodeToString(Z.extractFieldLVEncoded()),W=Z.extractFieldLVEncoded()??new Uint8Array(0),Y=new e9(W),z={...Y.generalDeviceState(),...Y.endorsementInformation(),...Y.wordsInformation(),...Y.onboardingStatus()};$||($="0.0.0",W=new Uint8Array);let X=(Q&4026531840)!==805306368,w=$.includes("-osu"),F="",_="",G="",B="",A,f,e,p0;if(X){G=$,A=Q;let R0=Z.extractFieldLVEncoded();R0&&(R0.length>=5?(F=Z.encodeToString(R0),f=parseInt(Z.encodeToHexaString(Z.extractFieldLVEncoded()),16)):f=parseInt(Z.encodeToHexaString(R0),16))}else{if(F=$,f=Q,_=Z.encodeToString(Z.extractFieldLVEncoded()),this.isBootloaderVersionSupported(F,J)&&(G=Z.encodeToString(Z.extractFieldLVEncoded())),this.isHardwareVersionSupported(F,J)?B=Z.encodeToHexaString(Z.extractFieldLVEncoded()):B="00",this.isLocalizationSupported(F,J)){let R0=Z.extractFieldLVEncoded();R0!==void 0&&(e=parseInt(Z.encodeToHexaString(R0),16))}if(this.isRecoverSupported(F,J)){let R0=Z.extractFieldLVEncoded();R0!==void 0&&(p0=parseInt(Z.encodeToHexaString(R0),16))}}return T({data:{isBootloader:X,isOsu:w,targetId:Q,seTargetId:f,mcuTargetId:A,seVersion:F,seFlags:W,mcuSephVersion:_,mcuBootloaderVersion:G,hwVersion:B,langId:e,recoverState:p0,secureElementFlags:z}})}isBootloaderVersionSupported(q,J){let Z=l0.coerce(q)??"";switch(J){case o.NANO_S:case o.NANO_X:return l0.gte(Z,"2.0.0");default:return!0}}isHardwareVersionSupported(q,J){let Z=l0.coerce(q)??"";switch(J){case o.NANO_X:return l0.gte(Z,"2.0.0");default:return!1}}isLocalizationSupported(q,J){let Z=l0.coerce(q)??"";switch(J){case o.NANO_S:return!1;case o.NANO_SP:return l0.gte(Z,"1.1.0");case o.NANO_X:return l0.gte(Z,"2.1.0");default:return!0}}isRecoverSupported(q,J){let Z=l0.coerce(q)??"";switch(J){case o.NANO_S:return!1;case o.NANO_SP:return l0.gte(Z,"1.1.2");case o.NANO_X:return l0.gte(Z,"2.2.3");case o.STAX:return l0.gte(Z,"1.4.0");case o.FLEX:return l0.gte(Z,"1.0.1");default:return!0}}}var s7={6624:{message:"Invalid state (List applications command must be sent)"}};class n7 extends S0{constructor({message:q,errorCode:J}){super({message:q,errorCode:J,tag:"ListAppsCommandError"})}}class o6{name="listApps";args;constructor(q={isContinue:!1}){this.args=q}getApdu(){let q={cla:224,ins:this.args.isContinue?223:222,p1:0,p2:0};return new _0(q).build()}parseResponse(q){let J=[],Z=new Y0(q);if(!m.isSuccessResponse(q)){let Q=Z.encodeToHexaString(q.statusCode);return h0(Q,s7)?T({error:new n7({...s7[Q],errorCode:Q})}):T({error:H0.handle(q)})}if(q.data.length<=0)return T({data:[]});for(Z.extract8BitUInt();Z.getUnparsedRemainingLength()>0;){let Q=Z.extract8BitUInt(),$=Z.extract16BitUInt();Z.extract16BitUInt();let W=Z.encodeToHexaString(Z.extractFieldByLength(32)),Y=Z.encodeToHexaString(Z.extractFieldByLength(32)),z=Z.encodeToString(Z.extractFieldLVEncoded());J.push({appEntryLength:Q,appSizeInBlocks:$,appCodeHash:W,appFullHash:Y,appName:z})}return T({data:J})}}var i7={"662d":{message:"Invalid LIST_ARG, first command must be sent with P1_LIST_LANGUAGE_PACKS_FIRST."}};class qJ extends S0{constructor({message:q,errorCode:J}){super({message:q,errorCode:J,tag:"ListLanguagePackCommandError"})}}class r6{constructor(q){this.args=q}name="listLanguagePack";getApdu(){let q={cla:224,ins:52,p1:this.args.firstChunk?0:1,p2:0};return new _0(q).build()}parseResponse(q){let J=new Y0(q);if(!m.isSuccessResponse(q)){let Y=J.encodeToHexaString(q.statusCode);return h0(Y,i7)?T({error:new qJ({...i7[Y],errorCode:Y})}):T({error:H0.handle(q)})}if(J.extract8BitUInt()===void 0)return T({data:void 0});J.extract8BitUInt();let Z=J.extractFieldLVEncoded();if(Z===void 0)return T({error:new H1("Failed to get language pack id")});let Q=J.extractFieldLVEncoded();if(Q===void 0)return T({error:new H1("Failed to get language pack size")});let $=parseInt(B0(Z),16),W=parseInt(B0(Q),16);return T({data:{id:$,size:W}})}}var a7={"422f":{message:"Incorrect structure type"},4230:{message:"Incorrect certificate version"},4231:{message:"Incorrect certificate validity"},4232:{message:"Incorrect certificate validity index"},4233:{message:"Unknown signer key ID"},4234:{message:"Unknown signature algorithm"},4235:{message:"Unknown public key ID"},4236:{message:"Unknown public key usage"},4237:{message:"Incorrect elliptic curve ID"},4238:{message:"Incorrect signature algorithm associated to the public key"},4239:{message:"Unknown target device"},"422d":{message:"Unknown certificate tag"},3301:{message:"Failed to hash data"},"422e":{message:"expected_key_usage doesn't match certificate key usage"},5720:{message:"Failed to verify signature"},4118:{message:"trusted_name buffer is too small to contain the trusted name"},ffff:{message:"Cryptography-related error"}};class o7 extends S0{constructor({message:q,errorCode:J}){super({tag:"ProvidePkiCertificateCommandError",message:q,errorCode:J})}}class r7{name="loadCertificate";args;triggersDisconnection=!1;constructor(q){this.args=q}getApdu(){let q={cla:176,ins:6,p1:this.args.keyUsage,p2:0};return new _0(q).addBufferToData(this.args.certificate).build()}parseResponse(q){if(m.isSuccessResponse(q))return T({data:void 0});let J=new Y0(q).encodeToHexaString(q.statusCode);return h0(J,a7)?T({error:new o7({...a7[J],errorCode:J})}):T({error:H0.handle(q)})}}var t7={"670a":{message:"No app name provided"},6807:{message:"Unknown application name"}};class e7 extends S0{constructor({message:q,errorCode:J}){super({tag:"OpenAppCommandError",message:q,errorCode:J})}}class t6{name="openApp";args;triggersDisconnection=!0;constructor(q){this.args=q}getApdu(){return new _0({cla:224,ins:216,p1:0,p2:0}).addAsciiStringToData(this.args.appName).build()}parseResponse(q){if(m.isSuccessResponse(q))return T({data:void 0});let J=new Y0(q).encodeToHexaString(q.statusCode);return h0(J,t7)?T({error:new e7({...t7[J],errorCode:J})}):T({error:H0.handle(q)})}}var u0=((q)=>(q.LOCKED="LOCKED",q.BUSY="BUSY",q.CONNECTED="CONNECTED",q.NOT_CONNECTED="NOT CONNECTED",q))(u0||{});var d1=((q)=>(q.NotStarted="not-started",q.Pending="pending",q.Stopped="stopped",q.Completed="completed",q.Error="error",q))(d1||{});var k=((q)=>(q.None="none",q.UnlockDevice="unlock-device",q.AllowSecureConnection="allow-secure-connection",q.ConfirmOpenApp="confirm-open-app",q.SignTransaction="sign-transaction",q.SignTypedData="sign-typed-data",q.AllowListApps="allow-list-apps",q.VerifyAddress="verify-address",q.SignPersonalMessage="sign-personal-message",q.SignDelegationAuthorization="sign-delegation-authorization",q.Web3ChecksOptIn="web3-checks-opt-in",q.VerifySafeAddress="verify-safe-address",q.RegisterWallet="register-wallet",q.ConfirmLoadImage="confirm-load-image",q.ConfirmCommitImage="confirm-commit-image",q.ConfirmRemoveImage="confirm-remove-image",q.GrantConsent="grant-consent",q.AllowInstallFirmware="allow-install-firmware",q))(k||{});var J0={of(q){return I0(q)},empty(){return p},zero(){return p},fromNullable(q){return q==null?p:I0(q)},fromFalsy(q){return q?I0(q):p},fromPredicate(q,J){switch(arguments.length){case 1:return(Z)=>J0.fromPredicate(q,Z);default:return q(J)?I0(J):p}},mapMaybe(q,J){switch(arguments.length){case 1:return(Z)=>J0.mapMaybe(q,Z);default:return J0.catMaybes(J.map(q))}},catMaybes(q){let J=[];for(let Z of q)if(Z.isJust())J.push(Z.extract());return J},encase(q){try{return I0(q())}catch{return p}},isMaybe(q){return q instanceof e6||q instanceof q8},sequence(q){let J=[];for(let Z of q)if(Z.isJust())J.push(Z.extract());else return p;return I0(J)},"fantasy-land/of"(q){return this.of(q)},"fantasy-land/empty"(){return this.empty()},"fantasy-land/zero"(){return this.zero()}};class e6{constructor(q){this.__value=q,this["fantasy-land/equals"]=this.equals,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/alt"]=this.alt,this["fantasy-land/chain"]=this.chain,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend,this["fantasy-land/filter"]=this.filter}isJust(){return!0}isNothing(){return!1}inspect(){return`Just(${this.__value})`}toString(){return this.inspect()}toJSON(){let q=this.__value;return q instanceof Date?q.toJSON():q}equals(q){return this.extract()===q.extract()}map(q){return I0(q(this.__value))}ap(q){return q.isJust()?this.map(q.extract()):p}alt(q){return this}altLazy(q){return this}chain(q){return q(this.__value)}chainNullable(q){return J0.fromNullable(q(this.__value))}join(){return this.__value}reduce(q,J){return q(J,this.__value)}extend(q){return I0(q(this))}unsafeCoerce(){return this.__value}caseOf(q){return"_"in q?q._():q.Just(this.__value)}orDefault(q){return this.__value}orDefaultLazy(q){return this.__value}toList(){return[this.__value]}mapOrDefault(q,J){return q(this.__value)}extract(){return this.__value}extractNullable(){return this.__value}toEither(q){return I(this.__value)}ifJust(q){return q(this.__value),this}ifNothing(q){return this}filter(q){return q(this.__value)?I0(this.__value):p}}e6.prototype.constructor=J0;class q8{constructor(){this["fantasy-land/equals"]=this.equals,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/alt"]=this.alt,this["fantasy-land/chain"]=this.chain,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend,this["fantasy-land/filter"]=this.filter}isJust(){return!1}isNothing(){return!0}inspect(){return"Nothing"}toString(){return this.inspect()}toJSON(){return this.__value}equals(q){return this.extract()===q.extract()}map(q){return p}ap(q){return p}alt(q){return q}altLazy(q){return q()}chain(q){return p}chainNullable(q){return p}join(){return p}reduce(q,J){return J}extend(q){return p}unsafeCoerce(){throw Error("Maybe#unsafeCoerce was ran on a Nothing")}caseOf(q){return"_"in q?q._():q.Nothing()}orDefault(q){return q}orDefaultLazy(q){return q()}toList(){return[]}mapOrDefault(q,J){return J}extract(){return}extractNullable(){return null}toEither(q){return K(q)}ifJust(q){return this}ifNothing(q){return q(),this}filter(q){return p}}q8.prototype.constructor=J0;var I0=(q)=>new e6(q),p=new q8;var L0={of(q){return I(q)},lefts(q){let J=[];for(let Z of q)if(Z.isLeft())J.push(Z.extract());return J},rights(q){let J=[];for(let Z of q)if(Z.isRight())J.push(Z.extract());return J},encase(q){try{return I(q())}catch(J){return K(J)}},sequence(q){let J=[];for(let Z of q){if(Z.isLeft())return Z;J.push(Z.extract())}return I(J)},isEither(q){return q instanceof Z8||q instanceof J8},"fantasy-land/of"(q){return L0.of(q)}};class J8{constructor(q){this.__value=q,this._="R",this["fantasy-land/bimap"]=this.bimap,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/equals"]=this.equals,this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend}isLeft(){return!1}isRight(){return!0}toJSON(){return this.__value}inspect(){return`Right(${this.__value})`}toString(){return this.inspect()}bimap(q,J){return I(J(this.__value))}map(q){return I(q(this.__value))}mapLeft(q){return this}ap(q){return q.isRight()?this.map(q.extract()):q}equals(q){return q.isRight()?this.__value===q.extract():!1}chain(q){return q(this.__value)}chainLeft(q){return this}join(){return this.__value}alt(q){return this}altLazy(q){return this}reduce(q,J){return q(J,this.__value)}extend(q){return I(q(this))}unsafeCoerce(){return this.__value}caseOf(q){return"_"in q?q._():q.Right(this.__value)}leftOrDefault(q){return q}orDefault(q){return this.__value}orDefaultLazy(q){return this.__value}leftOrDefaultLazy(q){return q()}ifLeft(q){return this}ifRight(q){return q(this.__value),this}toMaybe(){return I0(this.__value)}leftToMaybe(){return p}extract(){return this.__value}swap(){return K(this.__value)}}J8.prototype.constructor=L0;class Z8{constructor(q){this.__value=q,this._="L",this["fantasy-land/bimap"]=this.bimap,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/equals"]=this.equals,this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend}isLeft(){return!0}isRight(){return!1}toJSON(){return this.__value}inspect(){return`Left(${JSON.stringify(this.__value)})`}toString(){return this.inspect()}bimap(q,J){return K(q(this.__value))}map(q){return this}mapLeft(q){return K(q(this.__value))}ap(q){return q.isLeft()?q:this}equals(q){return q.isLeft()?q.extract()===this.__value:!1}chain(q){return this}chainLeft(q){return q(this.__value)}join(){return this}alt(q){return q}altLazy(q){return q()}reduce(q,J){return J}extend(q){return this}unsafeCoerce(){if(this.__value instanceof Error)throw this.__value;throw Error("Either#unsafeCoerce was ran on a Left")}caseOf(q){return"_"in q?q._():q.Left(this.__value)}leftOrDefault(q){return this.__value}orDefault(q){return q}orDefaultLazy(q){return q()}leftOrDefaultLazy(q){return this.__value}ifLeft(q){return q(this.__value),this}ifRight(q){return this}toMaybe(){return p}leftToMaybe(){return I0(this.__value)}extract(){return this.__value}swap(){return I(this.__value)}}Z8.prototype.constructor=L0;var K=(q)=>new Z8(q),I=(q)=>new J8(q);var G1=(q)=>q;var Q8=(q,J)=>{return typeof J==="bigint"?J.toString():J};var qQ=(q)=>typeof q==="object"&&q!==null&&!Array.isArray(q),Y1=(q,J)=>{let Z="";switch(typeof J){case"undefined":Z="undefined";break;case"object":Z=J===null?"null":Array.isArray(J)?"an array with value "+JSON.stringify(J,Q8):"an object with value "+JSON.stringify(J,Q8);break;case"boolean":Z="a boolean";break;case"symbol":Z="a symbol";break;case"function":Z="a function";break;case"bigint":Z=`a bigint with value ${J.toString()}`}return Z=Z||`a ${typeof J} with value ${JSON.stringify(J,Q8)}`,`Expected ${q}, but received ${Z}`},k3=(q)=>{if(Object.keys(q).length===1&&q.oneOf?.length===1&&typeof q.oneOf[0]==="object")Object.assign(q,q.oneOf[0]),delete q.oneOf;return q},O3=(q)=>{if(Array.isArray(q.oneOf))for(let J=0;J<q.oneOf.length;J++){let Z=q.oneOf[J];if(typeof Z==="object"&&Z.oneOf)return q.oneOf.splice(J,1),q.oneOf.push(...Z.oneOf),JQ(q)}return q},JQ=(q)=>{return O3(q),k3(q),q},r0={interface(q){let J=Object.keys(q),Z=($)=>{if(!qQ($))return K(Y1("an object",$));let W={};for(let Y of J){if(!$.hasOwnProperty(Y)&&!q[Y]._isOptional)return K(`Problem with property "${Y}": it does not exist in received object ${JSON.stringify($,Q8)}`);let z=q[Y].decode($[Y]);if(z.isLeft())return K(`Problem with the value of property "${Y}": ${z.extract()}`);let X=z.extract();if(X!==void 0)W[Y]=X}return I(W)};return{decode:Z,encode:($)=>{let W={};for(let Y of J)W[Y]=q[Y].encode($[Y]);return W},unsafeDecode:($)=>Z($).mapLeft(Error).unsafeCoerce(),schema:()=>J.reduce(($,W)=>{if(!q[W]._isOptional)$.required.push(W);return $.properties[W]=JQ(q[W].schema()),$},{type:"object",properties:{},required:[]})}},custom({decode:q,encode:J,schema:Z}){return{decode:q,encode:J,unsafeDecode:(Q)=>q(Q).mapLeft(Error).unsafeCoerce(),schema:Z??(()=>({}))}}},ZQ=r0.custom({decode:(q)=>typeof q==="string"?I(q):K(Y1("a string",q)),encode:G1,schema:()=>({type:"string"})}),QQ=r0.custom({decode:(q)=>typeof q==="number"?I(q):K(Y1("a number",q)),encode:G1,schema:()=>({type:"number"})}),yN=r0.custom({decode:(q)=>q===null?I(q):K(Y1("a null",q)),encode:G1,schema:()=>({type:"null"})}),C3=r0.custom({decode:(q)=>q===void 0?I(q):K(Y1("an undefined",q)),encode:G1}),uN=(q)=>({...b3([q,C3]),schema:q.schema,_isOptional:!0});var gN=r0.custom({decode:(q)=>typeof q==="boolean"?I(q):K(Y1("a boolean",q)),encode:G1,schema:()=>({type:"boolean"})}),mN=r0.custom({decode:I,encode:G1,schema:()=>({})});var b3=(q)=>r0.custom({decode:(J)=>{let Z=[];for(let Q of q){let $=Q.decode(J);if($.isRight())return $;else Z.push($.extract())}return K(`One of the following problems occured: ${Z.map((Q,$)=>`(${$}) ${Q}`).join(", ")}`)},encode:(J)=>{for(let Z of q)if(L0.encase(()=>Z.encode(J)).mapLeft(($)=>"").chain(Z.decode).isRight())return Z.encode(J);return J},schema:()=>({oneOf:q.map((J)=>J.schema())})}),lN=(q)=>r0.custom({decode:(J)=>{if(!Array.isArray(J))return K(Y1("an array",J));else{let Z=[];for(let Q=0;Q<J.length;Q++){let $=q.decode(J[Q]);if($.isRight())Z.push($.extract());else return K(`Problem with the value at index ${Q}: ${$.extract()}`)}return I(Z)}},encode:(J)=>J.map(q.encode),schema:()=>({type:"array",items:q.schema()})}),T3=r0.custom({decode:(q)=>ZQ.decode(q).chain((J)=>isFinite(+J)?I(J):K(Y1("a number",q))),encode:G1,schema:QQ.schema}),dN=(q,J)=>r0.custom({decode:(Z)=>{let Q={},$=q===QQ?T3:q;if(!qQ(Z))return K(Y1("an object",Z));for(let W of Object.keys(Z))if(Z.hasOwnProperty(W)){let Y=$.decode(W),z=J.decode(Z[W]);if(Y.isRight()&&z.isRight())Q[Y.extract()]=z.extract();else if(Y.isLeft())return K(`Problem with key type of property "${W}": ${Y.extract()}`);else if(z.isLeft())return K(`Problem with the value of property "${W}": ${z.extract()}`)}return I(Q)},encode:(Z)=>{let Q={};for(let $ in Z)if(Z.hasOwnProperty($))Q[q.encode($)]=J.encode(Z[$]);return Q},schema:()=>({type:"object",additionalProperties:J.schema()})}),cN=(...q)=>r0.custom({decode:(J)=>q.includes(J)?I(J):K(Y1(q.map((Z)=>JSON.stringify(Z)).join(", "),J)),encode:G1,schema:()=>({oneOf:q.map((J)=>({type:typeof J,enum:[J]}))})});var pN=r0.custom({decode:(q)=>ZQ.decode(q).mapLeft((J)=>`Problem with date string: ${J}`).chain((J)=>Number.isNaN(Date.parse(J))?K("Expected a valid date string, but received a string that cannot be parsed"):I(new Date(J))),encode:(q)=>q.toISOString(),schema:()=>({type:"string",format:"date-time"})});var $Q,WQ={liftEither(q){if(q.isRight())return Promise.resolve(q.extract());throw q.extract()},fromPromise(q){return q.then(WQ.liftEither)},throwE(q){throw q}};class JJ{constructor(q){this.runPromise=q,this[$Q]="EitherAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this.then=(J,Z)=>{return this.run().then(J,Z)}}leftOrDefault(q){return this.run().then((J)=>J.leftOrDefault(q))}orDefault(q){return this.run().then((J)=>J.orDefault(q))}join(){return S(async(q)=>{let J=await this;if(J.isRight()){let Z=await J.extract();return q.liftEither(Z)}return q.liftEither(J)})}ap(q){return S(async(J)=>{let Z=await q;if(Z.isRight()){let Q=await this.run();if(Q.isRight())return Z.extract()(Q.extract());else return J.liftEither(Q)}return J.liftEither(Z)})}alt(q){return S(async(J)=>{let Z=await this.run();if(Z.isRight())return Z.extract();else{let Q=await q;return J.liftEither(Q)}})}extend(q){return S(async(J)=>{let Z=await this.run();if(Z.isRight()){let Q=S.liftEither(Z);return J.liftEither(I(q(Q)))}return J.liftEither(Z)})}async run(){try{return I(await this.runPromise(WQ))}catch(q){return K(q)}}bimap(q,J){return S(async(Z)=>{let Q=await this.run();try{return await Z.liftEither(Q.bimap(q,J))}catch($){throw await $}})}map(q){return S((J)=>this.runPromise(J).then(q))}mapLeft(q){return S(async(J)=>{try{return await this.runPromise(J)}catch(Z){throw await q(Z)}})}chain(q){return S(async(J)=>{let Z=await this.runPromise(J);return J.fromPromise(q(Z))})}chainLeft(q){return S(async(J)=>{try{return await this.runPromise(J)}catch(Z){return J.fromPromise(q(Z))}})}toMaybeAsync(){return k0(async({liftMaybe:q})=>{let J=await this.run();return q(J.toMaybe())})}swap(){return S(async(q)=>{let J=await this.run();if(J.isRight())q.throwE(J.extract());return q.liftEither(I(J.extract()))})}ifLeft(q){return S(async(J)=>{let Z=await this.run();return Z.ifLeft(q),J.liftEither(Z)})}ifRight(q){return S(async(J)=>{let Z=await this.run();return Z.ifRight(q),J.liftEither(Z)})}void(){return this.map((q)=>{})}caseOf(q){return this.run().then((J)=>J.caseOf(q))}finally(q){return S(({fromPromise:J})=>J(this.run().finally(q)))}}$Q=Symbol.toStringTag;var S=Object.assign((q)=>new JJ(q),{fromPromise:(q)=>S(({fromPromise:J})=>J(q())),liftEither:(q)=>S(({liftEither:J})=>J(q)),lefts:(q)=>Promise.all(q.map((J)=>J.run())).then(L0.lefts),rights:(q)=>Promise.all(q.map((J)=>J.run())).then(L0.rights),sequence:(q)=>S(async(J)=>{let Z=[];for await(let Q of q){if(Q.isLeft())return J.liftEither(Q);Z.push(Q.extract())}return J.liftEither(I(Z))}),all:(q)=>S.fromPromise(async()=>Promise.all(q).then(L0.sequence))});JJ.prototype.constructor=S;var YQ,zQ={liftMaybe(q){if(q.isJust())return Promise.resolve(q.extract());throw p},fromPromise(q){return q.then(zQ.liftMaybe)}};class ZJ{constructor(q){this.runPromise=q,this[YQ]="MaybeAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/filter"]=this.filter,this["fantasy-land/alt"]=this.alt}orDefault(q){return this.run().then((J)=>J.orDefault(q))}join(){return k0(async(q)=>{let J=await this.run();if(J.isJust()){let Z=await J.extract();return q.liftMaybe(Z)}return q.liftMaybe(p)})}ap(q){return k0(async(J)=>{let Z=await q;if(Z.isJust()){let Q=await this.run();if(Q.isJust())return Z.extract()(Q.extract());else return J.liftMaybe(p)}return J.liftMaybe(p)})}alt(q){return k0(async(J)=>{let Z=await this.run();if(Z.isJust())return Z.extract();else{let Q=await q;return J.liftMaybe(Q)}})}extend(q){return k0(async(J)=>{let Z=await this.run();if(Z.isJust()){let Q=k0.liftMaybe(Z);return J.liftMaybe(I0(q(Q)))}return J.liftMaybe(p)})}filter(q){return k0(async(J)=>{let Z=await this.run();return J.liftMaybe(Z.filter(q))})}async run(){try{return I0(await this.runPromise(zQ))}catch{return p}}map(q){return k0((J)=>this.runPromise(J).then(q))}chain(q){return k0(async(J)=>{let Z=await this.runPromise(J);return J.fromPromise(q(Z))})}toEitherAsync(q){return S(async({liftEither:J})=>{let Z=await this.run();return J(Z.toEither(q))})}ifJust(q){return k0(async(J)=>{let Z=await this.run();return Z.ifJust(q),J.liftMaybe(Z)})}ifNothing(q){return k0(async(J)=>{let Z=await this.run();return Z.ifNothing(q),J.liftMaybe(Z)})}void(){return this.map((q)=>{})}caseOf(q){return this.run().then((J)=>J.caseOf(q))}finally(q){return k0(({fromPromise:J})=>J(this.run().finally(q)))}then(q,J){return this.run().then(q,J)}}YQ=Symbol.toStringTag;var k0=Object.assign((q)=>new ZJ(q),{catMaybes:(q)=>Promise.all(q).then(J0.catMaybes),fromPromise:(q)=>k0(({fromPromise:J})=>J(q())),liftMaybe:(q)=>k0(({liftMaybe:J})=>J(q))});ZJ.prototype.constructor=k0;function M3(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function f3(){let q=M3();if(q.__xstate__)return q.__xstate__;return}var wQ=(q)=>{if(typeof window>"u")return;let J=f3();if(J)J.register(q)};class WJ{constructor(q){this._process=q,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){if(this._current)this._current.next=null,this._last=this._current}enqueue(q){let J={value:q,next:null};if(this._current){this._last.next=J,this._last=J;return}if(this._current=J,this._last=J,this._active)this.flush()}flush(){while(this._current){let q=this._current;this._process(q.value),this._current=q.next}this._last=null}}var XJ=".",S3="",FJ="",h3="#",v3="*",NQ="xstate.init";var s1="xstate.stop";function y3(q,J){return{type:`xstate.after.${q}.${J}`}}function YJ(q,J){return{type:`xstate.done.state.${q}`,output:J}}function u3(q,J){return{type:`xstate.done.actor.${q}`,output:J,actorId:q}}function VQ(q,J){return{type:`xstate.error.actor.${q}`,error:J,actorId:q}}function _J(q){return{type:NQ,input:q}}function N1(q){setTimeout(()=>{throw q})}var g3=(()=>typeof Symbol==="function"&&Symbol.observable||"@@observable")();function HJ(q,J){let Z=XQ(q),Q=XQ(J);if(typeof Q==="string"){if(typeof Z==="string")return Q===Z;return!1}if(typeof Z==="string")return Z in Q;return Object.keys(Z).every(($)=>{if(!($ in Q))return!1;return HJ(Z[$],Q[$])})}function Y8(q){if(UQ(q))return q;let J=[],Z="";for(let Q=0;Q<q.length;Q++){switch(q.charCodeAt(Q)){case 92:Z+=q[Q+1],Q++;continue;case 46:J.push(Z),Z="";continue}Z+=q[Q]}return J.push(Z),J}function XQ(q){if(MQ(q))return q.value;if(typeof q!=="string")return q;let J=Y8(q);return BQ(J)}function BQ(q){if(q.length===1)return q[0];let J={},Z=J;for(let Q=0;Q<q.length-1;Q++)if(Q===q.length-2)Z[q[Q]]=q[Q+1];else{let $=Z;Z={},$[q[Q]]=Z}return J}function GJ(q,J){let Z={},Q=Object.keys(q);for(let $=0;$<Q.length;$++){let W=Q[$];Z[W]=J(q[W],W,q,$)}return Z}function DQ(q){if(UQ(q))return q;return[q]}function V1(q){if(q===void 0)return[];return DQ(q)}function zJ(q,J,Z,Q){if(typeof q==="function")return q({context:J,event:Z,self:Q});return q}function UQ(q){return Array.isArray(q)}function m3(q){return q.type.startsWith("xstate.error.actor")}function c1(q){return DQ(q).map((J)=>{if(typeof J>"u"||typeof J==="string")return{target:J};return J})}function KQ(q){if(q===void 0||q===S3)return;return V1(q)}function $8(q,J,Z){let Q=typeof q==="object",$=Q?q:void 0;return{next:(Q?q.next:q)?.bind($),error:(Q?q.error:J)?.bind($),complete:(Q?q.complete:Z)?.bind($)}}function NJ(q,J){return`${J}.${q}`}function eq(q,J){let Z=J.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!Z)return q.implementations.actors[J];let[,Q,$]=Z,Y=q.getStateNodeById($).config.invoke;return(Array.isArray(Y)?Y[Q]:Y).src}function FQ(q,J){return`${q.sessionId}.${J}`}var l3=0;function d3(q,J){let Z=new Map,Q=new Map,$=new WeakMap,W=new Set,Y={},{clock:z,logger:X}=J,w={schedule:(G,B,A,f,e=Math.random().toString(36).slice(2))=>{let p0={source:G,target:B,event:A,delay:f,id:e,startedAt:Date.now()},R0=FQ(G,e);_._snapshot._scheduledEvents[R0]=p0;let C9=z.setTimeout(()=>{delete Y[R0],delete _._snapshot._scheduledEvents[R0],_._relay(G,B,A)},f);Y[R0]=C9},cancel:(G,B)=>{let A=FQ(G,B),f=Y[A];if(delete Y[A],delete _._snapshot._scheduledEvents[A],f!==void 0)z.clearTimeout(f)},cancelAll:(G)=>{for(let B in _._snapshot._scheduledEvents){let A=_._snapshot._scheduledEvents[B];if(A.source===G)w.cancel(G,A.id)}}},F=(G)=>{if(!W.size)return;let B={...G,rootId:q.sessionId};W.forEach((A)=>A.next?.(B))},_={_snapshot:{_scheduledEvents:(J?.snapshot&&J.snapshot.scheduler)??{}},_bookId:()=>`x:${l3++}`,_register:(G,B)=>{return Z.set(G,B),G},_unregister:(G)=>{Z.delete(G.sessionId);let B=$.get(G);if(B!==void 0)Q.delete(B),$.delete(G)},get:(G)=>{return Q.get(G)},_set:(G,B)=>{let A=Q.get(G);if(A&&A!==B)throw Error(`Actor with system ID '${G}' already exists.`);Q.set(G,B),$.set(B,G)},inspect:(G)=>{let B=$8(G);return W.add(B),{unsubscribe(){W.delete(B)}}},_sendInspectionEvent:F,_relay:(G,B,A)=>{_._sendInspectionEvent({type:"@xstate.event",sourceRef:G,actorRef:B,event:A}),B._send(A)},scheduler:w,getSnapshot:()=>{return{_scheduledEvents:{..._._snapshot._scheduledEvents}}},start:()=>{let G=_._snapshot._scheduledEvents;_._snapshot._scheduledEvents={};for(let B in G){let{source:A,target:f,event:e,delay:p0,id:R0}=G[B];w.schedule(A,f,e,p0,R0)}},_clock:z,_logger:X};return _}var QJ=!1,z8=1,g0=function(q){return q[q.NotStarted=0]="NotStarted",q[q.Running=1]="Running",q[q.Stopped=2]="Stopped",q}({}),c3={clock:{setTimeout:(q,J)=>{return setTimeout(q,J)},clearTimeout:(q)=>{return clearTimeout(q)}},logger:console.log.bind(console),devTools:!1};class VJ{constructor(q,J){this.logic=q,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new WJ(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=g0.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];let Z={...c3,...J},{clock:Q,logger:$,parent:W,syncSnapshot:Y,id:z,systemId:X,inspect:w}=Z;if(this.system=W?W.system:d3(this,{clock:Q,logger:$}),w&&!W)this.system.inspect($8(w));if(this.sessionId=this.system._bookId(),this.id=z??this.sessionId,this.logger=J?.logger??this.system._logger,this.clock=J?.clock??this.system._clock,this._parent=W,this._syncSnapshot=Y,this.options=Z,this.src=Z.src??q,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:(F)=>{this._deferred.push(F)},system:this.system,stopChild:(F)=>{if(F._parent!==this)throw Error(`Cannot stop child actor ${F.id} of ${this.id} because it is not a child`);F._stop()},emit:(F)=>{let _=this.eventListeners.get(F.type),G=this.eventListeners.get("*");if(!_&&!G)return;let B=[..._?_.values():[],...G?G.values():[]];for(let A of B)A(F)},actionExecutor:(F)=>{let _=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:F.type,params:F.params}}),!F.exec)return;let G=QJ;try{QJ=!0,F.exec(F.info,F.params)}finally{QJ=G}};if(this._processingStatus===g0.Running)_();else this._deferred.push(_)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),X)this._systemId=X,this.system._set(X,this);if(this._initState(J?.snapshot??J?.state),X&&this._snapshot.status!=="active")this.system._unregister(this)}_initState(q){try{this._snapshot=q?this.logic.restoreSnapshot?this.logic.restoreSnapshot(q,this._actorScope):q:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(J){this._snapshot={status:"error",output:void 0,error:J}}}update(q,J){this._snapshot=q;let Z;while(Z=this._deferred.shift())try{Z()}catch(Q){this._deferred.length=0,this._snapshot={...q,status:"error",error:Q}}switch(this._snapshot.status){case"active":for(let Q of this.observers)try{Q.next?.(q)}catch($){N1($)}break;case"done":for(let Q of this.observers)try{Q.next?.(q)}catch($){N1($)}if(this._stopProcedure(),this._complete(),this._doneEvent=u3(this.id,this._snapshot.output),this._parent)this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:J,snapshot:q})}subscribe(q,J,Z){let Q=$8(q,J,Z);if(this._processingStatus!==g0.Stopped)this.observers.add(Q);else switch(this._snapshot.status){case"done":try{Q.complete?.()}catch($){N1($)}break;case"error":{let $=this._snapshot.error;if(!Q.error)N1($);else try{Q.error($)}catch(W){N1(W)}break}}return{unsubscribe:()=>{this.observers.delete(Q)}}}on(q,J){let Z=this.eventListeners.get(q);if(!Z)Z=new Set,this.eventListeners.set(q,Z);let Q=J.bind(void 0);return Z.add(Q),{unsubscribe:()=>{Z.delete(Q)}}}start(){if(this._processingStatus===g0.Running)return this;if(this._syncSnapshot)this.subscribe({next:(Z)=>{if(Z.status==="active")this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:Z})},error:()=>{}});if(this.system._register(this.sessionId,this),this._systemId)this.system._set(this._systemId,this);this._processingStatus=g0.Running;let q=_J(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:q}),this._snapshot.status){case"done":return this.update(this._snapshot,q),this;case"error":return this._error(this._snapshot.error),this}if(!this._parent)this.system.start();if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(Z){return this._snapshot={...this._snapshot,status:"error",error:Z},this._error(Z),this}if(this.update(this._snapshot,q),this.options.devTools)this.attachDevTools();return this.mailbox.start(),this}_process(q){let J,Z;try{J=this.logic.transition(this._snapshot,q,this._actorScope)}catch(Q){Z={err:Q}}if(Z){let{err:Q}=Z;this._snapshot={...this._snapshot,status:"error",error:Q},this._error(Q);return}if(this.update(J,q),q.type===s1)this._stopProcedure(),this._complete()}_stop(){if(this._processingStatus===g0.Stopped)return this;if(this.mailbox.clear(),this._processingStatus===g0.NotStarted)return this._processingStatus=g0.Stopped,this;return this.mailbox.enqueue({type:s1}),this}stop(){if(this._parent)throw Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(let q of this.observers)try{q.complete?.()}catch(J){N1(J)}this.observers.clear()}_reportError(q){if(!this.observers.size){if(!this._parent)N1(q);return}let J=!1;for(let Z of this.observers){let Q=Z.error;J||=!Q;try{Q?.(q)}catch($){N1($)}}if(this.observers.clear(),J)N1(q)}_error(q){if(this._stopProcedure(),this._reportError(q),this._parent)this.system._relay(this,this._parent,VQ(this.id,q))}_stopProcedure(){if(this._processingStatus!==g0.Running)return this;return this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new WJ(this._process.bind(this)),this._processingStatus=g0.Stopped,this.system._unregister(this),this}_send(q){if(this._processingStatus===g0.Stopped)return;this.mailbox.enqueue(q)}send(q){this.system._relay(void 0,this,q)}attachDevTools(){let{devTools:q}=this.options;if(q)(typeof q==="function"?q:wQ)(this)}toJSON(){return{xstate$$type:z8,id:this.id}}getPersistedSnapshot(q){return this.logic.getPersistedSnapshot(this._snapshot,q)}[g3](){return this}getSnapshot(){return this._snapshot}}function t0(q,...[J]){return new VJ(q,J)}function p3(q,J,Z,Q,{sendId:$}){let W=typeof $==="function"?$(Z,Q):$;return[J,{sendId:W},void 0]}function s3(q,J){q.defer(()=>{q.system.scheduler.cancel(q.self,J.sendId)})}function BJ(q){function J(Z,Q){}return J.type="xstate.cancel",J.sendId=q,J.resolve=p3,J.execute=s3,J}function n3(q,J,Z,Q,{id:$,systemId:W,src:Y,input:z,syncSnapshot:X}){let w=typeof Y==="string"?eq(J.machine,Y):Y,F=typeof $==="function"?$(Z):$,_,G=void 0;if(w)G=typeof z==="function"?z({context:J.context,event:Z.event,self:q.self}):z,_=t0(w,{id:F,src:Y,parent:q.self,syncSnapshot:X,systemId:W,input:G});return[b1(J,{children:{...J.children,[F]:_}}),{id:$,systemId:W,actorRef:_,src:Y,input:G},void 0]}function i3(q,{actorRef:J}){if(!J)return;q.defer(()=>{if(J._processingStatus===g0.Stopped)return;J.start()})}function DJ(...[q,{id:J,systemId:Z,input:Q,syncSnapshot:$=!1}={}]){function W(Y,z){}return W.type="xstate.spawnChild",W.id=J,W.systemId=Z,W.src=q,W.input=Q,W.syncSnapshot=$,W.resolve=n3,W.execute=i3,W}function a3(q,J,Z,Q,{actorRef:$}){let W=typeof $==="function"?$(Z,Q):$,Y=typeof W==="string"?J.children[W]:W,z=J.children;if(Y)z={...z},delete z[Y.id];return[b1(J,{children:z}),Y,void 0]}function o3(q,J){if(!J)return;if(q.system._unregister(J),J._processingStatus!==g0.Running){q.stopChild(J);return}q.defer(()=>{q.stopChild(J)})}function w8(q){function J(Z,Q){}return J.type="xstate.stopChild",J.actorRef=q,J.resolve=a3,J.execute=o3,J}function r3(q,{context:J,event:Z},{guards:Q}){return Q.every(($)=>Bq($,J,Z,q))}function t3(q){function J(Z,Q){return!1}return J.check=r3,J.guards=q,J}function Bq(q,J,Z,Q){let{machine:$}=Q,W=typeof q==="function",Y=W?q:$.implementations.guards[typeof q==="string"?q:q.type];if(!W&&!Y)throw Error(`Guard '${typeof q==="string"?q:q.type}' is not implemented.'.`);if(typeof Y!=="function")return Bq(Y,J,Z,Q);let z={context:J,event:Z},X=W||typeof q==="string"?void 0:("params"in q)?typeof q.params==="function"?q.params({context:J,event:Z}):q.params:void 0;if(!("check"in Y))return Y(z,X);return Y.check(Q,z,Y)}var UJ=(q)=>q.type==="atomic"||q.type==="final";function Nq(q){return Object.values(q.states).filter((J)=>J.type!=="history")}function q6(q,J){let Z=[];if(J===q)return Z;let Q=q.parent;while(Q&&Q!==J)Z.push(Q),Q=Q.parent;return Z}function J6(q){let J=new Set(q),Z=IQ(J);for(let Q of J)if(Q.type==="compound"&&(!Z.get(Q)||!Z.get(Q).length))_Q(Q).forEach(($)=>J.add($));else if(Q.type==="parallel")for(let $ of Nq(Q)){if($.type==="history")continue;if(!J.has($)){let W=_Q($);for(let Y of W)J.add(Y)}}for(let Q of J){let $=Q.parent;while($)J.add($),$=$.parent}return J}function jQ(q,J){let Z=J.get(q);if(!Z)return{};if(q.type==="compound"){let $=Z[0];if($){if(UJ($))return $.key}else return{}}let Q={};for(let $ of Z)Q[$.key]=jQ($,J);return Q}function IQ(q){let J=new Map;for(let Z of q){if(!J.has(Z))J.set(Z,[]);if(Z.parent){if(!J.has(Z.parent))J.set(Z.parent,[]);J.get(Z.parent).push(Z)}}return J}function LQ(q,J){let Z=J6(J);return jQ(q,IQ(Z))}function X8(q,J){if(J.type==="compound")return Nq(J).some((Z)=>Z.type==="final"&&q.has(Z));if(J.type==="parallel")return Nq(J).every((Z)=>X8(q,Z));return J.type==="final"}var Z6=(q)=>q[0]===h3;function AQ(q,J){return q.transitions.get(J)||[...q.transitions.keys()].filter((Q)=>{if(Q===v3)return!0;if(!Q.endsWith(".*"))return!1;let $=Q.split("."),W=J.split(".");for(let Y=0;Y<$.length;Y++){let z=$[Y],X=W[Y];if(z==="*")return Y===$.length-1;if(z!==X)return!1}return!0}).sort((Q,$)=>$.length-Q.length).flatMap((Q)=>q.transitions.get(Q))}function RQ(q){let J=q.config.after;if(!J)return[];let Z=($)=>{let W=y3($,q.id),Y=W.type;return q.entry.push(IJ(W,{id:Y,delay:$})),q.exit.push(BJ(Y)),Y};return Object.keys(J).flatMap(($)=>{let W=J[$],Y=typeof W==="string"?{target:W}:W,z=Number.isNaN(+$)?$:+$,X=Z(z);return V1(Y).map((w)=>({...w,event:X,delay:z}))}).map(($)=>{let{delay:W}=$;return{...O1(q,$.event,$),delay:W}})}function O1(q,J,Z){let Q=KQ(Z.target),$=Z.reenter??!1,W=e3(q,Q),Y={...Z,actions:V1(Z.actions),guard:Z.guard,target:W,source:q,reenter:$,eventType:J,toJSON:()=>({...Y,source:`#${q.id}`,target:W?W.map((z)=>`#${z.id}`):void 0})};return Y}function PQ(q){let J=new Map;if(q.config.on)for(let Z of Object.keys(q.config.on)){if(Z===FJ)throw Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let Q=q.config.on[Z];J.set(Z,c1(Q).map(($)=>O1(q,Z,$)))}if(q.config.onDone){let Z=`xstate.done.state.${q.id}`;J.set(Z,c1(q.config.onDone).map((Q)=>O1(q,Z,Q)))}for(let Z of q.invoke){if(Z.onDone){let Q=`xstate.done.actor.${Z.id}`;J.set(Q,c1(Z.onDone).map(($)=>O1(q,Q,$)))}if(Z.onError){let Q=`xstate.error.actor.${Z.id}`;J.set(Q,c1(Z.onError).map(($)=>O1(q,Q,$)))}if(Z.onSnapshot){let Q=`xstate.snapshot.${Z.id}`;J.set(Q,c1(Z.onSnapshot).map(($)=>O1(q,Q,$)))}}for(let Z of q.after){let Q=J.get(Z.eventType);if(!Q)Q=[],J.set(Z.eventType,Q);Q.push(Z)}return J}function EQ(q,J){let Z=typeof J==="string"?q.states[J]:J?q.states[J.target]:void 0;if(!Z&&J)throw Error(`Initial state node "${J}" not found on parent state node #${q.id}`);let Q={source:q,actions:!J||typeof J==="string"?[]:V1(J.actions),eventType:null,reenter:!1,target:Z?[Z]:[],toJSON:()=>({...Q,source:`#${q.id}`,target:Z?[`#${Z.id}`]:[]})};return Q}function e3(q,J){if(J===void 0)return;return J.map((Z)=>{if(typeof Z!=="string")return Z;if(Z6(Z))return q.machine.getStateNodeById(Z);let Q=Z[0]===XJ;if(Q&&!q.parent)return tq(q,Z.slice(1));let $=Q?q.key+Z:Z;if(q.parent)try{return tq(q.parent,$)}catch(W){throw Error(`Invalid transition definition for state node '${q.id}':
15
- ${W.message}`)}else throw Error(`Invalid target: "${Z}" is not a valid target from the root node. Did you mean ".${Z}"?`)})}function xQ(q){let J=KQ(q.config.target);if(!J)return q.parent.initial;return{target:J.map((Z)=>typeof Z==="string"?tq(q.parent,Z):Z)}}function p1(q){return q.type==="history"}function _Q(q){let J=KJ(q);for(let Z of J)for(let Q of q6(Z,q))J.add(Q);return J}function KJ(q){let J=new Set;function Z(Q){if(J.has(Q))return;if(J.add(Q),Q.type==="compound")Z(Q.initial.target[0]);else if(Q.type==="parallel")for(let $ of Nq(Q))Z($)}return Z(q),J}function Vq(q,J){if(Z6(J))return q.machine.getStateNodeById(J);if(!q.states)throw Error(`Unable to retrieve child state '${J}' from '${q.id}'; no child states exist.`);let Z=q.states[J];if(!Z)throw Error(`Child state '${J}' does not exist on '${q.id}'`);return Z}function tq(q,J){if(typeof J==="string"&&Z6(J))try{return q.machine.getStateNodeById(J)}catch{}let Z=Y8(J).slice(),Q=q;while(Z.length){let $=Z.shift();if(!$.length)break;Q=Vq(Q,$)}return Q}function Dq(q,J){if(typeof J==="string"){let $=q.states[J];if(!$)throw Error(`State '${J}' does not exist on '${q.id}'`);return[q,$]}let Z=Object.keys(J),Q=Z.map(($)=>Vq(q,$)).filter(Boolean);return[q.machine.root,q].concat(Q,Z.reduce(($,W)=>{let Y=Vq(q,W);if(!Y)return $;let z=Dq(Y,J[W]);return $.concat(z)},[]))}function q2(q,J,Z,Q){let W=Vq(q,J).next(Z,Q);if(!W||!W.length)return q.next(Z,Q);return W}function J2(q,J,Z,Q){let $=Object.keys(J),W=Vq(q,$[0]),Y=F8(W,J[$[0]],Z,Q);if(!Y||!Y.length)return q.next(Z,Q);return Y}function Z2(q,J,Z,Q){let $=[];for(let W of Object.keys(J)){let Y=J[W];if(!Y)continue;let z=Vq(q,W),X=F8(z,Y,Z,Q);if(X)$.push(...X)}if(!$.length)return q.next(Z,Q);return $}function F8(q,J,Z,Q){if(typeof J==="string")return q2(q,J,Z,Q);if(Object.keys(J).length===1)return J2(q,J,Z,Q);return Z2(q,J,Z,Q)}function Q2(q){return Object.keys(q.states).map((J)=>q.states[J]).filter((J)=>J.type==="history")}function C1(q,J){let Z=q;while(Z.parent&&Z.parent!==J)Z=Z.parent;return Z.parent===J}function $2(q,J){let Z=new Set(q),Q=new Set(J);for(let $ of Z)if(Q.has($))return!0;for(let $ of Q)if(Z.has($))return!0;return!1}function kQ(q,J,Z){let Q=new Set;for(let $ of q){let W=!1,Y=new Set;for(let z of Q)if($2(wJ([$],J,Z),wJ([z],J,Z)))if(C1($.source,z.source))Y.add(z);else{W=!0;break}if(!W){for(let z of Y)Q.delete(z);Q.add($)}}return Array.from(Q)}function W2(q){let[J,...Z]=q;for(let Q of q6(J,void 0))if(Z.every(($)=>C1($,Q)))return Q}function jJ(q,J){if(!q.target)return[];let Z=new Set;for(let Q of q.target)if(p1(Q))if(J[Q.id])for(let $ of J[Q.id])Z.add($);else for(let $ of jJ(xQ(Q),J))Z.add($);else Z.add(Q);return[...Z]}function OQ(q,J){let Z=jJ(q,J);if(!Z)return;if(!q.reenter&&Z.every(($)=>$===q.source||C1($,q.source)))return q.source;let Q=W2(Z.concat(q.source));if(Q)return Q;if(q.reenter)return;return q.source.machine.root}function wJ(q,J,Z){let Q=new Set;for(let $ of q)if($.target?.length){let W=OQ($,Z);if($.reenter&&$.source===W)Q.add(W);for(let Y of J)if(C1(Y,W))Q.add(Y)}return[...Q]}function Y2(q,J){if(q.length!==J.size)return!1;for(let Z of q)if(!J.has(Z))return!1;return!0}function W8(q,J,Z,Q,$,W){if(!q.length)return J;let Y=new Set(J._nodes),z=J.historyValue,X=kQ(q,Y,z),w=J;if(!$)[w,z]=F2(w,Q,Z,X,Y,z,W,Z.actionExecutor);w=n1(w,Q,Z,X.flatMap((_)=>_.actions),W,void 0),w=w2(w,Q,Z,X,Y,W,z,$);let F=[...Y];if(w.status==="done")w=n1(w,Q,Z,F.sort((_,G)=>G.order-_.order).flatMap((_)=>_.exit),W,void 0);try{if(z===J.historyValue&&Y2(J._nodes,Y))return w;return b1(w,{_nodes:F,historyValue:z})}catch(_){throw _}}function z2(q,J,Z,Q,$){if(Q.output===void 0)return;let W=YJ($.id,$.output!==void 0&&$.parent?zJ($.output,q.context,J,Z.self):void 0);return zJ(Q.output,q.context,W,Z.self)}function w2(q,J,Z,Q,$,W,Y,z){let X=q,w=new Set,F=new Set;if(X2(Q,Y,F,w),z)F.add(q.machine.root);let _=new Set;for(let G of[...w].sort((B,A)=>B.order-A.order)){$.add(G);let B=[];B.push(...G.entry);for(let A of G.invoke)B.push(DJ(A.src,{...A,syncSnapshot:!!A.onSnapshot}));if(F.has(G)){let A=G.initial.actions;B.push(...A)}if(X=n1(X,J,Z,B,W,G.invoke.map((A)=>A.id)),G.type==="final"){let A=G.parent,f=A?.type==="parallel"?A:A?.parent,e=f||G;if(A?.type==="compound")W.push(YJ(A.id,G.output!==void 0?zJ(G.output,X.context,J,Z.self):void 0));while(f?.type==="parallel"&&!_.has(f)&&X8($,f))_.add(f),W.push(YJ(f.id)),e=f,f=f.parent;if(f)continue;X=b1(X,{status:"done",output:z2(X,J,Z,X.machine.root,e)})}}return X}function X2(q,J,Z,Q){for(let $ of q){let W=OQ($,J);for(let z of $.target||[]){if(!p1(z)&&($.source!==z||$.source!==W||$.reenter))Q.add(z),Z.add(z);Gq(z,J,Z,Q)}let Y=jJ($,J);for(let z of Y){let X=q6(z,W);if(W?.type==="parallel")X.push(W);CQ(Q,J,Z,X,!$.source.parent&&$.reenter?void 0:W)}}}function Gq(q,J,Z,Q){if(p1(q))if(J[q.id]){let $=J[q.id];for(let W of $)Q.add(W),Gq(W,J,Z,Q);for(let W of $)$J(W,q.parent,Q,J,Z)}else{let $=xQ(q);for(let W of $.target){if(Q.add(W),$===q.parent?.initial)Z.add(q.parent);Gq(W,J,Z,Q)}for(let W of $.target)$J(W,q.parent,Q,J,Z)}else if(q.type==="compound"){let[$]=q.initial.target;if(!p1($))Q.add($),Z.add($);Gq($,J,Z,Q),$J($,q,Q,J,Z)}else if(q.type==="parallel"){for(let $ of Nq(q).filter((W)=>!p1(W)))if(![...Q].some((W)=>C1(W,$))){if(!p1($))Q.add($),Z.add($);Gq($,J,Z,Q)}}}function CQ(q,J,Z,Q,$){for(let W of Q){if(!$||C1(W,$))q.add(W);if(W.type==="parallel"){for(let Y of Nq(W).filter((z)=>!p1(z)))if(![...q].some((z)=>C1(z,Y)))q.add(Y),Gq(Y,J,Z,q)}}}function $J(q,J,Z,Q,$){CQ(Z,Q,$,q6(q,J))}function F2(q,J,Z,Q,$,W,Y,z){let X=q,w=wJ(Q,$,W);w.sort((_,G)=>G.order-_.order);let F;for(let _ of w)for(let G of Q2(_)){let B;if(G.history==="deep")B=(A)=>UJ(A)&&C1(A,_);else B=(A)=>{return A.parent===_};F??={...W},F[G.id]=Array.from($).filter(B)}for(let _ of w)X=n1(X,J,Z,[..._.exit,..._.invoke.map((G)=>w8(G.id))],Y,void 0),$.delete(_);return[X,F||W]}function _2(q,J){return q.implementations.actions[J]}function bQ(q,J,Z,Q,$,W){let{machine:Y}=q,z=q;for(let X of Q){let w=typeof X==="function",F=w?X:_2(Y,typeof X==="string"?X:X.type),_={context:z.context,event:J,self:Z.self,system:Z.system},G=w||typeof X==="string"?void 0:("params"in X)?typeof X.params==="function"?X.params({context:z.context,event:J}):X.params:void 0;if(!F||!("resolve"in F)){Z.actionExecutor({type:typeof X==="string"?X:typeof X==="object"?X.type:X.name||"(anonymous)",info:_,params:G,exec:F});continue}let B=F,[A,f,e]=B.resolve(Z,z,_,G,F,$);if(z=A,"retryResolve"in B)W?.push([B,f]);if("execute"in B)Z.actionExecutor({type:B.type,info:_,params:f,exec:B.execute.bind(null,Z,f)});if(e)z=bQ(z,J,Z,e,$,W)}return z}function n1(q,J,Z,Q,$,W){let Y=W?[]:void 0,z=bQ(q,J,Z,Q,{internalQueue:$,deferredActorIds:W},Y);return Y?.forEach(([X,w])=>{X.retryResolve(Z,z,w)}),z}function _8(q,J,Z,Q){let $=q,W=[];function Y(w,F,_){Z.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:Z.self,event:F,snapshot:w,_transitions:_}),W.push(w)}if(J.type===s1)return $=b1(HQ($,J,Z),{status:"stopped"}),Y($,J,[]),{snapshot:$,microstates:W};let z=J;if(z.type!==NQ){let w=z,F=m3(w),_=GQ(w,$);if(F&&!_.length)return $=b1(q,{status:"error",error:w.error}),Y($,w,[]),{snapshot:$,microstates:W};$=W8(_,q,Z,z,!1,Q),Y($,w,_)}let X=!0;while($.status==="active"){let w=X?H2($,z):[],F=w.length?$:void 0;if(!w.length){if(!Q.length)break;z=Q.shift(),w=GQ(z,$)}$=W8(w,$,Z,z,!1,Q),X=$!==F,Y($,z,w)}if($.status!=="active")HQ($,z,Z);return{snapshot:$,microstates:W}}function HQ(q,J,Z){return n1(q,J,Z,Object.values(q.children).map((Q)=>w8(Q)),[],void 0)}function GQ(q,J){return J.machine.getTransitionData(J,q)}function H2(q,J){let Z=new Set,Q=q._nodes.filter(UJ);for(let $ of Q)q:for(let W of[$].concat(q6($,void 0))){if(!W.always)continue;for(let Y of W.always)if(Y.guard===void 0||Bq(Y.guard,q.context,J,q)){Z.add(Y);break q}}return kQ(Array.from(Z),new Set(q._nodes),q.historyValue)}function TQ(q,J){let Z=J6(Dq(q,J));return LQ(q,[...Z])}function MQ(q){return!!q&&typeof q==="object"&&"machine"in q&&"value"in q}var G2=function(J){return HJ(J,this.value)},N2=function(J){return this.tags.has(J)},V2=function(J){let Z=this.machine.getTransitionData(this,J);return!!Z?.length&&Z.some((Q)=>Q.target!==void 0||Q.actions.length)},B2=function(){let{_nodes:J,tags:Z,machine:Q,getMeta:$,toJSON:W,can:Y,hasTag:z,matches:X,...w}=this;return{...w,tags:Array.from(Z)}},D2=function(){return this._nodes.reduce((J,Z)=>{if(Z.meta!==void 0)J[Z.id]=Z.meta;return J},{})};function Q6(q,J){return{status:q.status,output:q.output,error:q.error,machine:J,context:q.context,_nodes:q._nodes,value:LQ(J.root,q._nodes),tags:new Set(q._nodes.flatMap((Z)=>Z.tags)),children:q.children,historyValue:q.historyValue||{},matches:G2,hasTag:N2,can:V2,getMeta:D2,toJSON:B2}}function b1(q,J={}){return Q6({...q,...J},q.machine)}function fQ(q,J){let{_nodes:Z,tags:Q,machine:$,children:W,context:Y,can:z,hasTag:X,matches:w,getMeta:F,toJSON:_,...G}=q,B={};for(let f in W){let e=W[f];B[f]={snapshot:e.getPersistedSnapshot(J),src:e.src,systemId:e._systemId,syncSnapshot:e._syncSnapshot}}return{...G,context:SQ(Y),children:B}}function SQ(q){let J;for(let Z in q){let Q=q[Z];if(Q&&typeof Q==="object")if("sessionId"in Q&&"send"in Q&&"ref"in Q)J??=Array.isArray(q)?q.slice():{...q},J[Z]={xstate$$type:z8,id:Q.id};else{let $=SQ(Q);if($!==Q)J??=Array.isArray(q)?q.slice():{...q},J[Z]=$}}return J??q}function U2(q,J,Z,Q,{event:$,id:W,delay:Y},{internalQueue:z}){let X=J.machine.implementations.delays;if(typeof $==="string")throw Error(`Only event objects may be used with raise; use raise({ type: "${$}" }) instead`);let w=typeof $==="function"?$(Z,Q):$,F;if(typeof Y==="string"){let _=X&&X[Y];F=typeof _==="function"?_(Z,Q):_}else F=typeof Y==="function"?Y(Z,Q):Y;if(typeof F!=="number")z.push(w);return[J,{event:w,id:W,delay:F},void 0]}function K2(q,J){let{event:Z,delay:Q,id:$}=J;if(typeof Q==="number"){q.defer(()=>{let W=q.self;q.system.scheduler.schedule(W,W,Z,Q,$)});return}}function IJ(q,J){function Z(Q,$){}return Z.type="xstate.raise",Z.event=q,Z.id=J?.id,Z.delay=J?.delay,Z.resolve=U2,Z.execute=K2,Z}function lQ(q,J){return{config:q,transition:(Z,Q,$)=>{return{...Z,context:q(Z.context,Q,$)}},getInitialSnapshot:(Z,Q)=>{return{status:"active",output:void 0,error:void 0,context:typeof J==="function"?J({input:Q}):J}},getPersistedSnapshot:(Z)=>Z,restoreSnapshot:(Z)=>Z}}var hQ=new WeakMap;function LJ(q){return{config:q,start:(Z,Q)=>{let{self:$,system:W,emit:Y}=Q,z={receivers:void 0,dispose:void 0};hQ.set($,z),z.dispose=q({input:Z.input,system:W,self:$,sendBack:(X)=>{if($.getSnapshot().status==="stopped")return;if($._parent)W._relay($,$._parent,X)},receive:(X)=>{z.receivers??=new Set,z.receivers.add(X)},emit:Y})},transition:(Z,Q,$)=>{let W=hQ.get($.self);if(Q.type===s1)return Z={...Z,status:"stopped",error:void 0},W.dispose?.(),Z;return W.receivers?.forEach((Y)=>Y(Q)),Z},getInitialSnapshot:(Z,Q)=>{return{status:"active",output:void 0,error:void 0,input:Q}},getPersistedSnapshot:(Z)=>Z,restoreSnapshot:(Z)=>Z}}var vQ="xstate.observable.next",yQ="xstate.observable.error",uQ="xstate.observable.complete";function O0(q){return{config:q,transition:(Z,Q)=>{if(Z.status!=="active")return Z;switch(Q.type){case vQ:return{...Z,context:Q.data};case yQ:return{...Z,status:"error",error:Q.data,input:void 0,_subscription:void 0};case uQ:return{...Z,status:"done",input:void 0,_subscription:void 0};case s1:return Z._subscription.unsubscribe(),{...Z,status:"stopped",input:void 0,_subscription:void 0};default:return Z}},getInitialSnapshot:(Z,Q)=>{return{status:"active",output:void 0,error:void 0,context:void 0,input:Q,_subscription:void 0}},start:(Z,{self:Q,system:$,emit:W})=>{if(Z.status==="done")return;Z._subscription=q({input:Z.input,system:$,self:Q,emit:W}).subscribe({next:(Y)=>{$._relay(Q,Q,{type:vQ,data:Y})},error:(Y)=>{$._relay(Q,Q,{type:yQ,data:Y})},complete:()=>{$._relay(Q,Q,{type:uQ})}})},getPersistedSnapshot:({_subscription:Z,...Q})=>Q,restoreSnapshot:(Z)=>({...Z,_subscription:void 0})}}var gQ="xstate.promise.resolve",mQ="xstate.promise.reject",H8=new WeakMap;function l(q){return{config:q,transition:(Z,Q,$)=>{if(Z.status!=="active")return Z;switch(Q.type){case gQ:{let W=Q.data;return{...Z,status:"done",output:W,input:void 0}}case mQ:return{...Z,status:"error",error:Q.data,input:void 0};case s1:return H8.get($.self)?.abort(),{...Z,status:"stopped",input:void 0};default:return Z}},start:(Z,{self:Q,system:$,emit:W})=>{if(Z.status!=="active")return;let Y=new AbortController;H8.set(Q,Y),Promise.resolve(q({input:Z.input,system:$,self:Q,signal:Y.signal,emit:W})).then((X)=>{if(Q.getSnapshot().status!=="active")return;H8.delete(Q),$._relay(Q,Q,{type:gQ,data:X})},(X)=>{if(Q.getSnapshot().status!=="active")return;H8.delete(Q),$._relay(Q,Q,{type:mQ,data:X})})},getInitialSnapshot:(Z,Q)=>{return{status:"active",output:void 0,error:void 0,input:Q}},getPersistedSnapshot:(Z)=>Z,restoreSnapshot:(Z)=>Z}}var GV=lQ((q)=>{return},void 0);function j2(q,{machine:J,context:Z},Q,$){let W=(Y,z)=>{if(typeof Y==="string"){let X=eq(J,Y);if(!X)throw Error(`Actor logic '${Y}' not implemented in machine '${J.id}'`);let w=t0(X,{id:z?.id,parent:q.self,syncSnapshot:z?.syncSnapshot,input:typeof z?.input==="function"?z.input({context:Z,event:Q,self:q.self}):z?.input,src:Y,systemId:z?.systemId});return $[w.id]=w,w}else return t0(Y,{id:z?.id,parent:q.self,syncSnapshot:z?.syncSnapshot,input:z?.input,src:Y,systemId:z?.systemId})};return(Y,z)=>{let X=W(Y,z);return $[X.id]=X,q.defer(()=>{if(X._processingStatus===g0.Stopped)return;X.start()}),X}}function I2(q,J,Z,Q,{assignment:$}){if(!J.context)throw Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");let W={},Y={context:J.context,event:Z.event,spawn:j2(q,J,Z.event,W),self:q.self,system:q.system},z={};if(typeof $==="function")z=$(Y,Q);else for(let w of Object.keys($)){let F=$[w];z[w]=typeof F==="function"?F(Y,Q):F}let X=Object.assign({},J.context,z);return[b1(J,{context:X,children:Object.keys(W).length?{...J.children,...W}:J.children}),void 0,void 0]}function N(q){function J(Z,Q){}return J.type="xstate.assign",J.assignment=q,J.resolve=I2,J}function L2(q,J,Z,Q,{event:$}){let W=typeof $==="function"?$(Z,Q):$;return[J,{event:W},void 0]}function A2(q,{event:J}){q.defer(()=>q.emit(J))}function AJ(q){function J(Z,Q){}return J.type="xstate.emit",J.event=q,J.resolve=L2,J.execute=A2,J}var dQ=new WeakMap;function Uq(q,J,Z){let Q=dQ.get(q);if(!Q)Q={[J]:Z()},dQ.set(q,Q);else if(!(J in Q))Q[J]=Z();return Q[J]}var R2={},$6=(q)=>{if(typeof q==="string")return{type:q};if(typeof q==="function"){if("resolve"in q)return{type:q.type};return{type:q.name}}return q};class RJ{constructor(q,J){if(this.config=q,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=J._parent,this.key=J._key,this.machine=J._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(XJ),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?GJ(this.config.states,(Z,Q)=>{return new RJ(Z,{_parent:this,_key:Q,_machine:this.machine})}):R2,this.type==="compound"&&!this.config.initial)throw Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=V1(this.config.entry).slice(),this.exit=V1(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=V1(q.tags).slice()}_initialize(){if(this.transitions=PQ(this),this.config.always)this.always=c1(this.config.always).map((q)=>O1(this,FJ,q));Object.keys(this.states).forEach((q)=>{this.states[q]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map($6),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((q)=>`#${q.id}`),source:`#${this.id}`,actions:this.initial.actions.map($6),eventType:null})}:void 0,history:this.history,states:GJ(this.states,(q)=>{return q.definition}),on:this.on,transitions:[...this.transitions.values()].flat().map((q)=>({...q,actions:q.actions.map($6)})),entry:this.entry.map($6),exit:this.exit.map($6),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Uq(this,"invoke",()=>V1(this.config.invoke).map((q,J)=>{let{src:Z,systemId:Q}=q,$=q.id??NJ(this.id,J),W=typeof Z==="string"?Z:`xstate.invoke.${NJ(this.id,J)}`;return{...q,src:W,id:$,systemId:Q,toJSON(){let{onDone:Y,onError:z,...X}=q;return{...X,type:"xstate.invoke",src:W,id:$}}}}))}get on(){return Uq(this,"on",()=>{return[...this.transitions].flatMap(([J,Z])=>Z.map((Q)=>[J,Q])).reduce((J,[Z,Q])=>{return J[Z]=J[Z]||[],J[Z].push(Q),J},{})})}get after(){return Uq(this,"delayedTransitions",()=>RQ(this))}get initial(){return Uq(this,"initial",()=>EQ(this,this.config.initial))}next(q,J){let Z=J.type,Q=[],$,W=Uq(this,`candidates-${Z}`,()=>AQ(this,Z));for(let Y of W){let{guard:z}=Y,X=q.context,w=!1;try{w=!z||Bq(z,X,J,q)}catch(F){let _=typeof z==="string"?z:typeof z==="object"?z.type:void 0;throw Error(`Unable to evaluate guard ${_?`'${_}' `:""}in transition for event '${Z}' in state node '${this.id}':
16
- ${F.message}`)}if(w){Q.push(...Y.actions),$=Y;break}}return $?[$]:void 0}get events(){return Uq(this,"events",()=>{let{states:q}=this,J=new Set(this.ownEvents);if(q)for(let Z of Object.keys(q)){let Q=q[Z];if(Q.states)for(let $ of Q.events)J.add(`${$}`)}return Array.from(J)})}get ownEvents(){let q=new Set([...this.transitions.keys()].filter((J)=>{return this.transitions.get(J).some((Z)=>!(!Z.target&&!Z.actions.length&&!Z.reenter))}));return Array.from(q)}}var P2="#";class PJ{constructor(q,J){this.config=q,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=q.id||"(machine)",this.implementations={actors:J?.actors??{},actions:J?.actions??{},delays:J?.delays??{},guards:J?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new RJ(q,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(q){let{actions:J,guards:Z,actors:Q,delays:$}=this.implementations;return new PJ(this.config,{actions:{...J,...q.actions},guards:{...Z,...q.guards},actors:{...Q,...q.actors},delays:{...$,...q.delays}})}resolveState(q){let J=TQ(this.root,q.value),Z=J6(Dq(this.root,J));return Q6({_nodes:[...Z],context:q.context||{},children:{},status:X8(Z,this.root)?"done":q.status||"active",output:q.output,error:q.error,historyValue:q.historyValue},this)}transition(q,J,Z){return _8(q,J,Z,[]).snapshot}microstep(q,J,Z){return _8(q,J,Z,[]).microstates}getTransitionData(q,J){return F8(this.root,q.value,q,J)||[]}getPreInitialState(q,J,Z){let{context:Q}=this.config,$=Q6({context:typeof Q!=="function"&&Q?Q:{},_nodes:[this.root],children:{},status:"active"},this);if(typeof Q==="function")return n1($,J,q,[N(({spawn:Y,event:z,self:X})=>Q({spawn:Y,input:z.input,self:X}))],Z,void 0);return $}getInitialSnapshot(q,J){let Z=_J(J),Q=[],$=this.getPreInitialState(q,Z,Q),W=W8([{target:[...KJ(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],$,q,Z,!0,Q),{snapshot:Y}=_8(W,Z,q,Q);return Y}start(q){Object.values(q.children).forEach((J)=>{if(J.getSnapshot().status==="active")J.start()})}getStateNodeById(q){let J=Y8(q),Z=J.slice(1),Q=Z6(J[0])?J[0].slice(P2.length):J[0],$=this.idMap.get(Q);if(!$)throw Error(`Child state node '#${Q}' does not exist on machine '${this.id}'`);return tq($,Z)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(q,J){return fQ(q,J)}restoreSnapshot(q,J){let Z={},Q=q.children;Object.keys(Q).forEach((z)=>{let X=Q[z],w=X.snapshot,F=X.src,_=typeof F==="string"?eq(this,F):F;if(!_)return;let G=t0(_,{id:z,parent:J.self,syncSnapshot:X.syncSnapshot,snapshot:w,src:F,systemId:X.systemId});Z[z]=G});let $=Q6({...q,children:Z,_nodes:Array.from(J6(Dq(this.root,q.value)))},this),W=new Set;function Y(z,X){if(W.has(z))return;W.add(z);for(let w in z){let F=z[w];if(F&&typeof F==="object"){if("xstate$$type"in F&&F.xstate$$type===z8){z[w]=X[F.id];continue}Y(F,X)}}}return Y($.context,Z),$}}function E2(q,J){return new PJ(q,J)}function i({schemas:q,actors:J,actions:Z,guards:Q,delays:$}){return{createMachine:(W)=>E2({...W,schemas:q},{actors:J,actions:Z,guards:Q,delays:$})}}class G8{_tag="DeviceNotOnboardedError";originalError;constructor(q){this.originalError=Error(q??"Device not onboarded.")}}class B1{_tag="DeviceLockedError";originalError;constructor(q){this.originalError=Error(q??"Device locked.")}}class i1{_tag="UnsupportedFirmwareDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class T1{_tag="RefusedByUserDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class N8{_tag="AppAlreadyInstalledDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class D1{_tag="OutOfMemoryDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class q0{_tag="UnknownDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class EJ{_tag="UnsupportedApplicationDAError";originalError;constructor(q){this.originalError=Error(q??"Application currently not supported.")}}class xJ{_tag="MissingLanguagePackagesForOSDAError";originalError;constructor(q){this.originalError=Error(q??"Missing Language Packages for OS DAError.")}}class kJ{_tag="MissingLanguagePackageDAError";originalError;constructor(q){this.originalError=Error(q??"Missing Language Package DAError.")}}class V8{_tag="DeleteLanguagePackDAError";originalError;constructor(q){this.originalError=Error(q??"Delete language pack failed.")}}class OJ{_tag="NetworkDAError";originalError;constructor(q){this.originalError=Error(q??"Network error.")}}var t=60000;import{first as b2,from as T2,interval as M2,map as f2,switchMap as S2}from"rxjs";import{timeout as h2}from"rxjs/operators";import{Observable as x2,ReplaySubject as k2,share as O2}from"rxjs";var cQ={subscribers:[],error:()=>{},warn:()=>{},info:()=>{},debug:()=>{}},CJ=(q)=>cQ;class a{input;inspect=!1;logger;loggerFactory;constructor(q){this.input=q.input,this.inspect=!!q.inspect,this.logger=q.logger,this.loggerFactory=q.loggerFactory}getLoggerFactory(q){return this.loggerFactory??q.loggerFactory??CJ}_execute(q){let J=this.makeStateMachine(q);return!this.logger&&J.id&&(this.logger=this.getLoggerFactory(q)(J.id)),this._subscribeToStateMachine(J)}_subscribeToStateMachine(q){let J=t0(q,{input:this.input}),Z=new k2,Q=!1,$=(z)=>{let{context:X,status:w,output:F,error:_}=z;if(this.logger&&!Q&&(Q=!0,this.logger.debug("[XStateDeviceAction] Input",{data:{input:X.input}})),this.logger&&(w==="active"||w==="done")){let G=typeof z.value=="string"?z.value:JSON.stringify(z.value);this.logger.debug(`[XStateDeviceAction] State: ${G}`,{data:{internalState:X._internalState,intermediateValue:X.intermediateValue}})}switch(w){case"active":Z.next({status:d1.Pending,intermediateValue:X.intermediateValue});break;case"done":F.caseOf({Left:(G)=>{Z.next({status:d1.Error,error:G})},Right:(G)=>{Z.next({status:d1.Completed,output:G})}}),Z.complete();break;case"error":Z.error(_),Z.complete();break;case"stopped":Z.next({status:d1.Stopped}),Z.complete();break;default:this._exhaustiveMatchingGuard(w)}},W=new x2((z)=>{let X=Z.subscribe(z);return()=>{Y.unsubscribe(),X.unsubscribe(),J.stop()}}),Y=J.subscribe($);return J.start(),{observable:W.pipe(O2()),cancel:()=>{J.stop(),Y.unsubscribe(),$(J.getSnapshot())}}}_exhaustiveMatchingGuard(q){throw console.log("_exhaustiveMatchingGuard status",q),Error(`Unhandled status: ${q}`)}}var B8="BOLOS",C2=["BOLOS","OLOS","OLOS\x00"],a1=(q)=>q!=null&&C2.includes(q);var D8=Object.freeze({GET_APP_AND_VERSION:"os.waitForAppAndVersion.steps.getAppAndVersion",UNLOCK_DEVICE:"os.waitForAppAndVersion.steps.unlockDevice"});var pQ=(q)=>!n(q)&&("errorCode"in q.error)&&q.error.errorCode==="5515",v2=(q)=>!n(q)&&("errorCode"in q.error)&&q.error.errorCode==="6e00";class U8 extends a{makeStateMachine(q){let{getAppAndVersion:J,waitForDeviceUnlock:Z}=this.extractDependencies(q),Q=this.input.unlockTimeout??t;return i({types:{input:{unlockTimeout:Q},context:{},output:{}},actors:{getAppAndVersion:l(J),waitForDeviceUnlock:O0(Z)},guards:{isDeviceLocked:({context:$})=>$._internalState.locked,hasError:({context:$})=>$._internalState.error!==null},actions:{assignErrorDeviceLocked:N({_internalState:($)=>({...$.context._internalState,error:new B1})}),assignErrorFromEvent:N({_internalState:($)=>({...$.context._internalState,error:$.event.error})})}}).createMachine({id:"WaitForAppAndVersionDeviceAction",initial:"GetAppAndVersion",context:($)=>({input:{unlockTimeout:$.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:D8.GET_APP_AND_VERSION},_internalState:{appAndVersion:null,locked:!1,error:null}}),states:{GetAppAndVersion:{entry:N({intermediateValue:($)=>({...$.context.intermediateValue,step:D8.GET_APP_AND_VERSION,requiredUserInteraction:k.None})}),invoke:{src:"getAppAndVersion",onDone:{target:"CheckGetAppAndVersionResult",actions:N({_internalState:($)=>n($.event.output)?{...$.context._internalState,locked:!1,appAndVersion:$.event.output.data}:pQ($.event.output)?{...$.context._internalState,locked:!0}:v2($.event.output)?{...$.context._internalState,locked:!1,appAndVersion:{name:B8,version:"0.0.0"}}:{...$.context._internalState,error:$.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CheckGetAppAndVersionResult:{always:[{guard:"hasError",target:"Error"},{guard:"isDeviceLocked",target:"AwaitingForDeviceUnlocked"},{target:"Success"}]},AwaitingForDeviceUnlocked:{entry:N({intermediateValue:($)=>({...$.context.intermediateValue,requiredUserInteraction:k.UnlockDevice,step:D8.UNLOCK_DEVICE})}),invoke:{id:"AwaitingForDeviceUnlocked",src:"waitForDeviceUnlock",input:($)=>({unlockTimeout:Q}),onDone:{target:"GetAppAndVersion",actions:N({_internalState:($)=>({...$.context._internalState,locked:!1})})},onError:{target:"Error",actions:"assignErrorDeviceLocked"}}},Success:{type:"final"},Error:{type:"final"}},output:($)=>{let{context:W}=$,{error:Y,appAndVersion:z}=W._internalState;return Y?K(Y):I(z)}})}extractDependencies(q){return{getAppAndVersion:()=>q.sendCommand(new i0),waitForDeviceUnlock:({input:J})=>M2(1000).pipe(S2(()=>T2(q.sendCommand(new i0))),b2((Z)=>!pQ(Z)),f2(()=>{}),h2(J.unlockTimeout))}}}var d=((q)=>(q[q.Connected=0]="Connected",q[q.ReadyWithoutSecureChannel=1]="ReadyWithoutSecureChannel",q[q.ReadyWithSecureChannel=2]="ReadyWithSecureChannel",q))(d||{});var bJ=Object.freeze({WAIT_FOR_APP_AND_VERSION:"os.getDeviceStatus.steps.waitForAppAndVersion",ONBOARD_CHECK:"os.getDeviceStatus.steps.onboardCheck"});var y2=(q)=>({mcu:q.mcuSephVersion,bootloader:q.mcuBootloaderVersion,os:q.seVersion,metadata:q});class Kq extends a{makeStateMachine(q){let{getOsVersion:J,getDeviceSessionState:Z,setDeviceSessionState:Q}=this.extractDependencies(q),$=this.input.unlockTimeout??t,W=this.input.allowNonOnboardedDevice??!0,Y=(X)=>{let w=Z();w.sessionStateType!==d.Connected&&Q({...w,firmwareVersion:y2(X),isSecureConnectionAllowed:X.secureElementFlags.isSecureConnectionAllowed})},z=new U8({input:{unlockTimeout:$}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:$,allowNonOnboardedDevice:W},context:{},output:{}},actors:{waitForAppAndVersion:z,getOsVersion:l(J)},guards:{isCurrentAppBolos:({context:X})=>a1(X._internalState.currentApp),isOnboardedFromOsVersion:({context:X})=>X._internalState.osVersionMetadata?.secureElementFlags.isOnboarded===!0,isAllowedNonOnboardedDevice:({context:X})=>{let w=X._internalState.osVersionMetadata?.secureElementFlags;return X.input.allowNonOnboardedDevice===!0&&w?.isOnboarded===!1},hasError:({context:X})=>X._internalState.error!==null},actions:{assignErrorDeviceNotOnboarded:N({_internalState:(X)=>({...X.context._internalState,error:new G8})}),assignErrorFromEvent:N({_internalState:(X)=>({...X.context._internalState,error:X.event.error})})}}).createMachine({id:"GetDeviceStatusDeviceAction",initial:"DeviceReady",context:(X)=>{let w=Z(),{sessionStateType:F}=w;return{input:{unlockTimeout:X.input.unlockTimeout,allowNonOnboardedDevice:X.input.allowNonOnboardedDevice??!0},intermediateValue:{requiredUserInteraction:k.None,step:bJ.WAIT_FOR_APP_AND_VERSION},_internalState:{onboarded:!1,currentApp:F===d.ReadyWithoutSecureChannel?w.currentApp.name:null,currentAppVersion:null,osVersionMetadata:null,error:null}}},states:{DeviceReady:{always:{target:"WaitForAppAndVersion"}},WaitForAppAndVersion:{invoke:{src:"waitForAppAndVersion",input:(X)=>({unlockTimeout:X.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:X.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"WaitForAppAndVersionResultCheck",actions:N({_internalState:(X)=>X.event.output.caseOf({Left:(w)=>({...X.context._internalState,error:w}),Right:(w)=>{let F=Z();return F.sessionStateType!==d.Connected?Q({...F,currentApp:w}):Q({deviceModelId:F.deviceModelId,sessionStateType:d.ReadyWithoutSecureChannel,deviceStatus:u0.CONNECTED,currentApp:w,installedApps:[],isSecureConnectionAllowed:!1}),{...X.context._internalState,currentApp:w.name,currentAppVersion:w.version}}})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},WaitForAppAndVersionResultCheck:{always:[{guard:"hasError",target:"Error"},{target:"OnboardingCheck"}]},OnboardingCheck:{entry:N({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:k.None,step:bJ.ONBOARD_CHECK})}),always:[{guard:"isCurrentAppBolos",target:"GetOsVersion"},{target:"Success",actions:N({_internalState:(X)=>({...X.context._internalState,onboarded:!0})})}]},GetOsVersion:{invoke:{src:"getOsVersion",onDone:{target:"OnboardingResultCheck",actions:N({_internalState:(X)=>n(X.event.output)?(Y(X.event.output.data),{...X.context._internalState,osVersionMetadata:X.event.output.data}):{...X.context._internalState,error:X.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},OnboardingResultCheck:{always:[{guard:"hasError",target:"Error"},{guard:"isOnboardedFromOsVersion",target:"Success",actions:N({_internalState:(X)=>({...X.context._internalState,onboarded:!0})})},{guard:"isAllowedNonOnboardedDevice",target:"Success"},{target:"Error",actions:"assignErrorDeviceNotOnboarded"}]},Success:{type:"final"},Error:{type:"final"}},output:(X)=>{let{context:w}=X,{error:F,currentApp:_,currentAppVersion:G}=w._internalState;return F?K(F):I({currentApp:_,currentAppVersion:G})}})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new T0),getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}class A0{_tag="GeneralDmkError";originalError;constructor(q){q instanceof Error?this.originalError=q:q!==void 0&&(this.originalError=Error(String(q)))}}class u2 extends A0{constructor(q){super(q);this.err=q}_tag="DeviceAlreadyDiscoveredError"}class g2 extends A0{constructor(q){super(q);this.err=q}_tag="DeviceNotRecognizedError"}class m2 extends A0{constructor(q){super(q);this.err=q}_tag="NoAccessibleDeviceError"}class l2 extends A0{_tag="ConnectionOpeningError";constructor(q){super(q)}}class d2 extends A0{constructor(q){super(q);this.err=q}_tag="UnknownDeviceError"}class o1 extends A0{constructor(q){super(q);this.err=q}_tag="TransportNotSupportedError"}class c2 extends A0{constructor(q){super(q);this.err=q}_tag="SendApduConcurrencyError"}class TJ extends A0{constructor(q){super(q);this.err=q}_tag="SendApduTimeoutError"}class MJ extends A0{constructor(q){super(q);this.err=q}_tag="SendCommandTimeoutError"}class p2 extends A0{constructor(q){super(q);this.err=q}_tag="SendApduEmptyResponseError"}class s2 extends A0{constructor(q){super(q);this.err=q}_tag="DisconnectError"}class n2 extends A0{constructor(q){super(q);this.err=q}_tag="ReconnectionFailedError"}class i2 extends A0{constructor(q){super(q);this.err=q}_tag="DeviceNotInitializedError"}class a2 extends A0{constructor(q){super(q);this.err=q}_tag="NoTransportsProvidedError"}class fJ extends A0{constructor(q){super(q);this.err=q}_tag="TransportAlreadyExistsError"}class r1 extends A0{constructor(q){super(q);this.err=q}_tag="DeviceDisconnectedWhileSendingError"}class W6 extends A0{constructor(q){super(q);this.err=q}_tag="AlreadySendingApduError"}class SJ extends A0{constructor(q){super(q);this.err=q}_tag="DeviceDisconnectedBeforeSendingApdu"}class hJ extends A0{constructor(q){super(q);this.err=q}_tag="NoTransportProvidedError"}var sQ=Object.freeze({LIST_APPS:"os.openApp.steps.listApps",ONBOARD_CHECK:"os.openApp.steps.onboardCheck",GET_DEVICE_STATUS:"os.openApp.steps.getDeviceStatus",DASHBOARD_CHECK:"os.openApp.steps.dashboardCheck",CONFIRM_OPEN_APP:"os.openApp.steps.confirmOpenApp",CLOSE_APP:"os.openApp.steps.closeApp"});class M1 extends a{makeStateMachine(q){let{closeApp:J,openApp:Z,getDeviceSessionState:Q,setDeviceSessionState:$}=this.extractDependencies(q),W=this.input.unlockTimeout??t,Y=new Kq({input:{unlockTimeout:W,allowNonOnboardedDevice:!1}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{closeApp:l(J),openApp:l(Z),getDeviceStatus:Y},guards:{isRequestedAppOpen:({context:z})=>z._internalState.currentlyRunningApp===null?!1:z._internalState.currentlyRunningApp===z.input.appName,isDashboardOpen:({context:z})=>{if(z._internalState.currentlyRunningApp===null)throw Error("context.currentlyRunningApp === null");return a1(z._internalState.currentlyRunningApp)},hasDisconnectedWhileSending:({context:z})=>z._internalState.error!==null&&z._internalState.error instanceof r1,hasError:({context:z})=>z._internalState.error!==null},actions:{assignUserActionNeededOpenApp:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:k.ConfirmOpenApp})}),assignNoUserActionNeeded:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:k.None})}),assignErrorFromEvent:N({_internalState:(z)=>({...z.context._internalState,error:z.event.error})}),assignNoError:N({_internalState:(z)=>({...z.context._internalState,error:null})})}}).createMachine({id:"OpenAppDeviceAction",initial:"DeviceReady",context:({input:z})=>{let X=Q(),{sessionStateType:w}=X;return{input:z,intermediateValue:{requiredUserInteraction:k.None,step:sQ.GET_DEVICE_STATUS},_internalState:{error:null,currentlyRunningApp:w===d.ReadyWithoutSecureChannel?X.currentApp.name:null}}},states:{DeviceReady:{always:{target:"GetDeviceStatus"}},GetDeviceStatus:{invoke:{id:"deviceStatus",src:"getDeviceStatus",input:(z)=>({unlockTimeout:z.context.input.unlockTimeout,allowNonOnboardedDevice:!1}),onSnapshot:{actions:N({intermediateValue:(z)=>z.event.snapshot.context.intermediateValue})},onDone:{target:"CheckDeviceStatus",actions:N({_internalState:(z)=>z.event.output.caseOf({Right:(X)=>{let w=Q();return w.sessionStateType!==d.Connected&&$({...w,currentApp:{name:X.currentApp,version:X.currentAppVersion}}),{...z.context._internalState,currentlyRunningApp:X.currentApp}},Left:(X)=>({...z.context._internalState,currentlyRunningApp:null,error:X})})})},onError:{target:"Error",actions:[N({_internalState:(z)=>({...z.context._internalState,currentlyRunningApp:null})}),"assignErrorFromEvent"]}}},CheckDeviceStatus:{always:[{target:"ApplicationReady",guard:"isRequestedAppOpen",actions:"assignNoError"},{target:"Error",guard:"hasError"},{target:"DashboardCheck"}]},DashboardCheck:{always:[{target:"OpenApplication",guard:"isDashboardOpen"},"CloseApplication"]},OpenApplication:{entry:"assignUserActionNeededOpenApp",exit:"assignNoUserActionNeeded",invoke:{src:"openApp",input:({context:z})=>({appName:z.input.appName}),onDone:{target:"OpenApplicationResultCheck",actions:N({_internalState:(z)=>n(z.event.output)?{...z.context._internalState,currentlyRunningApp:z.context.input.appName}:{...z.context._internalState,error:z.event.output.error}})},onError:{target:"OpenApplicationResultCheck",actions:"assignErrorFromEvent"}}},OpenApplicationResultCheck:{always:[{target:"GetDeviceStatus",guard:"hasDisconnectedWhileSending"},{target:"Error",guard:"hasError"},{target:"GetDeviceStatus"}]},CloseApplication:{invoke:{src:"closeApp",onDone:{target:"CloseApplicationResultCheck",actions:N({_internalState:(z)=>n(z.event.output)?{...z.context._internalState,currentlyRunningApp:B8}:{...z.context._internalState,error:z.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CloseApplicationResultCheck:{always:[{target:"Error",guard:"hasError"},{target:"OpenApplication"}]},ApplicationReady:{always:"Success"},Success:{type:"final",actions:"assignNoError"},Error:{type:"final"}},output:({context:z})=>z._internalState.error?K(z._internalState.error):I(void 0)})}extractDependencies(q){return{closeApp:async()=>q.sendCommand(new wq),openApp:async(J)=>q.sendCommand(new t6({appName:J.input.appName})),getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}var K8=Object.freeze({OPEN_APP:"os.callTaskInApp.steps.openApp",CALL_TASK:"os.callTaskInApp.steps.callTask"});class nQ extends a{makeStateMachine(q){let{callTask:J}=this.extractDependencies(q);return i({types:{input:{},context:{},output:{}},actors:{callTask:l(J),openAppStateMachine:new M1({input:{appName:this.input.appName}}).makeStateMachine(q)},guards:{skipOpenApp:()=>this.input.skipOpenApp,noInternalError:({context:Z})=>Z._internalState.error===null},actions:{assignErrorFromEvent:N({_internalState:(Z)=>({...Z.context._internalState,error:Z.event.error})})}}).createMachine({id:"CallTaskInAppDeviceAction",initial:"InitialState",context:({input:Z})=>({input:Z,intermediateValue:{requiredUserInteraction:k.None,step:K8.OPEN_APP},_internalState:{taskResponse:null,error:null}}),states:{InitialState:{always:[{target:"CallTask",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",input:{appName:this.input.appName},src:"openAppStateMachine",onSnapshot:{actions:N({intermediateValue:(Z)=>Z.event.snapshot.context.intermediateValue})},onDone:{actions:N({_internalState:(Z)=>Z.event.output.caseOf({Right:()=>Z.context._internalState,Left:(Q)=>({...Z.context._internalState,error:Q})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"CallTask",guard:"noInternalError"},"Error"]},CallTask:{entry:N({intermediateValue:{requiredUserInteraction:this.input.requiredUserInteraction,step:K8.CALL_TASK}}),exit:N({intermediateValue:{requiredUserInteraction:k.None,step:K8.CALL_TASK}}),invoke:{id:"callTask",src:"callTask",input:(Z)=>Z.context.input.task,onDone:{target:"CallTaskResultCheck",actions:[N({_internalState:({event:Z,context:Q})=>x1(Z.output)?{...Q._internalState,taskResponse:Z.output.data}:{...Q._internalState,error:Z.output.error}})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CallTaskResultCheck:{always:[{target:"Success",guard:"noInternalError"},"Error"]},Success:{type:"final"},Error:{type:"final"}},output:({context:Z})=>Z._internalState.taskResponse?I(Z._internalState.taskResponse):K(Z._internalState.error||new q0("No error in final state"))})}extractDependencies(q){return{callTask:(J)=>J.input(q)}}}var Y6=Object.freeze({GET_DEVICE_STATUS:"os.goToDashboard.steps.getDeviceStatus",DASHBOARD_CHECK:"os.goToDashboard.steps.dashboardCheck",CLOSE_APP:"os.goToDashboard.steps.closeApp",CONFIRM_DASHBOARD_OPEN:"os.goToDashboard.steps.confirmDashboardOpen"});class M0 extends a{makeStateMachine(q){let{getDeviceSessionState:J,setDeviceSessionState:Z,closeApp:Q,getAppAndVersion:$}=this.extractDependencies(q),W=this.input.unlockTimeout??t,Y=new Kq({input:{unlockTimeout:W}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:W},context:{},output:{}},actors:{getAppAndVersion:l($),closeApp:l(Q),getDeviceStatus:Y},guards:{hasError:({context:z})=>z._internalState.error!==null,isDashboardOpen:({context:z})=>z._internalState.currentApp!==null&&a1(z._internalState.currentApp)},actions:{assignErrorFromEvent:N({_internalState:(z)=>({...z.context._internalState,error:z.event.error})})}}).createMachine({id:"GoToDashboardDeviceAction",initial:"DeviceReady",context:(z)=>{let X=J();return{input:{unlockTimeout:z.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:Y6.GET_DEVICE_STATUS},_internalState:{currentApp:"currentApp"in X?X.currentApp.name:null,error:null}}},states:{DeviceReady:{always:{target:"GetDeviceStatus"}},GetDeviceStatus:{invoke:{id:"deviceStatus",src:"getDeviceStatus",input:(z)=>({unlockTimeout:z.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(z)=>z.event.snapshot.context.intermediateValue})},onDone:{target:"CheckDeviceStatus",actions:N({_internalState:(z)=>z.event.output.caseOf({Right:(X)=>({...z.context._internalState,currentApp:X.currentApp}),Left:(X)=>({...z.context._internalState,error:X})})})}}},CheckDeviceStatus:{always:[{target:"Error",guard:"hasError"},{target:"DashboardCheck"}]},DashboardCheck:{always:[{target:"Success",guard:"isDashboardOpen"},{target:"Error",guard:"hasError"},{target:"Error",guard:(z)=>z.context._internalState.currentApp===null,actions:N({_internalState:(z)=>({...z.context._internalState,error:new q0("currentApp === null")}),intermediateValue:(z)=>({requiredUserInteraction:k.None,step:Y6.DASHBOARD_CHECK})})},{target:"CloseApp"}]},CloseApp:{invoke:{src:"closeApp",onDone:{target:"CloseAppCheck",actions:N({_internalState:(z)=>n(z.event.output)?z.context._internalState:{...z.context._internalState,error:z.event.output.error},intermediateValue:(z)=>({requiredUserInteraction:k.None,step:Y6.CLOSE_APP})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CloseAppCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetAppAndVersion",reenter:!0}]},GetAppAndVersion:{invoke:{src:"getAppAndVersion",onDone:{target:"DashboardCheck",actions:N({_internalState:(z)=>{if(n(z.event.output)){let X=J();return X.sessionStateType!==d.Connected&&Z({...X,currentApp:z.event.output.data}),{...z.context._internalState,currentApp:z.event.output.data.name}}return{...z.context._internalState,error:z.event.output.error}},intermediateValue:(z)=>({requiredUserInteraction:k.None,step:Y6.CONFIRM_DASHBOARD_OPEN})})}}},Success:{type:"final"},Error:{type:"final"}},output:(z)=>z.context._internalState.error?K(z.context._internalState.error):I(void 0)})}extractDependencies(q){return{closeApp:async()=>q.sendCommand(new wq),getAppAndVersion:async()=>q.sendCommand(new i0),getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}var vJ=Object.freeze({GO_TO_DASHBOARD:"os.listApps.steps.goToDashboard",LIST_APPS:"os.listApps.steps.listApps"});class jq extends a{makeStateMachine(q){let{listApps:J}=this.extractDependencies(q),Z=this.input.unlockTimeout??t,Q=new M0({input:{unlockTimeout:Z}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:Z},context:{},output:{}},actors:{listApps:l(J),goToDashboard:Q},guards:{hasError:({context:$})=>$._internalState.error!==null,hasMoreApps:($)=>$.context._internalState.shouldContinue},actions:{assignAllowListApps:N({intermediateValue:($)=>({requiredUserInteraction:k.AllowListApps,step:vJ.LIST_APPS})}),assignErrorFromEvent:N({_internalState:($)=>({...$.context._internalState,error:$.event.error})})}}).createMachine({id:"ListAppsDeviceAction",initial:"DeviceReady",context:($)=>({input:{unlockTimeout:$.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:vJ.GO_TO_DASHBOARD},_internalState:{error:null,apps:[],shouldContinue:!1}}),states:{DeviceReady:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"dashboard",src:"goToDashboard",input:($)=>({unlockTimeout:$.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:($)=>$.event.snapshot.context.intermediateValue})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:($)=>$.event.output.caseOf({Right:()=>$.context._internalState,Left:(W)=>({...$.context._internalState,error:W})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"ListApps"}]},ListApps:{entry:"assignAllowListApps",invoke:{src:"listApps",input:($)=>!1,onDone:{target:"Continue",actions:N({_internalState:($)=>n($.event.output)?{...$.context._internalState,apps:$.context._internalState.apps.concat($.event.output.data),shouldContinue:$.event.output.data.length>=2}:{...$.context._internalState,error:$.event.output.error},intermediateValue:($)=>({...$.context.intermediateValue,requiredUserInteraction:k.None})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListAppsCheck:{always:[{target:"Error",guard:"hasError"},"ListAppsContinue"]},ListAppsContinue:{invoke:{src:"listApps",input:($)=>!0,onDone:{target:"Continue",actions:N({_internalState:($)=>n($.event.output)?{...$.context._internalState,apps:$.context._internalState.apps.concat($.event.output.data),shouldContinue:$.event.output.data.length>=2}:{...$.context._internalState,error:$.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Continue:{always:[{target:"ListAppsContinue",guard:"hasMoreApps"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:($)=>$.context._internalState.error?K($.context._internalState.error):I($.context._internalState.apps)})}extractDependencies(q){return{listApps:async({input:J})=>{let Z=new o6({isContinue:J});return q.sendCommand(Z)}}}}var iQ=k1(_q(),1);class j8{_tag="InvalidGetFirmwareMetadataResponseError";originalError;constructor(q){this.originalError=Error(q??"Invalid Firmware Metadata response error.")}}class z6{_tag="GetApplicationsMetadataTaskError";originalError;constructor(q){this.originalError=Error(q??"Failed to get applications metadata.")}}var o2="0000000000000000000000000000000000000000000000000000000000000000";class yJ{constructor(q,J){this.api=q,this.args=J}async run(){let q=this.args.installedApps.filter((F)=>this.isApplication(F)),J=this.api.getManagerApiService(),Z=q.map((F)=>F.hash),Q=await J.getAppsByHash(Z).chain((F)=>J.getAppList(this.args.firmwareVersion.metadata).map((_)=>({applications:F,catalog:_})));if(Q.isLeft())return n0({error:new z6("Cannot get the application catalog")});let{applications:$,catalog:W}=Q.unsafeCoerce(),Y=$.reduce((F,_,G)=>{if(_!==null)return[...F,_];let B=q[G],A=W.find((f)=>f.versionName===B.name);return A?[...F,A]:F},[]),z=$.filter((F)=>F!==null).reduce((F,_)=>{let G=W.find((B)=>B.versionName===_.versionName);return G&&iQ.gt(G.version,_.version)?[...F,G]:F},[]),X=[];for(let F=0;;F++){let _=await this.api.sendCommand(new r6({firstChunk:F===0}));if(!n(_)||_.data===void 0)break;X=[...X,_.data]}let w=await J.getLanguagePackages(this.args.deviceVersion,this.args.firmware);return w.isRight()?n0({data:{applications:Y,applicationsUpdates:z,installedLanguages:X,catalog:{applications:W,languagePackages:w.extract()}}}):n0({error:new z6("Cannot get the languages catalog")})}isApplication(q){return q.hashCode!==o2}}class uJ{constructor(q){this.api=q}async run(){let q=await this.api.sendCommand(new T0);if(!n(q))return n0({error:q.error});let J={mcu:q.data.mcuSephVersion,bootloader:q.data.mcuBootloaderVersion,os:q.data.seVersion,metadata:q.data},Z=this.api.getManagerApiService(),Q=await Z.getDeviceVersion(q.data).chain((F)=>Z.getFirmwareVersion(q.data,F).map((_)=>({deviceVersion:F,currentFirmware:_})));if(Q.isLeft())return n0({error:new j8});let{deviceVersion:$,currentFirmware:W}=Q.unsafeCoerce(),Y=await this.getAvailableUpdate(Z,W,$,J),z={currentFirmware:W,availableUpdate:Y},X={},w=await this.api.sendCommand(new h6);return n(w)&&(X={size:w.data}),n0({data:{deviceVersion:$,firmware:W,firmwareVersion:J,firmwareUpdateContext:z,customImage:X}})}async getAvailableUpdate(q,J,Z,Q){let $=await q.getLatestFirmwareVersion(J,Z);if($.isLeft())return;let W=$.unsafeCoerce();if(!W.isNothing())return this.getFirmwareUpdate(q,W.unsafeCoerce(),Q)}async getFirmwareUpdate(q,J,Z){let Q=await q.getNextFirmwareVersion(J);if(Q.isLeft())return;let $=await q.getMcuList();if($.isLeft())return;let W=Q.unsafeCoerce(),Y=$.unsafeCoerce().find((z)=>z.name===Z.mcu);return{osuFirmware:J,finalFirmware:W,mcuUpdateRequired:Y===void 0||!W.mcuVersions.includes(Y.id)}}}function I8(q){return Array.isArray(q)&&q.every((J)=>typeof J=="object"&&J!==null&&("flags"in J)&&("hash"in J)&&("hash_code_data"in J)&&("name"in J)&&typeof J.flags=="number"&&typeof J.hash=="string"&&typeof J.hash_code_data=="string"&&typeof J.name=="string")}var Iq=null;if(typeof WebSocket<"u")Iq=WebSocket;else if(typeof MozWebSocket<"u")Iq=MozWebSocket;else if(typeof global<"u")Iq=global.WebSocket||global.MozWebSocket;else if(typeof window<"u")Iq=window.WebSocket||window.MozWebSocket;else if(typeof self<"u")Iq=self.WebSocket||self.MozWebSocket;var L8=Iq;import{Observable as Gw}from"rxjs";var r2=((q)=>(q.GenuineCheck="GenuineCheck",q.ListInstalledApps="ListInstalledApps",q.UpdateMcu="UpdateMcu",q.UpdateFirmware="UpdateFirmware",q.InstallApp="InstallApp",q.UninstallApp="UninstallApp",q))(r2||{}),U1=((q)=>(q.EXCHANGE="exchange",q.BULK="bulk",q.ERROR="error",q.WARNING="warning",q.SUCCESS="success",q))(U1||{}),A8=((q)=>(q.SUCCESS="success",q.ERROR="error",q))(A8||{}),M=((q)=>(q.Opened="opened",q.Closed="closed",q.PermissionRequested="permission-requested",q.PermissionGranted="permission-granted",q.PreExchange="pre-exchange",q.Exchange="exchange",q.DeviceId="device-id",q.Progress="progress",q.Warning="warning",q.Error="error",q.Result="result",q))(M||{});var aQ="0000";function oQ(q){return q[0]===224&&q[1]===81}function rQ(q){return q[0]===224&&q[1]===82}function tQ(q){try{let J=new Y0(q);return J.extractFieldLVEncoded()?J.extractFieldLVEncoded()??null:null}catch{return null}}function eQ(q){return q===aQ}var R8=BigInt(4294967295),q$=BigInt(32);function t2(q,J=!1){if(J)return{h:Number(q&R8),l:Number(q>>q$&R8)};return{h:Number(q>>q$&R8)|0,l:Number(q&R8)|0}}function J$(q,J=!1){let Z=q.length,Q=new Uint32Array(Z),$=new Uint32Array(Z);for(let W=0;W<Z;W++){let{h:Y,l:z}=t2(q[W],J);[Q[W],$[W]]=[Y,z]}return[Q,$]}var Z$=(q,J,Z)=>q<<Z|J>>>32-Z,Q$=(q,J,Z)=>J<<Z|q>>>32-Z,$$=(q,J,Z)=>J<<Z-32|q>>>64-Z,W$=(q,J,Z)=>q<<Z-32|J>>>64-Z;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function e2(q){return q instanceof Uint8Array||ArrayBuffer.isView(q)&&q.constructor.name==="Uint8Array"}function gJ(q){if(!Number.isSafeInteger(q)||q<0)throw Error("positive integer expected, got "+q)}function w6(q,...J){if(!e2(q))throw Error("Uint8Array expected");if(J.length>0&&!J.includes(q.length))throw Error("Uint8Array expected of length "+J+", got length="+q.length)}function mJ(q,J=!0){if(q.destroyed)throw Error("Hash instance has been destroyed");if(J&&q.finished)throw Error("Hash#digest() has already been called")}function Y$(q,J){w6(q);let Z=J.outputLen;if(q.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function z$(q){return new Uint32Array(q.buffer,q.byteOffset,Math.floor(q.byteLength/4))}function lJ(...q){for(let J=0;J<q.length;J++)q[J].fill(0)}function mD(q){return new DataView(q.buffer,q.byteOffset,q.byteLength)}function lD(q,J){return q<<32-J|q>>>J}function dD(q,J){return q<<J|q>>>32-J>>>0}var qw=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Jw(q){return q<<24&4278190080|q<<8&16711680|q>>>8&65280|q>>>24&255}function Zw(q){for(let J=0;J<q.length;J++)q[J]=Jw(q[J]);return q}var dJ=qw?(q)=>q:Zw;function Qw(q){if(typeof q!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(q))}function cJ(q){if(typeof q==="string")q=Qw(q);return w6(q),q}class pJ{}function w$(q){let J=(Q)=>q().update(cJ(Q)).digest(),Z=q();return J.outputLen=Z.outputLen,J.blockLen=Z.blockLen,J.create=()=>q(),J}var $w=BigInt(0),X6=BigInt(1),Ww=BigInt(2),Yw=BigInt(7),zw=BigInt(256),ww=BigInt(113),_$=[],H$=[],G$=[];for(let q=0,J=X6,Z=1,Q=0;q<24;q++){[Z,Q]=[Q,(2*Z+3*Q)%5],_$.push(2*(5*Q+Z)),H$.push((q+1)*(q+2)/2%64);let $=$w;for(let W=0;W<7;W++)if(J=(J<<X6^(J>>Yw)*ww)%zw,J&Ww)$^=X6<<(X6<<BigInt(W))-X6;G$.push($)}var N$=J$(G$,!0),Xw=N$[0],Fw=N$[1],X$=(q,J,Z)=>Z>32?$$(q,J,Z):Z$(q,J,Z),F$=(q,J,Z)=>Z>32?W$(q,J,Z):Q$(q,J,Z);function _w(q,J=24){let Z=new Uint32Array(10);for(let Q=24-J;Q<24;Q++){for(let Y=0;Y<10;Y++)Z[Y]=q[Y]^q[Y+10]^q[Y+20]^q[Y+30]^q[Y+40];for(let Y=0;Y<10;Y+=2){let z=(Y+8)%10,X=(Y+2)%10,w=Z[X],F=Z[X+1],_=X$(w,F,1)^Z[z],G=F$(w,F,1)^Z[z+1];for(let B=0;B<50;B+=10)q[Y+B]^=_,q[Y+B+1]^=G}let $=q[2],W=q[3];for(let Y=0;Y<24;Y++){let z=H$[Y],X=X$($,W,z),w=F$($,W,z),F=_$[Y];$=q[F],W=q[F+1],q[F]=X,q[F+1]=w}for(let Y=0;Y<50;Y+=10){for(let z=0;z<10;z++)Z[z]=q[Y+z];for(let z=0;z<10;z++)q[Y+z]^=~Z[(z+2)%10]&Z[(z+4)%10]}q[0]^=Xw[Q],q[1]^=Fw[Q]}lJ(Z)}class sJ extends pJ{constructor(q,J,Z,Q=!1,$=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=q,this.suffix=J,this.outputLen=Z,this.enableXOF=Q,this.rounds=$,gJ(Z),!(0<q&&q<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=z$(this.state)}clone(){return this._cloneInto()}keccak(){dJ(this.state32),_w(this.state32,this.rounds),dJ(this.state32),this.posOut=0,this.pos=0}update(q){mJ(this),q=cJ(q),w6(q);let{blockLen:J,state:Z}=this,Q=q.length;for(let $=0;$<Q;){let W=Math.min(J-this.pos,Q-$);for(let Y=0;Y<W;Y++)Z[this.pos++]^=q[$++];if(this.pos===J)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:q,suffix:J,pos:Z,blockLen:Q}=this;if(q[Z]^=J,(J&128)!==0&&Z===Q-1)this.keccak();q[Q-1]^=128,this.keccak()}writeInto(q){mJ(this,!1),w6(q),this.finish();let J=this.state,{blockLen:Z}=this;for(let Q=0,$=q.length;Q<$;){if(this.posOut>=Z)this.keccak();let W=Math.min(Z-this.posOut,$-Q);q.set(J.subarray(this.posOut,this.posOut+W),Q),this.posOut+=W,Q+=W}return q}xofInto(q){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(q)}xof(q){return gJ(q),this.xofInto(new Uint8Array(q))}digestInto(q){if(Y$(q,this),this.finished)throw Error("digest() was already called");return this.writeInto(q),this.destroy(),q}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,lJ(this.state)}_cloneInto(q){let{blockLen:J,suffix:Z,outputLen:Q,rounds:$,enableXOF:W}=this;return q||(q=new sJ(J,Z,Q,W,$)),q.state32.set(this.state32),q.pos=this.pos,q.posOut=this.posOut,q.finished=this.finished,q.rounds=$,q.suffix=Z,q.outputLen=Q,q.enableXOF=W,q.destroyed=this.destroyed,q}}var Hw=(q,J,Z)=>w$(()=>new sJ(J,q,Z));var V$=(()=>Hw(6,136,32))();class nJ{sha3_256(q){return V$(q)}}var Lq=((q)=>(q[q.AppAlreadyInstalled=0]="AppAlreadyInstalled",q[q.DeviceLocked=1]="DeviceLocked",q[q.OutOfMemory=2]="OutOfMemory",q[q.RefusedByUser=3]="RefusedByUser",q[q.Unknown=4]="Unknown",q))(Lq||{});class iJ{constructor(q){this.error=q,this.originalError=q}_tag="WebSocketConnectionError";originalError}class E0{constructor(q,J=4){this.error=q,this.errorType=J,this.originalError=q}_tag="SecureChannelError";originalError;mapDAErrors(){switch(this.errorType){case 1:return new B1;case 3:return new T1;default:return this}}mapInstallDAErrors(){switch(this.errorType){case 1:return new B1;case 3:return new T1;case 0:return new N8;case 2:return new D1;default:return this}}mapUpdateFirmwareDAErrors(){switch(this.errorType){case 2:return new D1;case 1:return new B1;case 3:return new T1;case 4:return new q0;default:return this}}mapFlashMcuDAErrors(){switch(this.errorType){case 1:return new B1;case 4:return new q0;default:return this}}}class d0{constructor(q,J){if(this._api=q,this._args=J,this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new E0(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`);this._cryptoService=this._args.cryptoService??new nJ}_connection;_cryptoService;_deviceIdCaptured=!1;run(){return new Gw((q)=>{let J=!1,Z=!1,Q=!1,$=(W)=>{q.next({type:M.Error,error:W}),q.complete(),Z=!0};return this._connection.onopen=()=>{q.next({type:M.Opened})},this._connection.onerror=(W)=>{Z||(q.next({type:M.Error,error:new E0({url:this._connection.url,errorMessage:W.message})}),q.complete())},this._connection.onclose=()=>{Z||(Q?q.next({type:M.Closed}):q.next({type:M.Error,error:new E0({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),q.complete())},this._connection.onmessage=async(W)=>{if(J)return;let Y;try{let z=JSON.parse(String(W.data));if(this.isInMessageType(z))Y=z;else throw Error("Data does not match InMessageType")}catch{$(new E0({url:this._connection.url,errorMessage:`Invalid message received: ${String(W.data)}`}));return}switch(Y.query){case U1.EXCHANGE:{let{nonce:z,data:X}=Y;if(typeof X!="string"){$(new E0(`${U1.EXCHANGE} data type should be an APDU`));return}let w=_1(X);if(w===null||w.length<5){$(new E0(`Received invalid APDU data: ${X}`));return}q.next({type:M.PreExchange,payload:{nonce:z,apdu:w}});let F=!1;oQ(w)&&!this.isSecureConnectionAllowed()&&(F=!0,q.next({type:M.PermissionRequested}));let _=await this._api.sendApdu(w);if(J)return;_.caseOf({Left:(G)=>{$(new E0(G))},Right:(G)=>{let B,A=this.mapDeviceError(G);if(A===null){if(B=A8.SUCCESS,!this._deviceIdCaptured&&rQ(w)){this._deviceIdCaptured=!0;let e=tQ(G);if(e){let p0=this._cryptoService.sha3_256(e);q.next({type:M.DeviceId,payload:{deviceId:p0}})}}q.next({type:M.Exchange,payload:{nonce:z,apdu:w,data:G.data,status:G.statusCode}}),F&&q.next({type:M.PermissionGranted})}else B=A8.ERROR,$(A);let f={nonce:z,response:B,data:B0(G.data,!1)};this._connection.send(JSON.stringify(f))}});break}case U1.BULK:{if(Z=!0,this._connection.close(),!Array.isArray(Y.data)||Y.data.length===0||!Y.data.every((z)=>typeof z=="string")){$(new E0("Invalid bulk data received"));return}for(let z=0,X=Y.data.length;z<X;z++){let w=_1(Y.data[z]);if(w===null||w.length<5){$(new E0(`Received invalid APDU bulk data: ${Y.data[z]}`));return}let F=await this._api.sendApdu(w);if(J)return;if(F.isLeft()){$(new E0(F.extract()));return}else if(F.isRight()){let _=this.mapDeviceError(F.extract());if(_===null)q.next({type:M.Progress,payload:{progress:+Number((z+1)/X).toFixed(2),index:z,total:X}});else{$(_);return}}}Q=!0,q.complete();break}case U1.SUCCESS:{if(Z)break;let z=Y.result??Y.data;z&&q.next({type:M.Result,payload:z??""}),Q=!0,q.complete();break}case U1.WARNING:{if(Z)break;q.next({type:M.Warning,payload:{message:String(Y.data)}});break}case U1.ERROR:{if(Z)break;$(new E0({url:this._connection.url,errorMessage:String(Y.data)}))}}},()=>{J=!0,this._connection.readyState===L8.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){let q=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in q&&q.isSecureConnectionAllowed}isInMessageType(q){if(typeof q!="object"||!q)return!1;let J=q;return typeof J.uuid=="string"&&typeof J.session=="string"&&typeof J.query=="string"&&Object.values(U1).includes(J.query)&&typeof J.nonce=="number"}mapDeviceError(q){return m.isSuccessResponse(q)?null:m.isLockedDeviceResponse(q)?new E0({url:this._connection.url,errorMessage:"Device is locked"},Lq.DeviceLocked):m.isRefusedByUser(q)?new E0({url:this._connection.url,errorMessage:"User refused on the device"},Lq.RefusedByUser):m.isAppAlreadyInstalled(q)?new E0({url:this._connection.url,errorMessage:"App already installed"},Lq.AppAlreadyInstalled):m.isOutOfMemory(q)?new E0({url:this._connection.url,errorMessage:"Out of memory"},Lq.OutOfMemory):new E0({url:this._connection.url,errorMessage:`Invalid status code: ${B0(q.statusCode)}`})}}var t1=Object.freeze({GET_DEVICE_METADATA:"os.getDeviceMetadata.steps.getDeviceMetadata",GO_TO_DASHBOARD:"os.getDeviceMetadata.steps.goToDashboard",GET_FIRMWARE_METADATA:"os.getDeviceMetadata.steps.getFirmwareMetadata",LIST_APPS_SECURE_CHANNEL:"os.getDeviceMetadata.steps.listAppsSecureChannel",LIST_APPS:"os.getDeviceMetadata.steps.listApps",GET_APPLICATIONS_METADATA:"os.getDeviceMetadata.steps.getApplicationsMetadata"});class f1 extends a{makeStateMachine(q){let{getDeviceMetadata:J,getFirmwareMetadata:Z,getApplicationsMetadata:Q,listAppsSecureChannel:$}=this.extractDependencies(q),W=this.input.unlockTimeout??t,Y=new M0({input:{unlockTimeout:W}}).makeStateMachine(q),z=new jq({input:{unlockTimeout:W}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:W},context:{},output:{}},actors:{goToDashboard:Y,getDeviceMetadata:l(J),getFirmwareMetadata:l(Z),getApplicationsMetadata:l(Q),listApps:z,listAppsSecureChannel:O0($)},guards:{hasError:({context:X})=>X._internalState.error!==null,hasMetadata:({context:X})=>X._internalState.firmwareVersion!==null&&X._internalState.firmwareUpdateContext!==null&&X._internalState.customImage!==null&&X._internalState.applications!==null&&X._internalState.applicationsUpdates!==null&&X._internalState.installedLanguages!==null&&X._internalState.catalog!==null,forceUpdate:({context:X})=>!!X.input.forceUpdate,useSecureChannel:({context:X})=>!!X.input.useSecureChannel},actions:{assignErrorFromEvent:N({_internalState:(X)=>({...X.context._internalState,error:X.event.error})})}}).createMachine({id:"GetDeviceMetadataDeviceAction",initial:"DeviceReady",context:(X)=>({input:{useSecureChannel:X.input.useSecureChannel,forceUpdate:X.input.forceUpdate,unlockTimeout:X.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:t1.GET_DEVICE_METADATA},_internalState:{error:null,deviceVersion:null,firmware:null,firmwareVersion:null,firmwareUpdateContext:null,customImage:null,installedApps:null,applications:null,applicationsUpdates:null,installedLanguages:null,catalog:null}}),states:{DeviceReady:{always:[{target:"GoToDashboard",guard:"forceUpdate"},{target:"GetDeviceMetadataFromContext"}]},GetDeviceMetadataFromContext:{invoke:{src:"getDeviceMetadata",onDone:{target:"GetDeviceMetadataFromContextResultCheck",actions:N({_internalState:(X)=>X.event.output===null?X.context._internalState:{...X.context._internalState,firmwareVersion:X.event.output.firmwareVersion,firmwareUpdateContext:X.event.output.firmwareUpdateContext,customImage:X.event.output.customImage,applications:X.event.output.applications,applicationsUpdates:X.event.output.applicationsUpdates,installedLanguages:X.event.output.installedLanguages,catalog:X.event.output.catalog}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceMetadataFromContextResultCheck:{always:[{target:"Success",guard:"hasMetadata"},{target:"GoToDashboard"}]},GoToDashboard:{exit:N({intermediateValue:{requiredUserInteraction:k.None,step:t1.GO_TO_DASHBOARD}}),invoke:{id:"dashboard",src:"goToDashboard",input:(X)=>({unlockTimeout:X.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(X)=>X.event.snapshot.context.intermediateValue})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(X)=>X.event.output.caseOf({Right:()=>X.context._internalState,Left:(w)=>({...X.context._internalState,error:w})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetFirmwareMetadata"}]},GetFirmwareMetadata:{invoke:{src:"getFirmwareMetadata",onDone:{target:"GetFirmwareMetadataResultCheck",actions:N({_internalState:(X)=>{if(x1(X.event.output)){let w=q.getDeviceSessionState();return w.sessionStateType!==d.Connected&&q.setDeviceSessionState({...w,firmwareVersion:X.event.output.data.firmwareVersion,firmwareUpdateContext:X.event.output.data.firmwareUpdateContext,customImage:X.event.output.data.customImage}),{...X.context._internalState,deviceVersion:X.event.output.data.deviceVersion,firmware:X.event.output.data.firmware,firmwareVersion:X.event.output.data.firmwareVersion,firmwareUpdateContext:X.event.output.data.firmwareUpdateContext,customImage:X.event.output.data.customImage}}return{...X.context._internalState,error:X.event.output.error}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetFirmwareMetadataResultCheck:{always:[{guard:"hasError",target:"Error"},{guard:"useSecureChannel",target:"ListAppsSecureChannel"},{target:"ListApps"}]},ListAppsSecureChannel:{exit:N({intermediateValue:{requiredUserInteraction:k.None,step:t1.LIST_APPS_SECURE_CHANNEL}}),invoke:{id:"listAppsSecureChannel",src:"listAppsSecureChannel",input:(X)=>({firmware:X.context._internalState.firmware,firmwareVersion:X.context._internalState.firmwareVersion}),onSnapshot:{actions:N({intermediateValue:(X)=>{switch(X.event.snapshot.context?.type){case M.DeviceId:return{...X.context.intermediateValue,deviceId:X.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...X.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:{let w=q.getDeviceSessionState();return w.sessionStateType!==d.Connected&&q.setDeviceSessionState({...w,isSecureConnectionAllowed:!0}),{...X.context.intermediateValue,requiredUserInteraction:k.None}}default:return{...X.context.intermediateValue}}},_internalState:(X)=>{if(X.event.snapshot.context?.type===M.Error)return{...X.context._internalState,error:X.event.snapshot.context.error.mapDAErrors()};if(X.event.snapshot.context?.type===M.Result){if(I8(X.event.snapshot.context.payload))return{...X.context._internalState,installedApps:X.event.snapshot.context.payload.map((w)=>({name:w.name,hash:w.hash,hashCode:w.hash_code_data}))};throw Error(`Invalid result ${JSON.stringify(X.event.snapshot.context.payload)}`)}return{...X.context._internalState}}})},onDone:{target:"ListAppsCheck"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListApps:{exit:N({intermediateValue:{requiredUserInteraction:k.None,step:t1.LIST_APPS}}),invoke:{id:"listApps",src:"listApps",input:(X)=>({unlockTimeout:X.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(X)=>X.event.snapshot.context.intermediateValue})},onDone:{target:"ListAppsCheck",actions:N({_internalState:(X)=>X.event.output.isLeft()?{...X.context._internalState,error:X.event.output.extract()}:{...X.context._internalState,installedApps:X.event.output.unsafeCoerce().map((w)=>({name:w.appName,hash:w.appFullHash,hashCode:w.appCodeHash}))}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetApplicationsMetadata"}]},GetApplicationsMetadata:{invoke:{src:"getApplicationsMetadata",input:(X)=>({deviceVersion:X.context._internalState.deviceVersion,firmware:X.context._internalState.firmware,firmwareVersion:X.context._internalState.firmwareVersion,installedApps:X.context._internalState.installedApps}),onDone:{target:"GetApplicationsMetadataResultCheck",actions:N({_internalState:(X)=>{if(x1(X.event.output)){let w=q.getDeviceSessionState();return w.sessionStateType!==d.Connected&&q.setDeviceSessionState({...w,installedApps:X.event.output.data.applications,appsUpdates:X.event.output.data.applicationsUpdates,installedLanguages:X.event.output.data.installedLanguages,catalog:X.event.output.data.catalog}),{...X.context._internalState,applications:X.event.output.data.applications,applicationsUpdates:X.event.output.data.applicationsUpdates,installedLanguages:X.event.output.data.installedLanguages,catalog:X.event.output.data.catalog}}return{...X.context._internalState,error:X.event.output.error}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetApplicationsMetadataResultCheck:{always:[{guard:"hasError",target:"Error"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(X)=>{let{context:w}=X,{error:F,firmwareVersion:_,firmwareUpdateContext:G,customImage:B,applications:A,applicationsUpdates:f,installedLanguages:e,catalog:p0}=w._internalState;return F?K(F):I({firmwareVersion:_,firmwareUpdateContext:G,customImage:B,applications:A,applicationsUpdates:f,installedLanguages:e,catalog:p0})}})}extractDependencies(q){return{getDeviceMetadata:()=>{let J=q.getDeviceSessionState();return J.sessionStateType===d.Connected||J.firmwareVersion?.metadata===void 0||J.firmwareUpdateContext===void 0||J.customImage===void 0||J.installedApps.length===0||J.appsUpdates===void 0||J.installedLanguages===void 0||J.catalog===void 0?Promise.resolve(null):Promise.resolve({firmwareVersion:J.firmwareVersion,firmwareUpdateContext:J.firmwareUpdateContext,customImage:J.customImage,applications:J.installedApps,applicationsUpdates:J.appsUpdates,installedLanguages:J.installedLanguages,catalog:J.catalog})},getFirmwareMetadata:async()=>new uJ(q).run(),getApplicationsMetadata:async(J)=>new yJ(q,{deviceVersion:J.input.deviceVersion,firmware:J.input.firmware,firmwareVersion:J.input.firmwareVersion,installedApps:J.input.installedApps}).run(),listAppsSecureChannel:(J)=>{let{firmware:Z,firmwareVersion:Q}=J.input,$=q.getSecureChannelService().listInstalledApps(Q.metadata,Z);return new d0(q,{connection:$}).run()}}}}import{Observable as Nw}from"rxjs";class aJ{constructor(q,J){this.api=q,this.args=J}run(){return new Nw((q)=>{(async()=>{let J;try{let Q=await fetch(this.args.apduInstallUrl);if(!Q.ok)throw Error(`HTTP ${Q.status} ${Q.statusText}`);J=await Q.text()}catch(Q){throw new OJ(`Failed to fetch APDUs: ${Q instanceof Error?Q.message:String(Q)}`)}let Z=J.split(/\r?\n/).filter(Boolean);if(typeof J!="string"||Z.length===0)throw new q0(`Language pack install script contains no APDUs: ${this.args.apduInstallUrl}`);for(let Q=0;Q<Z.length;Q++){let $=Z[Q],W=_1($);if(W===null||W.length<5)throw new q0(`Invalid APDU data: ${$}`);let Y=(await this.api.sendApdu(W)).caseOf({Left:(z)=>new q0(`Device communication error: ${String(z)}`),Right:(z)=>m.isRefusedByUser(z)?new T1("Language install refused on device."):m.isOutOfMemory(z)?new D1("Not enough space for language pack."):m.isSuccessResponse(z)?null:new q0(`Unexpected device response: ${B0(z.statusCode)}`)});if(Y)throw Y;q.next({type:"progress",progress:(Q+1)/Z.length})}})().then(()=>q.complete(),(J)=>q.error(J))})}}var Vw={0:"english",1:"french",2:"spanish",3:"brazilian",4:"german",5:"russian",6:"turkish",7:"thai"},B$=Object.freeze({DEVICE_READY:"os.installLanguagePackage.steps.deviceReady",GET_DEVICE_METADATA:"os.installLanguagePackage.steps.getDeviceMetadata",DELETE_CURRENT_LANGUAGE_PACK:"os.installLanguagePackage.steps.deleteCurrentLanguagePack",INSTALL_LANGUAGE_PACK:"os.installLanguagePackage.steps.installLanguagePack"});class D$ extends a{makeStateMachine(q){let{deleteCurrentLanguagePack:J,installLanguagePack:Z}=this.extractDependencies(q),Q=this.input.unlockTimeout??t,$=this.input.language,{None:W}=k,{DEVICE_READY:Y,GET_DEVICE_METADATA:z,DELETE_CURRENT_LANGUAGE_PACK:X,INSTALL_LANGUAGE_PACK:w}=B$,F=new f1({input:{unlockTimeout:Q}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:Q,language:$},context:{},output:{}},actors:{getDeviceMetadata:F,deleteCurrentLanguagePack:l(J),installLanguagePack:O0(({input:_})=>Z(_.apduInstallUrl))},guards:{isDefaultLanguage:({context:_})=>_.input.language==="english",hasError:({context:_})=>_._internalState.error!==null,shouldSkipInstall:({context:_})=>_._internalState.shouldSkipInstall},actions:{assignErrorFromEvent:N({_internalState:(_)=>({..._.context._internalState,error:_.event.error,shouldSkipInstall:!1})}),assignGetDeviceMetadataSnapshot:N({intermediateValue:(_)=>{let G=_.event.snapshot.context.intermediateValue;return G.step===t1.GET_DEVICE_METADATA?{...G,step:z}:G}}),assignGetDeviceMetadataDone:N({_internalState:(_)=>_.event.output.caseOf({Right:(G)=>{let B=G.catalog.languagePackages;if(!B)return{..._.context._internalState,error:new xJ(`Language packages not found for OS ${G?.firmwareVersion?.os}.`)};let A=B.find((f)=>f.language===$);return A?(G.installedLanguages??[]).map(({id:f})=>f).includes(A.languagePackageId)?{..._.context._internalState,shouldSkipInstall:!0}:{..._.context._internalState,languagePackage:A}:{..._.context._internalState,error:new kJ(`Language package not found for ${$}.`)}},Left:(G)=>({..._.context._internalState,error:G})})}),assignDeleteCurrentLanguagePackSnapshot:N({intermediateValue:(_)=>({requiredUserInteraction:W,step:X})}),assignDeleteCurrentLanguagePackDone:N({_internalState:(_)=>{let G=_.event.output;return n(G)?_.context._internalState:{..._.context._internalState,error:new V8("message"in G.error?G.error.message:"Delete language pack failed.")}}}),assignInstallLanguagePackSnapshot:N({intermediateValue:(_)=>{let G=_.event.snapshot.context,B=_.context,A="progress"in B.intermediateValue?B.intermediateValue.progress??0:0;return{requiredUserInteraction:W,step:w,progress:G?.type==="progress"?G.progress:A}}})}}).createMachine({id:"InstallLanguagePackageDeviceAction",initial:"CheckRequestedLanguage",context:(_)=>({input:{unlockTimeout:_.input.unlockTimeout,language:_.input.language},intermediateValue:{requiredUserInteraction:W,step:Y,progress:0},_internalState:{error:null,languagePackage:null,shouldSkipInstall:!1}}),states:{CheckRequestedLanguage:{always:[{guard:"isDefaultLanguage",target:"DeleteCurrentLanguagePack"},{target:"GetDeviceMetadata"}]},GetDeviceMetadata:{invoke:{id:"GetDeviceMetadata",src:"getDeviceMetadata",input:({context:_})=>({unlockTimeout:_.input.unlockTimeout,forceUpdate:!0,useSecureChannel:!0}),onSnapshot:{actions:"assignGetDeviceMetadataSnapshot"},onDone:{target:"LanguagePackCheck",actions:"assignGetDeviceMetadataDone"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},LanguagePackCheck:{always:[{guard:"hasError",target:"Error"},{guard:"shouldSkipInstall",target:"Success"},{target:"DeleteCurrentLanguagePack"}]},DeleteCurrentLanguagePack:{invoke:{id:"DeleteCurrentLanguagePack",src:"deleteCurrentLanguagePack",onSnapshot:{actions:"assignDeleteCurrentLanguagePackSnapshot"},onDone:{target:"DeleteCurrentLanguagePackResultCheck",actions:"assignDeleteCurrentLanguagePackDone"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},DeleteCurrentLanguagePackResultCheck:{always:[{guard:"hasError",target:"Error"},{guard:"isDefaultLanguage",target:"Success"},{target:"InstallLanguagePack"}]},InstallLanguagePack:{invoke:{id:"InstallLanguagePack",src:"installLanguagePack",input:({context:_})=>({apduInstallUrl:_._internalState.languagePackage.apduInstallUrl}),onSnapshot:{actions:"assignInstallLanguagePackSnapshot"},onDone:{target:"Success"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final"},Error:{type:"final"}},output:(_)=>_.context._internalState.error!==null?K(_.context._internalState.error):I(void 0)})}extractDependencies(q){return{deleteCurrentLanguagePack:()=>q.sendCommand(new S6({languagePackageId:255})),installLanguagePack:(J)=>new aJ(q,{apduInstallUrl:J}).run()}}}var oJ=k1(_q(),1);class rJ{constructor(q,J){this.api=q,this.args=J;let Z=q.getDeviceModel();this.deviceModelId=Z.id}deviceModelId;run(){let q=this.api.getDeviceSessionState();if(q.sessionStateType===d.Connected)return{error:new q0("Invalid device state")};if(q.catalog===void 0)return{error:new q0("Device apps metadata not fetched")};let J=[],Z=[],Q=[];for(let $ of this.args.applications){let W=q.catalog.applications.find((z)=>z.versionName===$.name),Y=q.installedApps.find((z)=>z.versionName===$.name);if(Y!==void 0&&this.validateConstraint(Y,W,$.constraints)){Z=[...Z,$.name];continue}if(W!==void 0&&this.validateConstraint(W,void 0,$.constraints))J=[...J,W];else if(this.args.allowMissingApplication)Q=[...Q,$.name];else return q.firmwareUpdateContext?.availableUpdate!==void 0&&W!==void 0?{error:new i1(`Application ${$.name} needs latest firmware`)}:q.firmwareUpdateContext?.availableUpdate!==void 0?{error:new i1(`Application ${$.name} needs latest firmware`)}:{error:new EJ(`Application ${$.name} not supported for this device`)}}return J=[...J.reduce(($,W)=>{let Y=W.parentName;if(Y){let z=q.catalog.applications.find((w)=>w.versionName===Y),X=q.installedApps.find((w)=>w.versionName===Y);if(z&&!X)return[...$,z]}return $},[]),...J],{installPlan:J.filter(($,W)=>J.findIndex((Y)=>Y.versionName===$.versionName)===W),missingApplications:Q,alreadyInstalled:Z}}validateConstraint(q,J,Z){if(Z===void 0)return!0;for(let Q of Z)if(!(Q.exemptModels!==void 0&&Q.exemptModels.includes(this.deviceModelId))&&!(Q.applicableModels!==void 0&&!Q.applicableModels.includes(this.deviceModelId)))return Q.minVersion==="latest"?!J||oJ.gte(q.version,J.version):oJ.gte(q.version,Q.minVersion);return!0}}var Bw=1;class tJ{constructor(q,J){this.api=q,this.args=J,this.deviceModel=q.getDeviceModel()}deviceModel;run(){let q=this.api.getDeviceSessionState();if(q.sessionStateType===d.Connected)return{error:new q0("Invalid device state")};let{firmwareUpdateContext:J,customImage:Z,firmwareVersion:Q,installedLanguages:$,installedApps:W}=q;if(J===void 0||Z===void 0||Q===void 0||$===void 0)return{error:new q0("Device metadata not fetched")};let{blockSize:Y,totalMemoryBlocks:z}=this.getMemoryConstants(Q),X=this.getCurrentMemoryBlocksUsage({firmwareUpdateContext:J,customImage:Z,installedApps:W,installedLanguages:$,blockSize:Y}),w=this.getInstallPlanMemoryBlocksUsage(this.args.installPlan,Y);return{outOfMemory:X+w>=z-Bw}}getMemoryConstants(q){let J=this.deviceModel.getBlockSize({firmwareVersion:q.os}),Z=Math.floor(this.deviceModel.memorySize/J);return{blockSize:J,totalMemoryBlocks:Z}}getCurrentMemoryBlocksUsage({firmwareUpdateContext:q,customImage:J,installedApps:Z,installedLanguages:Q,blockSize:$}){let W=(F)=>Math.ceil(F/$),Y=W(q.currentFirmware.bytes||0),z=W(J.size||0),X=Z.reduce((F,_)=>F+W(_.bytes||0),0),w=Q.reduce((F,_)=>F+W(_.size),0);return Y+z+X+w}getInstallPlanMemoryBlocksUsage(q,J){let Z=(Q)=>Math.ceil(Q/J);return q.reduce((Q,$)=>Q+Z($.bytes||0),0)}}var U$=Object.freeze({UPDATE_DEVICE_METADATA:"os.installOrUpdateApps.steps.updateDeviceMetadata",BUILD_INSTALL_PLAN:"os.installOrUpdateApps.steps.buildInstallPlan",CHECK_IF_ENOUGH_MEMORY:"os.installOrUpdateApps.steps.checkIfEnoughMemory",INSTALL_APPLICATION:"os.installOrUpdateApps.steps.installApplication"});class P8 extends a{makeStateMachine(q){let{buildInstallPlan:J,predictOutOfMemory:Z,installApp:Q}=this.extractDependencies(q),$=this.input.unlockTimeout??t,W=new f1({input:{unlockTimeout:$,useSecureChannel:!0,forceUpdate:!1}}).makeStateMachine(q),Y=new M0({input:{unlockTimeout:$}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:$},context:{},output:{}},actors:{updateMetadata:W,buildInstallPlan:l(J),predictOutOfMemory:l(Z),goToDashboard:Y,installApp:O0(Q)},guards:{hasError:({context:z})=>z._internalState.error!==null,hasInstallPlan:(z)=>z.context.intermediateValue.installPlan!==null,hasMoreApps:(z)=>z.context._internalState.currentIndex<z.context.intermediateValue.installPlan.installPlan.length},actions:{assignErrorFromEvent:N({_internalState:(z)=>({...z.context._internalState,error:z.event.error})}),nextAppIndex:N({_internalState:(z)=>({...z.context._internalState,currentIndex:z.context._internalState.currentIndex+1})}),cleanupDeviceState:()=>{let z=q.getDeviceSessionState();z.sessionStateType!==d.Connected&&q.setDeviceSessionState({...z,installedApps:[],appsUpdates:void 0})}}}).createMachine({id:"InstallOrUpdateAppsDeviceAction",initial:"DeviceReady",context:(z)=>({input:{applications:z.input.applications,allowMissingApplication:z.input.allowMissingApplication,unlockTimeout:z.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:U$.UPDATE_DEVICE_METADATA,installPlan:null},_internalState:{error:null,osVersion:null,currentIndex:0}}),states:{DeviceReady:{always:[{target:"UpdateDeviceMetadata"}]},UpdateDeviceMetadata:{exit:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{id:"updateMetadata",src:"updateMetadata",input:(z)=>({unlockTimeout:z.context.input.unlockTimeout,useSecureChannel:!0,forceUpdate:!1}),onSnapshot:{actions:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:z.event.snapshot.context.intermediateValue.requiredUserInteraction,deviceId:z.event.snapshot.context.intermediateValue.deviceId??z.context.intermediateValue.deviceId})})},onDone:{target:"UpdateDeviceMetadataCheck",actions:N({_internalState:(z)=>z.event.output.caseOf({Right:(X)=>({...z.context._internalState,osVersion:X.firmwareVersion.metadata}),Left:(X)=>({...z.context._internalState,error:X})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},UpdateDeviceMetadataCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"hasInstallPlan"},{target:"BuildInstallPlan"}]},BuildInstallPlan:{invoke:{src:"buildInstallPlan",input:(z)=>({applications:z.context.input.applications,allowMissingApplication:z.context.input.allowMissingApplication}),onDone:{target:"BuildInstallPlanCheck",actions:N({_internalState:(z)=>("error"in z.event.output)?{...z.context._internalState,error:z.event.output.error}:z.context._internalState,intermediateValue:(z)=>("error"in z.event.output)?z.context.intermediateValue:{...z.context.intermediateValue,installPlan:{installPlan:z.event.output.installPlan,alreadyInstalled:z.event.output.alreadyInstalled,missingApplications:z.event.output.missingApplications,currentIndex:0,currentProgress:0}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},BuildInstallPlanCheck:{always:[{guard:"hasError",target:"Error"},{target:"PredictOutOfMemory",guard:"hasMoreApps"},{target:"Success"}]},PredictOutOfMemory:{invoke:{src:"predictOutOfMemory",input:(z)=>({installPlan:z.context.intermediateValue.installPlan.installPlan}),onDone:{target:"PredictOutOfMemoryCheck",actions:N({_internalState:(z)=>("error"in z.event.output)?{...z.context._internalState,error:z.event.output.error}:z.event.output.outOfMemory?{...z.context._internalState,error:new D1("Not enough memory for those applications")}:z.context._internalState})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},PredictOutOfMemoryCheck:{always:[{guard:"hasError",target:"Error"},{target:"GoToDashboard"}]},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(z)=>({unlockTimeout:z.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:z.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(z)=>z.event.output.caseOf({Right:()=>z.context._internalState,Left:(X)=>({...z.context._internalState,error:X})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"InstallApp",actions:"cleanupDeviceState"}]},InstallApp:{exit:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{id:"installApp",src:"installApp",input:(z)=>({osVersion:z.context._internalState.osVersion,application:z.context.intermediateValue.installPlan.installPlan[z.context._internalState.currentIndex]}),onSnapshot:{actions:N({intermediateValue:(z)=>{switch(z.event.snapshot.context?.type){case M.DeviceId:return{...z.context.intermediateValue,deviceId:z.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...z.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:{let X=q.getDeviceSessionState();return X.sessionStateType!==d.Connected&&q.setDeviceSessionState({...X,isSecureConnectionAllowed:!0}),{...z.context.intermediateValue,requiredUserInteraction:k.None}}case M.Progress:return{...z.context.intermediateValue,installPlan:{...z.context.intermediateValue.installPlan,currentIndex:z.context._internalState.currentIndex,currentProgress:z.event.snapshot.context.payload.progress}};default:return z.context.intermediateValue}},_internalState:(z)=>z.event.snapshot.context?.type===M.Error?{...z.context._internalState,error:z.event.snapshot.context.error.mapInstallDAErrors()}:z.context._internalState})},onDone:{target:"InstallAppCheck",actions:"nextAppIndex"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},InstallAppCheck:{always:[{target:"Error",guard:"hasError"},{target:"InstallApp",guard:"hasMoreApps"},{target:"UpdateDeviceMetadata"}]},Success:{type:"final"},Error:{type:"final"}},output:(z)=>{let{context:X}=z,{error:w}=X._internalState,{installPlan:F}=X.intermediateValue;return w?K(w):I({successfullyInstalled:F.installPlan,alreadyInstalled:F.alreadyInstalled,missingApplications:F.missingApplications})}})}extractDependencies(q){return{buildInstallPlan:(J)=>Promise.resolve(new rJ(q,{applications:J.input.applications,allowMissingApplication:J.input.allowMissingApplication}).run()),predictOutOfMemory:(J)=>Promise.resolve(new tJ(q,{installPlan:J.input.installPlan}).run()),installApp:(J)=>{let{osVersion:Z,application:Q}=J.input,$=q.getSecureChannelService().installApp(Z,Q);return new d0(q,{connection:$}).run()}}}}var eJ=Object.freeze({LIST_APPS:"os.listAppsWithMetadata.steps.listApps",FETCH_METADATA:"os.listAppsWithMetadata.steps.fetchMetadata",SAVE_SESSION:"os.listAppsWithMetadata.steps.saveSession"});class K$ extends a{makeStateMachine(q){let{getAppsByHash:J,setDeviceSessionState:Z,getDeviceSessionState:Q}=this.extractDependencies(q),$=this.input.unlockTimeout??t,W=new jq({input:{unlockTimeout:$}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:$},context:{},output:{}},actors:{listApps:W,getAppsByHash:l(J),updateDeviceSessionState:LJ(({input:Y,sendBack:z})=>{let{appsWithMetadata:X}=Y,w=X.filter((_)=>_!==null),F={...Q(),installedApps:w};try{Z(F),z({type:"done"})}catch(_){z({type:"error",error:_})}})},guards:{hasError:({context:Y})=>Y._internalState.error!==null,hasNoAppsInstalled:({context:Y})=>Y._internalState.apps.length===0},actions:{assignErrorFromEvent:N({_internalState:(Y)=>({...Y.context._internalState,error:Y.event.error})})}}).createMachine({id:"ListAppsWithMetadataDeviceAction",initial:"DeviceReady",context:(Y)=>({input:Y.input,_internalState:{error:null,apps:[],appsWithMetadata:[]},intermediateValue:{requiredUserInteraction:k.None,step:eJ.LIST_APPS}}),states:{DeviceReady:{always:{target:"ListApps"}},ListApps:{invoke:{id:"listApps",src:"listApps",input:(Y)=>({unlockTimeout:Y.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(Y)=>Y.event.snapshot.context.intermediateValue})},onDone:{target:"ListAppsCheck",actions:N({intermediateValue:(Y)=>({requiredUserInteraction:k.None,step:eJ.LIST_APPS}),_internalState:(Y)=>Y.event.output.caseOf({Right:(z)=>({...Y.context._internalState,apps:z}),Left:(z)=>({...Y.context._internalState,error:z})})})}}},ListAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"hasNoAppsInstalled",actions:N({_internalState:(Y)=>({...Y.context._internalState,appsWithMetadata:[]})})},{target:"FetchMetadata"}]},FetchMetadata:{invoke:{id:"getAppsByHash",src:"getAppsByHash",input:(Y)=>Y.context._internalState.apps,onDone:{target:"FetchMetadataCheck",actions:N({_internalState:(Y)=>Y.event.output.caseOf({Right:(z)=>({...Y.context._internalState,appsWithMetadata:z}),Left:(z)=>({...Y.context._internalState,error:z})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},FetchMetadataCheck:{always:[{target:"Error",guard:"hasError"},{target:"SaveSession"}]},SaveSession:{invoke:{src:"updateDeviceSessionState",input:(Y)=>({appsWithMetadata:Y.context._internalState.appsWithMetadata})},on:{done:{target:"Success"},error:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final"},Error:{type:"final"}},output:(Y)=>Y.context._internalState.error?K(Y.context._internalState.error):I(Y.context._internalState.appsWithMetadata)})}extractDependencies(q){return{getAppsByHash:({input:J})=>{let Z=J.reduce((Q,$)=>$.appFullHash?Q.concat($.appFullHash):Q,[]);return q.getManagerApiService().getAppsByHash(Z)},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}var j$=Object.freeze({GET_DEVICE_METADATA:"os.openAppWithDependencies.steps.getDeviceMetadata",INSTALL_OR_UPDATE_APPS:"os.openAppWithDependencies.steps.installOrUpdateApps",OPEN_APP:"os.openAppWithDependencies.steps.openApp"});class I$ extends a{makeStateMachine(q){let J=this.input.unlockTimeout??t,Z=new f1({input:{unlockTimeout:J,useSecureChannel:!0,forceUpdate:!1}}).makeStateMachine(q),Q=new P8({input:{unlockTimeout:J,applications:[...this.input.dependencies,this.input.application],allowMissingApplication:this.input.allowMissingApplication??!1}}).makeStateMachine(q),$=new M1({input:{unlockTimeout:J,appName:this.input.application.name}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:J},context:{},output:{}},actors:{getMetadata:Z,installApps:Q,openApp:$},guards:{hasError:({context:W})=>W._internalState.error!==null},actions:{assignErrorFromEvent:N({_internalState:(W)=>({...W.context._internalState,error:W.event.error})})}}).createMachine({id:"OpenAppWithDependenciesDeviceAction",initial:"DeviceReady",context:(W)=>({input:{application:W.input.application,dependencies:W.input.dependencies,requireLatestFirmware:W.input.requireLatestFirmware,unlockTimeout:W.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:j$.GET_DEVICE_METADATA,installPlan:null},_internalState:{error:null,deviceMetadata:null,installResult:null}}),states:{DeviceReady:{always:[{target:"GetDeviceMetadata"}]},GetDeviceMetadata:{exit:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{id:"getMetadata",src:"getMetadata",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout,useSecureChannel:!0,forceUpdate:!1}),onSnapshot:{actions:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:W.event.snapshot.context.intermediateValue.requiredUserInteraction,deviceId:W.event.snapshot.context.intermediateValue.deviceId??W.context.intermediateValue.deviceId})})},onDone:{target:"GetDeviceMetadataCheck",actions:N({_internalState:(W)=>W.event.output.caseOf({Right:(Y)=>W.context.input.requireLatestFirmware&&Y.firmwareUpdateContext.availableUpdate!==void 0?{...W.context._internalState,error:new i1("Firmware is not the latest version")}:{...W.context._internalState,deviceMetadata:Y},Left:(Y)=>({...W.context._internalState,error:Y})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceMetadataCheck:{always:[{target:"Error",guard:"hasError"},{target:"InstallDependencies"}]},InstallDependencies:{exit:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{src:"installApps",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout,applications:[...W.context.input.dependencies,W.context.input.application],allowMissingApplication:this.input.allowMissingApplication??!1}),onSnapshot:{actions:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:W.event.snapshot.context.intermediateValue.requiredUserInteraction,installPlan:W.event.snapshot.context.intermediateValue.installPlan,deviceId:W.event.snapshot.context.intermediateValue.deviceId??W.context.intermediateValue.deviceId})})},onDone:{target:"InstallDependenciesCheck",actions:N({_internalState:(W)=>W.event.output.caseOf({Right:(Y)=>({...W.context._internalState,installResult:Y}),Left:(Y)=>({...W.context._internalState,error:Y})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},InstallDependenciesCheck:{always:[{guard:"hasError",target:"Error"},{target:"OpenApp"}]},OpenApp:{exit:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{src:"openApp",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout,appName:W.context.input.application.name}),onSnapshot:{actions:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:W.event.snapshot.context.intermediateValue.requiredUserInteraction,installPlan:null})})},onDone:{target:"OpenAppCheck",actions:N({_internalState:(W)=>W.event.output.caseOf({Right:()=>W.context._internalState,Left:(Y)=>({...W.context._internalState,error:Y})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},OpenAppCheck:{always:[{guard:"hasError",target:"Error"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(W)=>{let{context:Y}=W,{error:z,deviceMetadata:X,installResult:w}=Y._internalState;return z?K(z):I({deviceMetadata:X,installResult:w})}})}}var E8=Object.freeze({OPEN_APP:"os.sendCommandInApp.steps.openApp",SEND_COMMAND:"os.sendCommandInApp.steps.sendCommand"});class L$ extends a{makeStateMachine(q){let{sendCommand:J}=this.extractDependencies(q);return i({types:{input:{},context:{},output:{}},actors:{sendCommand:l(J),openAppStateMachine:new M1({input:{appName:this.input.appName}}).makeStateMachine(q)},guards:{skipOpenApp:()=>this.input.skipOpenApp,noInternalError:({context:Z})=>Z._internalState.error===null},actions:{assignErrorFromEvent:N({_internalState:(Z)=>({...Z.context._internalState,error:Z.event.error})})}}).createMachine({id:"SendCommandInAppDeviceAction",initial:"InitialState",context:({input:Z})=>({input:Z,intermediateValue:{requiredUserInteraction:k.None,step:E8.OPEN_APP},_internalState:{commandResponse:null,error:null}}),states:{InitialState:{always:[{target:"SendCommand",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",input:{appName:this.input.appName},src:"openAppStateMachine",onSnapshot:{actions:N({intermediateValue:(Z)=>Z.event.snapshot.context.intermediateValue})},onDone:{actions:N({_internalState:(Z)=>Z.event.output.caseOf({Right:()=>Z.context._internalState,Left:(Q)=>({...Z.context._internalState,error:Q})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"SendCommand",guard:"noInternalError"},"Error"]},SendCommand:{entry:N({intermediateValue:{requiredUserInteraction:this.input.requiredUserInteraction,step:E8.SEND_COMMAND}}),exit:N({intermediateValue:{requiredUserInteraction:k.None,step:E8.SEND_COMMAND}}),invoke:{id:"sendCommand",src:"sendCommand",input:({context:Z})=>Z.input.command,onDone:{target:"SendCommandResultCheck",actions:[N({_internalState:({event:Z,context:Q})=>n(Z.output)?{...Q._internalState,commandResponse:Z.output.data}:{...Q._internalState,error:Z.output.error}})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},SendCommandResultCheck:{always:[{target:"Success",guard:"noInternalError"},"Error"]},Success:{type:"final"},Error:{type:"final"}},output:({context:Z})=>Z._internalState.commandResponse?I(Z._internalState.commandResponse):K(Z._internalState.error||new q0("No error in final state"))})}extractDependencies(q){return{sendCommand:(J)=>q.sendCommand(J.input)}}}var Hj=k1(O6(),1);var tK=k1(O6(),1);function K1(q,J){return Reflect.getOwnMetadata(J,q)}function F6(q,J,Z){Reflect.defineMetadata(J,Z,q)}function z1(q,J,Z,Q){let $=Q(K1(q,J)??Z());Reflect.defineMetadata(J,$,q)}function U0(q){return(typeof q=="object"&&q!==null||typeof q=="function")&&typeof q.then=="function"}function f0(q){switch(typeof q){case"string":case"symbol":return q.toString();case"function":return q.name;default:throw Error(`Unexpected ${typeof q} service id type`)}}var q5=Symbol.for("@inversifyjs/common/islazyServiceIdentifier");class Aq{[q5];#q;constructor(q){this.#q=q,this[q5]=!0}static is(q){return typeof q=="object"&&q!==null&&q[q5]===!0}unwrap(){return this.#q()}}var J5="@inversifyjs/container/bindingId";function I1(){let q=K1(Object,J5)??0;return q===Number.MAX_SAFE_INTEGER?F6(Object,J5,Number.MIN_SAFE_INTEGER):z1(Object,J5,()=>q,(J)=>J+1),q}var s0={Request:"Request",Singleton:"Singleton",Transient:"Transient"},F0={ConstantValue:"ConstantValue",DynamicValue:"DynamicValue",Factory:"Factory",Instance:"Instance",Provider:"Provider",ResolvedValue:"ResolvedValue",ServiceRedirection:"ServiceRedirection"};function*u$(...q){for(let J of q)yield*J}class G6{#q;#J;#$;constructor(q){this.#q=new Map,this.#J={};for(let J of Reflect.ownKeys(q))this.#J[J]=new Map;this.#$=q}add(q,J){this.#Z(q).push(J);for(let Z of Reflect.ownKeys(J))this.#Y(Z,J[Z]).push(q)}clone(){let q=Reflect.ownKeys(this.#$),J=new G6(this.#$);this.#z(this.#q,J.#q);for(let Z of q)this.#z(this.#J[Z],J.#J[Z]);return J}get(q,J){return this.#J[q].get(J)}getAllKeys(q){return this.#J[q].keys()}removeByRelation(q,J){let Z=this.get(q,J);if(Z===void 0)return;let Q=new Set(Z);for(let $ of Q){let W=this.#q.get($);if(W===void 0)throw Error("Expecting model relation, none found");for(let Y of W)Y[q]===J&&this.#W($,Y);this.#q.delete($)}}#Z(q){let J=this.#q.get(q);return J===void 0&&(J=[],this.#q.set(q,J)),J}#Y(q,J){let Z=this.#J[q].get(J);return Z===void 0&&(Z=[],this.#J[q].set(J,Z)),Z}#z(q,J){for(let[Z,Q]of q)J.set(Z,[...Q])}#W(q,J){for(let Z of Reflect.ownKeys(J))this.#Q(q,Z,J[Z])}#Q(q,J,Z){let Q=this.#J[J].get(Z);if(Q!==void 0){let $=Q.indexOf(q);$!==-1&&Q.splice($,1),Q.length===0&&this.#J[J].delete(Z)}}}var _6,e0,H6;(function(q){q.moduleId="moduleId",q.serviceId="serviceId"})(_6||(_6={}));class Eq{#q;#J;constructor(q,J){this.#q=J??new G6({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#J=q}static build(q){return new Eq(q)}add(q,J){this.#q.add(q,J)}clone(){return new Eq(this.#J,this.#q.clone())}get(q){let J=[],Z=this.#q.get(_6.serviceId,q);Z!==void 0&&J.push(Z);let Q=this.#J?.get(q);if(Q!==void 0&&J.push(Q),J.length!==0)return u$(...J)}removeAllByModuleId(q){this.#q.removeByRelation(_6.moduleId,q)}removeAllByServiceId(q){this.#q.removeByRelation(_6.serviceId,q)}}(function(q){q.id="id",q.moduleId="moduleId",q.serviceId="serviceId"})(e0||(e0={}));class xq{#q;#J;constructor(q,J){this.#q=J??new G6({id:{isOptional:!1},moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#J=q}static build(q){return new xq(q)}clone(){return new xq(this.#J,this.#q.clone())}get(q){return this.getNonParentBindings(q)??this.#J?.get(q)}getById(q){return this.#q.get(e0.id,q)??this.#J?.getById(q)}getByModuleId(q){return this.#q.get(e0.moduleId,q)??this.#J?.getByModuleId(q)}getNonParentBindings(q){return this.#q.get(e0.serviceId,q)}getNonParentBoundServices(){return this.#q.getAllKeys(e0.serviceId)}removeById(q){this.#q.removeByRelation(e0.id,q)}removeAllByModuleId(q){this.#q.removeByRelation(e0.moduleId,q)}removeAllByServiceId(q){this.#q.removeByRelation(e0.serviceId,q)}set(q){let J={[e0.id]:q.id,[e0.serviceId]:q.serviceIdentifier};q.moduleId!==void 0&&(J[e0.moduleId]=q.moduleId),this.#q.add(q,J)}}(function(q){q.moduleId="moduleId",q.serviceId="serviceId"})(H6||(H6={}));class kq{#q;#J;constructor(q,J){this.#q=J??new G6({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#J=q}static build(q){return new kq(q)}add(q,J){this.#q.add(q,J)}clone(){return new kq(this.#J,this.#q.clone())}get(q){let J=[],Z=this.#q.get(H6.serviceId,q);Z!==void 0&&J.push(Z);let Q=this.#J?.get(q);if(Q!==void 0&&J.push(Q),J.length!==0)return u$(...J)}removeAllByModuleId(q){this.#q.removeByRelation(H6.moduleId,q)}removeAllByServiceId(q){this.#q.removeByRelation(H6.serviceId,q)}}var Rq="@inversifyjs/core/classMetadataReflectKey";function Pq(){return{constructorArguments:[],lifecycle:{postConstructMethodName:void 0,preDestroyMethodName:void 0},properties:new Map,scope:void 0}}var g$="@inversifyjs/core/pendingClassMetadataCountReflectKey",Z5=Symbol.for("@inversifyjs/core/InversifyCoreError");class z0 extends Error{[Z5];kind;constructor(q,J,Z){super(J,Z),this[Z5]=!0,this.kind=q}static is(q){return typeof q=="object"&&q!==null&&q[Z5]===!0}static isErrorOfKind(q,J){return z0.is(q)&&q.kind===J}}var w0,Oq,j1;function N6(q){let J=K1(q,Rq)??Pq();if(!function(Z){let Q=K1(Z,g$);return Q!==void 0&&Q!==0}(q))return function(Z,Q){let $=[];if(Q.length<Z.length)throw new z0(w0.missingInjectionDecorator,`Found unexpected missing metadata on type "${Z.name}". "${Z.name}" constructor requires at least ${Z.length.toString()} arguments, found ${Q.length.toString()} instead.
14
+ ***************************************************************************** */var JZ;(function(q){(function(J){var Z=typeof globalThis==="object"?globalThis:typeof global==="object"?global:typeof self==="object"?self:typeof this==="object"?this:z(),Q=$(q);if(typeof Z.Reflect<"u")Q=$(Z.Reflect,Q);if(J(Q,Z),typeof Z.Reflect>"u")Z.Reflect=q;function $(X,w){return function(F,_){if(Object.defineProperty(X,F,{configurable:!0,writable:!0,value:_}),w)w(F,_)}}function W(){try{return Function("return this;")()}catch(X){}}function Y(){try{return(0,eval)("(function() { return this; })()")}catch(X){}}function z(){return W()||Y()}})(function(J,Z){var Q=Object.prototype.hasOwnProperty,$=typeof Symbol==="function",W=$&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",Y=$&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",z=typeof Object.create==="function",X={__proto__:[]}instanceof Array,w=!z&&!X,F={create:z?function(){return h9(Object.create(null))}:X?function(){return h9({__proto__:null})}:function(){return h9({})},has:w?function(H,V){return Q.call(H,V)}:function(H,V){return V in H},get:w?function(H,V){return Q.call(H,V)?H[V]:void 0}:function(H,V){return H[V]}},_=Object.getPrototypeOf(Function),G=typeof Map==="function"&&typeof Map.prototype.entries==="function"?Map:xY(),B=typeof Set==="function"&&typeof Set.prototype.entries==="function"?Set:kY(),R=typeof WeakMap==="function"?WeakMap:OY(),S=$?Symbol.for("@reflect-metadata:registry"):void 0,e=RY(),s0=PY(e);function P0(H,V,D,K){if(!y(D)){if(!n5(H))throw TypeError();if(!N0(V))throw TypeError();if(!N0(K)&&!y(K)&&!Qq(K))throw TypeError();if(Qq(K))K=void 0;return D=W1(D),DY(H,V,D,K)}else{if(!n5(H))throw TypeError();if(!i5(V))throw TypeError();return BY(H,V)}}J("decorate",P0);function T9(H,V){function D(K,b){if(!N0(K))throw TypeError();if(!y(b)&&!LY(b))throw TypeError();l5(H,V,K,b)}return D}J("metadata",T9);function wY(H,V,D,K){if(!N0(D))throw TypeError();if(!y(K))K=W1(K);return l5(H,V,D,K)}J("defineMetadata",wY);function XY(H,V,D){if(!N0(V))throw TypeError();if(!y(D))D=W1(D);return u5(H,V,D)}J("hasMetadata",XY);function FY(H,V,D){if(!N0(V))throw TypeError();if(!y(D))D=W1(D);return M9(H,V,D)}J("hasOwnMetadata",FY);function _Y(H,V,D){if(!N0(V))throw TypeError();if(!y(D))D=W1(D);return g5(H,V,D)}J("getMetadata",_Y);function HY(H,V,D){if(!N0(V))throw TypeError();if(!y(D))D=W1(D);return m5(H,V,D)}J("getOwnMetadata",HY);function GY(H,V){if(!N0(H))throw TypeError();if(!y(V))V=W1(V);return d5(H,V)}J("getMetadataKeys",GY);function NY(H,V){if(!N0(H))throw TypeError();if(!y(V))V=W1(V);return c5(H,V)}J("getOwnMetadataKeys",NY);function VY(H,V,D){if(!N0(V))throw TypeError();if(!y(D))D=W1(D);if(!N0(V))throw TypeError();if(!y(D))D=W1(D);var K=gq(V,D,!1);if(y(K))return!1;return K.OrdinaryDeleteMetadata(H,V,D)}J("deleteMetadata",VY);function BY(H,V){for(var D=H.length-1;D>=0;--D){var K=H[D],b=K(V);if(!y(b)&&!Qq(b)){if(!i5(b))throw TypeError();V=b}}return V}function DY(H,V,D,K){for(var b=H.length-1;b>=0;--b){var V0=H[b],E0=V0(V,D,K);if(!y(E0)&&!Qq(E0)){if(!N0(E0))throw TypeError();K=E0}}return K}function u5(H,V,D){var K=M9(H,V,D);if(K)return!0;var b=S9(V);if(!Qq(b))return u5(H,b,D);return!1}function M9(H,V,D){var K=gq(V,D,!1);if(y(K))return!1;return s5(K.OrdinaryHasOwnMetadata(H,V,D))}function g5(H,V,D){var K=M9(H,V,D);if(K)return m5(H,V,D);var b=S9(V);if(!Qq(b))return g5(H,b,D);return}function m5(H,V,D){var K=gq(V,D,!1);if(y(K))return;return K.OrdinaryGetOwnMetadata(H,V,D)}function l5(H,V,D,K){var b=gq(D,K,!0);b.OrdinaryDefineOwnMetadata(H,V,D,K)}function d5(H,V){var D=c5(H,V),K=S9(H);if(K===null)return D;var b=d5(K,V);if(b.length<=0)return D;if(D.length<=0)return b;var V0=new B,E0=[];for(var c=0,A=D;c<A.length;c++){var x=A[c],O=V0.has(x);if(!O)V0.add(x),E0.push(x)}for(var C=0,s=b;C<s.length;C++){var x=s[C],O=V0.has(x);if(!O)V0.add(x),E0.push(x)}return E0}function c5(H,V){var D=gq(H,V,!1);if(!D)return[];return D.OrdinaryOwnMetadataKeys(H,V)}function p5(H){if(H===null)return 1;switch(typeof H){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return H===null?1:6;default:return 6}}function y(H){return H===void 0}function Qq(H){return H===null}function UY(H){return typeof H==="symbol"}function N0(H){return typeof H==="object"?H!==null:typeof H==="function"}function KY(H,V){switch(p5(H)){case 0:return H;case 1:return H;case 2:return H;case 3:return H;case 4:return H;case 5:return H}var D=V===3?"string":V===5?"number":"default",K=a5(H,W);if(K!==void 0){var b=K.call(H,D);if(N0(b))throw TypeError();return b}return jY(H,D==="default"?"number":D)}function jY(H,V){if(V==="string"){var D=H.toString;if($q(D)){var K=D.call(H);if(!N0(K))return K}var b=H.valueOf;if($q(b)){var K=b.call(H);if(!N0(K))return K}}else{var b=H.valueOf;if($q(b)){var K=b.call(H);if(!N0(K))return K}var V0=H.toString;if($q(V0)){var K=V0.call(H);if(!N0(K))return K}}throw TypeError()}function s5(H){return!!H}function IY(H){return""+H}function W1(H){var V=KY(H,3);if(UY(V))return V;return IY(V)}function n5(H){return Array.isArray?Array.isArray(H):H instanceof Object?H instanceof Array:Object.prototype.toString.call(H)==="[object Array]"}function $q(H){return typeof H==="function"}function i5(H){return typeof H==="function"}function LY(H){switch(p5(H)){case 3:return!0;case 4:return!0;default:return!1}}function f9(H,V){return H===V||H!==H&&V!==V}function a5(H,V){var D=H[V];if(D===void 0||D===null)return;if(!$q(D))throw TypeError();return D}function o5(H){var V=a5(H,Y);if(!$q(V))throw TypeError();var D=V.call(H);if(!N0(D))throw TypeError();return D}function r5(H){return H.value}function t5(H){var V=H.next();return V.done?!1:V}function e5(H){var V=H.return;if(V)V.call(H)}function S9(H){var V=Object.getPrototypeOf(H);if(typeof H!=="function"||H===_)return V;if(V!==_)return V;var D=H.prototype,K=D&&Object.getPrototypeOf(D);if(K==null||K===Object.prototype)return V;var b=K.constructor;if(typeof b!=="function")return V;if(b===H)return V;return b}function AY(){var H;if(!y(S)&&typeof Z.Reflect<"u"&&!(S in Z.Reflect)&&typeof Z.Reflect.defineMetadata==="function")H=EY(Z.Reflect);var V,D,K,b=new R,V0={registerProvider:E0,getProvider:A,setProvider:O};return V0;function E0(C){if(!Object.isExtensible(V0))throw Error("Cannot add provider to a frozen registry.");switch(!0){case H===C:break;case y(V):V=C;break;case V===C:break;case y(D):D=C;break;case D===C:break;default:if(K===void 0)K=new B;K.add(C);break}}function c(C,s){if(!y(V)){if(V.isProviderFor(C,s))return V;if(!y(D)){if(D.isProviderFor(C,s))return V;if(!y(K)){var $0=o5(K);while(!0){var B0=t5($0);if(!B0)return;var J1=r5(B0);if(J1.isProviderFor(C,s))return e5($0),J1}}}}if(!y(H)&&H.isProviderFor(C,s))return H;return}function A(C,s){var $0=b.get(C),B0;if(!y($0))B0=$0.get(s);if(!y(B0))return B0;if(B0=c(C,s),!y(B0)){if(y($0))$0=new G,b.set(C,$0);$0.set(s,B0)}return B0}function x(C){if(y(C))throw TypeError();return V===C||D===C||!y(K)&&K.has(C)}function O(C,s,$0){if(!x($0))throw Error("Metadata provider not registered.");var B0=A(C,s);if(B0!==$0){if(!y(B0))return!1;var J1=b.get(C);if(y(J1))J1=new G,b.set(C,J1);J1.set(s,$0)}return!0}}function RY(){var H;if(!y(S)&&N0(Z.Reflect)&&Object.isExtensible(Z.Reflect))H=Z.Reflect[S];if(y(H))H=AY();if(!y(S)&&N0(Z.Reflect)&&Object.isExtensible(Z.Reflect))Object.defineProperty(Z.Reflect,S,{enumerable:!1,configurable:!1,writable:!1,value:H});return H}function PY(H){var V=new R,D={isProviderFor:function(x,O){var C=V.get(x);if(y(C))return!1;return C.has(O)},OrdinaryDefineOwnMetadata:E0,OrdinaryHasOwnMetadata:b,OrdinaryGetOwnMetadata:V0,OrdinaryOwnMetadataKeys:c,OrdinaryDeleteMetadata:A};return e.registerProvider(D),D;function K(x,O,C){var s=V.get(x),$0=!1;if(y(s)){if(!C)return;s=new G,V.set(x,s),$0=!0}var B0=s.get(O);if(y(B0)){if(!C)return;if(B0=new G,s.set(O,B0),!H.setProvider(x,O,D)){if(s.delete(O),$0)V.delete(x);throw Error("Wrong provider for target.")}}return B0}function b(x,O,C){var s=K(O,C,!1);if(y(s))return!1;return s5(s.has(x))}function V0(x,O,C){var s=K(O,C,!1);if(y(s))return;return s.get(x)}function E0(x,O,C,s){var $0=K(C,s,!0);$0.set(x,O)}function c(x,O){var C=[],s=K(x,O,!1);if(y(s))return C;var $0=s.keys(),B0=o5($0),J1=0;while(!0){var qZ=t5(B0);if(!qZ)return C.length=J1,C;var CY=r5(qZ);try{C[J1]=CY}catch(bY){try{e5(B0)}finally{throw bY}}J1++}}function A(x,O,C){var s=K(O,C,!1);if(y(s))return!1;if(!s.delete(x))return!1;if(s.size===0){var $0=V.get(O);if(!y($0)){if($0.delete(C),$0.size===0)V.delete($0)}}return!0}}function EY(H){var{defineMetadata:V,hasOwnMetadata:D,getOwnMetadata:K,getOwnMetadataKeys:b,deleteMetadata:V0}=H,E0=new R,c={isProviderFor:function(A,x){var O=E0.get(A);if(!y(O)&&O.has(x))return!0;if(b(A,x).length){if(y(O))O=new B,E0.set(A,O);return O.add(x),!0}return!1},OrdinaryDefineOwnMetadata:V,OrdinaryHasOwnMetadata:D,OrdinaryGetOwnMetadata:K,OrdinaryOwnMetadataKeys:b,OrdinaryDeleteMetadata:V0};return c}function gq(H,V,D){var K=e.getProvider(H,V);if(!y(K))return K;if(D){if(e.setProvider(H,V,s0))return s0;throw Error("Illegal state.")}return}function xY(){var H={},V=[],D=function(){function c(A,x,O){this._index=0,this._keys=A,this._values=x,this._selector=O}return c.prototype["@@iterator"]=function(){return this},c.prototype[Y]=function(){return this},c.prototype.next=function(){var A=this._index;if(A>=0&&A<this._keys.length){var x=this._selector(this._keys[A],this._values[A]);if(A+1>=this._keys.length)this._index=-1,this._keys=V,this._values=V;else this._index++;return{value:x,done:!1}}return{value:void 0,done:!0}},c.prototype.throw=function(A){if(this._index>=0)this._index=-1,this._keys=V,this._values=V;throw A},c.prototype.return=function(A){if(this._index>=0)this._index=-1,this._keys=V,this._values=V;return{value:A,done:!0}},c}(),K=function(){function c(){this._keys=[],this._values=[],this._cacheKey=H,this._cacheIndex=-2}return Object.defineProperty(c.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),c.prototype.has=function(A){return this._find(A,!1)>=0},c.prototype.get=function(A){var x=this._find(A,!1);return x>=0?this._values[x]:void 0},c.prototype.set=function(A,x){var O=this._find(A,!0);return this._values[O]=x,this},c.prototype.delete=function(A){var x=this._find(A,!1);if(x>=0){var O=this._keys.length;for(var C=x+1;C<O;C++)this._keys[C-1]=this._keys[C],this._values[C-1]=this._values[C];if(this._keys.length--,this._values.length--,f9(A,this._cacheKey))this._cacheKey=H,this._cacheIndex=-2;return!0}return!1},c.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=H,this._cacheIndex=-2},c.prototype.keys=function(){return new D(this._keys,this._values,b)},c.prototype.values=function(){return new D(this._keys,this._values,V0)},c.prototype.entries=function(){return new D(this._keys,this._values,E0)},c.prototype["@@iterator"]=function(){return this.entries()},c.prototype[Y]=function(){return this.entries()},c.prototype._find=function(A,x){if(!f9(this._cacheKey,A)){this._cacheIndex=-1;for(var O=0;O<this._keys.length;O++)if(f9(this._keys[O],A)){this._cacheIndex=O;break}}if(this._cacheIndex<0&&x)this._cacheIndex=this._keys.length,this._keys.push(A),this._values.push(void 0);return this._cacheIndex},c}();return K;function b(c,A){return c}function V0(c,A){return A}function E0(c,A){return[c,A]}}function kY(){var H=function(){function V(){this._map=new G}return Object.defineProperty(V.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),V.prototype.has=function(D){return this._map.has(D)},V.prototype.add=function(D){return this._map.set(D,D),this},V.prototype.delete=function(D){return this._map.delete(D)},V.prototype.clear=function(){this._map.clear()},V.prototype.keys=function(){return this._map.keys()},V.prototype.values=function(){return this._map.keys()},V.prototype.entries=function(){return this._map.entries()},V.prototype["@@iterator"]=function(){return this.keys()},V.prototype[Y]=function(){return this.keys()},V}();return H}function OY(){var H=16,V=F.create(),D=K();return function(){function A(){this._key=K()}return A.prototype.has=function(x){var O=b(x,!1);return O!==void 0?F.has(O,this._key):!1},A.prototype.get=function(x){var O=b(x,!1);return O!==void 0?F.get(O,this._key):void 0},A.prototype.set=function(x,O){var C=b(x,!0);return C[this._key]=O,this},A.prototype.delete=function(x){var O=b(x,!1);return O!==void 0?delete O[this._key]:!1},A.prototype.clear=function(){this._key=K()},A}();function K(){var A;do A="@@WeakMap@@"+c();while(F.has(V,A));return V[A]=!0,A}function b(A,x){if(!Q.call(A,D)){if(!x)return;Object.defineProperty(A,D,{value:F.create()})}return A[D]}function V0(A,x){for(var O=0;O<x;++O)A[O]=Math.random()*255|0;return A}function E0(A){if(typeof Uint8Array==="function"){var x=new Uint8Array(A);if(typeof crypto<"u")crypto.getRandomValues(x);else if(typeof msCrypto<"u")msCrypto.getRandomValues(x);else V0(x,A);return x}return V0(Array(A),A)}function c(){var A=E0(H);A[6]=A[6]&79|64,A[8]=A[8]&191|128;var x="";for(var O=0;O<H;++O){var C=A[O];if(O===4||O===6||O===8)x+="-";if(C<16)x+="0";x+=C.toString(16).toLowerCase()}return x}}function h9(H){return H.__=void 0,delete H.__,H}})})(JZ||(JZ={}))});var dq=u((JG,YZ)=>{var yY=Number.MAX_SAFE_INTEGER||9007199254740991,uY=["major","premajor","minor","preminor","patch","prepatch","prerelease"];YZ.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:yY,RELEASE_TYPES:uY,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var cq=u((ZG,zZ)=>{var gY=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...q)=>console.error("SEMVER",...q):()=>{};zZ.exports=gY});var Xq=u((Y1,wZ)=>{var{MAX_SAFE_COMPONENT_LENGTH:m9,MAX_SAFE_BUILD_LENGTH:mY,MAX_LENGTH:lY}=dq(),dY=cq();Y1=wZ.exports={};var cY=Y1.re=[],pY=Y1.safeRe=[],P=Y1.src=[],sY=Y1.safeSrc=[],E=Y1.t={},nY=0,l9="[a-zA-Z0-9-]",iY=[["\\s",1],["\\d",lY],[l9,mY]],aY=(q)=>{for(let[J,Z]of iY)q=q.split(`${J}*`).join(`${J}{0,${Z}}`).split(`${J}+`).join(`${J}{1,${Z}}`);return q},g=(q,J,Z)=>{let Q=aY(J),$=nY++;dY(q,$,J),E[q]=$,P[$]=J,sY[$]=Q,cY[$]=new RegExp(J,Z?"g":void 0),pY[$]=new RegExp(Q,Z?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*");g("NUMERICIDENTIFIERLOOSE","\\d+");g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${l9}*`);g("MAINVERSION",`(${P[E.NUMERICIDENTIFIER]})\\.(${P[E.NUMERICIDENTIFIER]})\\.(${P[E.NUMERICIDENTIFIER]})`);g("MAINVERSIONLOOSE",`(${P[E.NUMERICIDENTIFIERLOOSE]})\\.(${P[E.NUMERICIDENTIFIERLOOSE]})\\.(${P[E.NUMERICIDENTIFIERLOOSE]})`);g("PRERELEASEIDENTIFIER",`(?:${P[E.NONNUMERICIDENTIFIER]}|${P[E.NUMERICIDENTIFIER]})`);g("PRERELEASEIDENTIFIERLOOSE",`(?:${P[E.NONNUMERICIDENTIFIER]}|${P[E.NUMERICIDENTIFIERLOOSE]})`);g("PRERELEASE",`(?:-(${P[E.PRERELEASEIDENTIFIER]}(?:\\.${P[E.PRERELEASEIDENTIFIER]})*))`);g("PRERELEASELOOSE",`(?:-?(${P[E.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${P[E.PRERELEASEIDENTIFIERLOOSE]})*))`);g("BUILDIDENTIFIER",`${l9}+`);g("BUILD",`(?:\\+(${P[E.BUILDIDENTIFIER]}(?:\\.${P[E.BUILDIDENTIFIER]})*))`);g("FULLPLAIN",`v?${P[E.MAINVERSION]}${P[E.PRERELEASE]}?${P[E.BUILD]}?`);g("FULL",`^${P[E.FULLPLAIN]}$`);g("LOOSEPLAIN",`[v=\\s]*${P[E.MAINVERSIONLOOSE]}${P[E.PRERELEASELOOSE]}?${P[E.BUILD]}?`);g("LOOSE",`^${P[E.LOOSEPLAIN]}$`);g("GTLT","((?:<|>)?=?)");g("XRANGEIDENTIFIERLOOSE",`${P[E.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);g("XRANGEIDENTIFIER",`${P[E.NUMERICIDENTIFIER]}|x|X|\\*`);g("XRANGEPLAIN",`[v=\\s]*(${P[E.XRANGEIDENTIFIER]})(?:\\.(${P[E.XRANGEIDENTIFIER]})(?:\\.(${P[E.XRANGEIDENTIFIER]})(?:${P[E.PRERELEASE]})?${P[E.BUILD]}?)?)?`);g("XRANGEPLAINLOOSE",`[v=\\s]*(${P[E.XRANGEIDENTIFIERLOOSE]})(?:\\.(${P[E.XRANGEIDENTIFIERLOOSE]})(?:\\.(${P[E.XRANGEIDENTIFIERLOOSE]})(?:${P[E.PRERELEASELOOSE]})?${P[E.BUILD]}?)?)?`);g("XRANGE",`^${P[E.GTLT]}\\s*${P[E.XRANGEPLAIN]}$`);g("XRANGELOOSE",`^${P[E.GTLT]}\\s*${P[E.XRANGEPLAINLOOSE]}$`);g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${m9}})(?:\\.(\\d{1,${m9}}))?(?:\\.(\\d{1,${m9}}))?`);g("COERCE",`${P[E.COERCEPLAIN]}(?:$|[^\\d])`);g("COERCEFULL",P[E.COERCEPLAIN]+`(?:${P[E.PRERELEASE]})?(?:${P[E.BUILD]})?(?:$|[^\\d])`);g("COERCERTL",P[E.COERCE],!0);g("COERCERTLFULL",P[E.COERCEFULL],!0);g("LONETILDE","(?:~>?)");g("TILDETRIM",`(\\s*)${P[E.LONETILDE]}\\s+`,!0);Y1.tildeTrimReplace="$1~";g("TILDE",`^${P[E.LONETILDE]}${P[E.XRANGEPLAIN]}$`);g("TILDELOOSE",`^${P[E.LONETILDE]}${P[E.XRANGEPLAINLOOSE]}$`);g("LONECARET","(?:\\^)");g("CARETTRIM",`(\\s*)${P[E.LONECARET]}\\s+`,!0);Y1.caretTrimReplace="$1^";g("CARET",`^${P[E.LONECARET]}${P[E.XRANGEPLAIN]}$`);g("CARETLOOSE",`^${P[E.LONECARET]}${P[E.XRANGEPLAINLOOSE]}$`);g("COMPARATORLOOSE",`^${P[E.GTLT]}\\s*(${P[E.LOOSEPLAIN]})$|^$`);g("COMPARATOR",`^${P[E.GTLT]}\\s*(${P[E.FULLPLAIN]})$|^$`);g("COMPARATORTRIM",`(\\s*)${P[E.GTLT]}\\s*(${P[E.LOOSEPLAIN]}|${P[E.XRANGEPLAIN]})`,!0);Y1.comparatorTrimReplace="$1$2$3";g("HYPHENRANGE",`^\\s*(${P[E.XRANGEPLAIN]})\\s+-\\s+(${P[E.XRANGEPLAIN]})\\s*$`);g("HYPHENRANGELOOSE",`^\\s*(${P[E.XRANGEPLAINLOOSE]})\\s+-\\s+(${P[E.XRANGEPLAINLOOSE]})\\s*$`);g("STAR","(<|>)?=?\\s*\\*");g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var v6=u((QG,XZ)=>{var oY=Object.freeze({loose:!0}),rY=Object.freeze({}),tY=(q)=>{if(!q)return rY;if(typeof q!=="object")return oY;return q};XZ.exports=tY});var d9=u(($G,HZ)=>{var FZ=/^[0-9]+$/,_Z=(q,J)=>{let Z=FZ.test(q),Q=FZ.test(J);if(Z&&Q)q=+q,J=+J;return q===J?0:Z&&!Q?-1:Q&&!Z?1:q<J?-1:1},eY=(q,J)=>_Z(J,q);HZ.exports={compareIdentifiers:_Z,rcompareIdentifiers:eY}});var T0=u((WG,NZ)=>{var y6=cq(),{MAX_LENGTH:GZ,MAX_SAFE_INTEGER:u6}=dq(),{safeRe:g6,t:m6}=Xq(),q4=v6(),{compareIdentifiers:Fq}=d9();class Z1{constructor(q,J){if(J=q4(J),q instanceof Z1)if(q.loose===!!J.loose&&q.includePrerelease===!!J.includePrerelease)return q;else q=q.version;else if(typeof q!=="string")throw TypeError(`Invalid version. Must be a string. Got type "${typeof q}".`);if(q.length>GZ)throw TypeError(`version is longer than ${GZ} characters`);y6("SemVer",q,J),this.options=J,this.loose=!!J.loose,this.includePrerelease=!!J.includePrerelease;let Z=q.trim().match(J.loose?g6[m6.LOOSE]:g6[m6.FULL]);if(!Z)throw TypeError(`Invalid Version: ${q}`);if(this.raw=q,this.major=+Z[1],this.minor=+Z[2],this.patch=+Z[3],this.major>u6||this.major<0)throw TypeError("Invalid major version");if(this.minor>u6||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>u6||this.patch<0)throw TypeError("Invalid patch version");if(!Z[4])this.prerelease=[];else this.prerelease=Z[4].split(".").map((Q)=>{if(/^[0-9]+$/.test(Q)){let $=+Q;if($>=0&&$<u6)return $}return Q});this.build=Z[5]?Z[5].split("."):[],this.format()}format(){if(this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length)this.version+=`-${this.prerelease.join(".")}`;return this.version}toString(){return this.version}compare(q){if(y6("SemVer.compare",this.version,this.options,q),!(q instanceof Z1)){if(typeof q==="string"&&q===this.version)return 0;q=new Z1(q,this.options)}if(q.version===this.version)return 0;return this.compareMain(q)||this.comparePre(q)}compareMain(q){if(!(q instanceof Z1))q=new Z1(q,this.options);return Fq(this.major,q.major)||Fq(this.minor,q.minor)||Fq(this.patch,q.patch)}comparePre(q){if(!(q instanceof Z1))q=new Z1(q,this.options);if(this.prerelease.length&&!q.prerelease.length)return-1;else if(!this.prerelease.length&&q.prerelease.length)return 1;else if(!this.prerelease.length&&!q.prerelease.length)return 0;let J=0;do{let Z=this.prerelease[J],Q=q.prerelease[J];if(y6("prerelease compare",J,Z,Q),Z===void 0&&Q===void 0)return 0;else if(Q===void 0)return 1;else if(Z===void 0)return-1;else if(Z===Q)continue;else return Fq(Z,Q)}while(++J)}compareBuild(q){if(!(q instanceof Z1))q=new Z1(q,this.options);let J=0;do{let Z=this.build[J],Q=q.build[J];if(y6("build compare",J,Z,Q),Z===void 0&&Q===void 0)return 0;else if(Q===void 0)return 1;else if(Z===void 0)return-1;else if(Z===Q)continue;else return Fq(Z,Q)}while(++J)}inc(q,J,Z){if(q.startsWith("pre")){if(!J&&Z===!1)throw Error("invalid increment argument: identifier is empty");if(J){let Q=`-${J}`.match(this.options.loose?g6[m6.PRERELEASELOOSE]:g6[m6.PRERELEASE]);if(!Q||Q[1]!==J)throw Error(`invalid identifier: ${J}`)}}switch(q){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",J,Z);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",J,Z);break;case"prepatch":this.prerelease.length=0,this.inc("patch",J,Z),this.inc("pre",J,Z);break;case"prerelease":if(this.prerelease.length===0)this.inc("patch",J,Z);this.inc("pre",J,Z);break;case"release":if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0)this.major++;this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0)this.minor++;this.patch=0,this.prerelease=[];break;case"patch":if(this.prerelease.length===0)this.patch++;this.prerelease=[];break;case"pre":{let Q=Number(Z)?1:0;if(this.prerelease.length===0)this.prerelease=[Q];else{let $=this.prerelease.length;while(--$>=0)if(typeof this.prerelease[$]==="number")this.prerelease[$]++,$=-2;if($===-1){if(J===this.prerelease.join(".")&&Z===!1)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(Q)}}if(J){let $=[J,Q];if(Z===!1)$=[J];if(Fq(this.prerelease[0],J)===0){if(isNaN(this.prerelease[1]))this.prerelease=$}else this.prerelease=$}break}default:throw Error(`invalid increment argument: ${q}`)}if(this.raw=this.format(),this.build.length)this.raw+=`+${this.build.join(".")}`;return this}}NZ.exports=Z1});var l1=u((YG,BZ)=>{var VZ=T0(),J4=(q,J,Z=!1)=>{if(q instanceof VZ)return q;try{return new VZ(q,J)}catch(Q){if(!Z)return null;throw Q}};BZ.exports=J4});var UZ=u((zG,DZ)=>{var Z4=l1(),Q4=(q,J)=>{let Z=Z4(q,J);return Z?Z.version:null};DZ.exports=Q4});var jZ=u((wG,KZ)=>{var $4=l1(),W4=(q,J)=>{let Z=$4(q.trim().replace(/^[=v]+/,""),J);return Z?Z.version:null};KZ.exports=W4});var AZ=u((XG,LZ)=>{var IZ=T0(),Y4=(q,J,Z,Q,$)=>{if(typeof Z==="string")$=Q,Q=Z,Z=void 0;try{return new IZ(q instanceof IZ?q.version:q,Z).inc(J,Q,$).version}catch(W){return null}};LZ.exports=Y4});var EZ=u((FG,PZ)=>{var RZ=l1(),z4=(q,J)=>{let Z=RZ(q,null,!0),Q=RZ(J,null,!0),$=Z.compare(Q);if($===0)return null;let W=$>0,Y=W?Z:Q,z=W?Q:Z,X=!!Y.prerelease.length;if(!!z.prerelease.length&&!X){if(!z.patch&&!z.minor)return"major";if(z.compareMain(Y)===0){if(z.minor&&!z.patch)return"minor";return"patch"}}let F=X?"pre":"";if(Z.major!==Q.major)return F+"major";if(Z.minor!==Q.minor)return F+"minor";if(Z.patch!==Q.patch)return F+"patch";return"prerelease"};PZ.exports=z4});var kZ=u((_G,xZ)=>{var w4=T0(),X4=(q,J)=>new w4(q,J).major;xZ.exports=X4});var CZ=u((HG,OZ)=>{var F4=T0(),_4=(q,J)=>new F4(q,J).minor;OZ.exports=_4});var TZ=u((GG,bZ)=>{var H4=T0(),G4=(q,J)=>new H4(q,J).patch;bZ.exports=G4});var fZ=u((NG,MZ)=>{var N4=l1(),V4=(q,J)=>{let Z=N4(q,J);return Z&&Z.prerelease.length?Z.prerelease:null};MZ.exports=V4});var o0=u((VG,hZ)=>{var SZ=T0(),B4=(q,J,Z)=>new SZ(q,Z).compare(new SZ(J,Z));hZ.exports=B4});var yZ=u((BG,vZ)=>{var D4=o0(),U4=(q,J,Z)=>D4(J,q,Z);vZ.exports=U4});var gZ=u((DG,uZ)=>{var K4=o0(),j4=(q,J)=>K4(q,J,!0);uZ.exports=j4});var l6=u((UG,lZ)=>{var mZ=T0(),I4=(q,J,Z)=>{let Q=new mZ(q,Z),$=new mZ(J,Z);return Q.compare($)||Q.compareBuild($)};lZ.exports=I4});var cZ=u((KG,dZ)=>{var L4=l6(),A4=(q,J)=>q.sort((Z,Q)=>L4(Z,Q,J));dZ.exports=A4});var sZ=u((jG,pZ)=>{var R4=l6(),P4=(q,J)=>q.sort((Z,Q)=>R4(Q,Z,J));pZ.exports=P4});var pq=u((IG,nZ)=>{var E4=o0(),x4=(q,J,Z)=>E4(q,J,Z)>0;nZ.exports=x4});var d6=u((LG,iZ)=>{var k4=o0(),O4=(q,J,Z)=>k4(q,J,Z)<0;iZ.exports=O4});var c9=u((AG,aZ)=>{var C4=o0(),b4=(q,J,Z)=>C4(q,J,Z)===0;aZ.exports=b4});var p9=u((RG,oZ)=>{var T4=o0(),M4=(q,J,Z)=>T4(q,J,Z)!==0;oZ.exports=M4});var c6=u((PG,rZ)=>{var f4=o0(),S4=(q,J,Z)=>f4(q,J,Z)>=0;rZ.exports=S4});var p6=u((EG,tZ)=>{var h4=o0(),v4=(q,J,Z)=>h4(q,J,Z)<=0;tZ.exports=v4});var s9=u((xG,eZ)=>{var y4=c9(),u4=p9(),g4=pq(),m4=c6(),l4=d6(),d4=p6(),c4=(q,J,Z,Q)=>{switch(J){case"===":if(typeof q==="object")q=q.version;if(typeof Z==="object")Z=Z.version;return q===Z;case"!==":if(typeof q==="object")q=q.version;if(typeof Z==="object")Z=Z.version;return q!==Z;case"":case"=":case"==":return y4(q,Z,Q);case"!=":return u4(q,Z,Q);case">":return g4(q,Z,Q);case">=":return m4(q,Z,Q);case"<":return l4(q,Z,Q);case"<=":return d4(q,Z,Q);default:throw TypeError(`Invalid operator: ${J}`)}};eZ.exports=c4});var J7=u((kG,q7)=>{var p4=T0(),s4=l1(),{safeRe:s6,t:n6}=Xq(),n4=(q,J)=>{if(q instanceof p4)return q;if(typeof q==="number")q=String(q);if(typeof q!=="string")return null;J=J||{};let Z=null;if(!J.rtl)Z=q.match(J.includePrerelease?s6[n6.COERCEFULL]:s6[n6.COERCE]);else{let X=J.includePrerelease?s6[n6.COERCERTLFULL]:s6[n6.COERCERTL],w;while((w=X.exec(q))&&(!Z||Z.index+Z[0].length!==q.length)){if(!Z||w.index+w[0].length!==Z.index+Z[0].length)Z=w;X.lastIndex=w.index+w[1].length+w[2].length}X.lastIndex=-1}if(Z===null)return null;let Q=Z[2],$=Z[3]||"0",W=Z[4]||"0",Y=J.includePrerelease&&Z[5]?`-${Z[5]}`:"",z=J.includePrerelease&&Z[6]?`+${Z[6]}`:"";return s4(`${Q}.${$}.${W}${Y}${z}`,J)};q7.exports=n4});var $7=u((OG,Q7)=>{class Z7{constructor(){this.max=1000,this.map=new Map}get(q){let J=this.map.get(q);if(J===void 0)return;else return this.map.delete(q),this.map.set(q,J),J}delete(q){return this.map.delete(q)}set(q,J){if(!this.delete(q)&&J!==void 0){if(this.map.size>=this.max){let Q=this.map.keys().next().value;this.delete(Q)}this.map.set(q,J)}return this}}Q7.exports=Z7});var r0=u((CG,w7)=>{var i4=/\s+/g;class sq{constructor(q,J){if(J=o4(J),q instanceof sq)if(q.loose===!!J.loose&&q.includePrerelease===!!J.includePrerelease)return q;else return new sq(q.raw,J);if(q instanceof n9)return this.raw=q.value,this.set=[[q]],this.formatted=void 0,this;if(this.options=J,this.loose=!!J.loose,this.includePrerelease=!!J.includePrerelease,this.raw=q.trim().replace(i4," "),this.set=this.raw.split("||").map((Z)=>this.parseRange(Z.trim())).filter((Z)=>Z.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let Z=this.set[0];if(this.set=this.set.filter((Q)=>!Y7(Q[0])),this.set.length===0)this.set=[Z];else if(this.set.length>1){for(let Q of this.set)if(Q.length===1&&Qz(Q[0])){this.set=[Q];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let q=0;q<this.set.length;q++){if(q>0)this.formatted+="||";let J=this.set[q];for(let Z=0;Z<J.length;Z++){if(Z>0)this.formatted+=" ";this.formatted+=J[Z].toString().trim()}}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(q){let Z=((this.options.includePrerelease&&Jz)|(this.options.loose&&Zz))+":"+q,Q=W7.get(Z);if(Q)return Q;let $=this.options.loose,W=$?l0[y0.HYPHENRANGELOOSE]:l0[y0.HYPHENRANGE];q=q.replace(W,Gz(this.options.includePrerelease)),W0("hyphen replace",q),q=q.replace(l0[y0.COMPARATORTRIM],t4),W0("comparator trim",q),q=q.replace(l0[y0.TILDETRIM],e4),W0("tilde trim",q),q=q.replace(l0[y0.CARETTRIM],qz),W0("caret trim",q);let Y=q.split(" ").map((F)=>$z(F,this.options)).join(" ").split(/\s+/).map((F)=>Hz(F,this.options));if($)Y=Y.filter((F)=>{return W0("loose invalid filter",F,this.options),!!F.match(l0[y0.COMPARATORLOOSE])});W0("range list",Y);let z=new Map,X=Y.map((F)=>new n9(F,this.options));for(let F of X){if(Y7(F))return[F];z.set(F.value,F)}if(z.size>1&&z.has(""))z.delete("");let w=[...z.values()];return W7.set(Z,w),w}intersects(q,J){if(!(q instanceof sq))throw TypeError("a Range is required");return this.set.some((Z)=>{return z7(Z,J)&&q.set.some((Q)=>{return z7(Q,J)&&Z.every(($)=>{return Q.every((W)=>{return $.intersects(W,J)})})})})}test(q){if(!q)return!1;if(typeof q==="string")try{q=new r4(q,this.options)}catch(J){return!1}for(let J=0;J<this.set.length;J++)if(Nz(this.set[J],q,this.options))return!0;return!1}}w7.exports=sq;var a4=$7(),W7=new a4,o4=v6(),n9=nq(),W0=cq(),r4=T0(),{safeRe:l0,t:y0,comparatorTrimReplace:t4,tildeTrimReplace:e4,caretTrimReplace:qz}=Xq(),{FLAG_INCLUDE_PRERELEASE:Jz,FLAG_LOOSE:Zz}=dq(),Y7=(q)=>q.value==="<0.0.0-0",Qz=(q)=>q.value==="",z7=(q,J)=>{let Z=!0,Q=q.slice(),$=Q.pop();while(Z&&Q.length)Z=Q.every((W)=>{return $.intersects(W,J)}),$=Q.pop();return Z},$z=(q,J)=>{return W0("comp",q,J),q=zz(q,J),W0("caret",q),q=Wz(q,J),W0("tildes",q),q=Xz(q,J),W0("xrange",q),q=_z(q,J),W0("stars",q),q},u0=(q)=>!q||q.toLowerCase()==="x"||q==="*",Wz=(q,J)=>{return q.trim().split(/\s+/).map((Z)=>Yz(Z,J)).join(" ")},Yz=(q,J)=>{let Z=J.loose?l0[y0.TILDELOOSE]:l0[y0.TILDE];return q.replace(Z,(Q,$,W,Y,z)=>{W0("tilde",q,Q,$,W,Y,z);let X;if(u0($))X="";else if(u0(W))X=`>=${$}.0.0 <${+$+1}.0.0-0`;else if(u0(Y))X=`>=${$}.${W}.0 <${$}.${+W+1}.0-0`;else if(z)W0("replaceTilde pr",z),X=`>=${$}.${W}.${Y}-${z} <${$}.${+W+1}.0-0`;else X=`>=${$}.${W}.${Y} <${$}.${+W+1}.0-0`;return W0("tilde return",X),X})},zz=(q,J)=>{return q.trim().split(/\s+/).map((Z)=>wz(Z,J)).join(" ")},wz=(q,J)=>{W0("caret",q,J);let Z=J.loose?l0[y0.CARETLOOSE]:l0[y0.CARET],Q=J.includePrerelease?"-0":"";return q.replace(Z,($,W,Y,z,X)=>{W0("caret",q,$,W,Y,z,X);let w;if(u0(W))w="";else if(u0(Y))w=`>=${W}.0.0${Q} <${+W+1}.0.0-0`;else if(u0(z))if(W==="0")w=`>=${W}.${Y}.0${Q} <${W}.${+Y+1}.0-0`;else w=`>=${W}.${Y}.0${Q} <${+W+1}.0.0-0`;else if(X)if(W0("replaceCaret pr",X),W==="0")if(Y==="0")w=`>=${W}.${Y}.${z}-${X} <${W}.${Y}.${+z+1}-0`;else w=`>=${W}.${Y}.${z}-${X} <${W}.${+Y+1}.0-0`;else w=`>=${W}.${Y}.${z}-${X} <${+W+1}.0.0-0`;else if(W0("no pr"),W==="0")if(Y==="0")w=`>=${W}.${Y}.${z}${Q} <${W}.${Y}.${+z+1}-0`;else w=`>=${W}.${Y}.${z}${Q} <${W}.${+Y+1}.0-0`;else w=`>=${W}.${Y}.${z} <${+W+1}.0.0-0`;return W0("caret return",w),w})},Xz=(q,J)=>{return W0("replaceXRanges",q,J),q.split(/\s+/).map((Z)=>Fz(Z,J)).join(" ")},Fz=(q,J)=>{q=q.trim();let Z=J.loose?l0[y0.XRANGELOOSE]:l0[y0.XRANGE];return q.replace(Z,(Q,$,W,Y,z,X)=>{W0("xRange",q,Q,$,W,Y,z,X);let w=u0(W),F=w||u0(Y),_=F||u0(z),G=_;if($==="="&&G)$="";if(X=J.includePrerelease?"-0":"",w)if($===">"||$==="<")Q="<0.0.0-0";else Q="*";else if($&&G){if(F)Y=0;if(z=0,$===">")if($=">=",F)W=+W+1,Y=0,z=0;else Y=+Y+1,z=0;else if($==="<=")if($="<",F)W=+W+1;else Y=+Y+1;if($==="<")X="-0";Q=`${$+W}.${Y}.${z}${X}`}else if(F)Q=`>=${W}.0.0${X} <${+W+1}.0.0-0`;else if(_)Q=`>=${W}.${Y}.0${X} <${W}.${+Y+1}.0-0`;return W0("xRange return",Q),Q})},_z=(q,J)=>{return W0("replaceStars",q,J),q.trim().replace(l0[y0.STAR],"")},Hz=(q,J)=>{return W0("replaceGTE0",q,J),q.trim().replace(l0[J.includePrerelease?y0.GTE0PRE:y0.GTE0],"")},Gz=(q)=>(J,Z,Q,$,W,Y,z,X,w,F,_,G)=>{if(u0(Q))Z="";else if(u0($))Z=`>=${Q}.0.0${q?"-0":""}`;else if(u0(W))Z=`>=${Q}.${$}.0${q?"-0":""}`;else if(Y)Z=`>=${Z}`;else Z=`>=${Z}${q?"-0":""}`;if(u0(w))X="";else if(u0(F))X=`<${+w+1}.0.0-0`;else if(u0(_))X=`<${w}.${+F+1}.0-0`;else if(G)X=`<=${w}.${F}.${_}-${G}`;else if(q)X=`<${w}.${F}.${+_+1}-0`;else X=`<=${X}`;return`${Z} ${X}`.trim()},Nz=(q,J,Z)=>{for(let Q=0;Q<q.length;Q++)if(!q[Q].test(J))return!1;if(J.prerelease.length&&!Z.includePrerelease){for(let Q=0;Q<q.length;Q++){if(W0(q[Q].semver),q[Q].semver===n9.ANY)continue;if(q[Q].semver.prerelease.length>0){let $=q[Q].semver;if($.major===J.major&&$.minor===J.minor&&$.patch===J.patch)return!0}}return!1}return!0}});var nq=u((bG,N7)=>{var iq=Symbol("SemVer ANY");class i6{static get ANY(){return iq}constructor(q,J){if(J=X7(J),q instanceof i6)if(q.loose===!!J.loose)return q;else q=q.value;if(q=q.trim().split(/\s+/).join(" "),a9("comparator",q,J),this.options=J,this.loose=!!J.loose,this.parse(q),this.semver===iq)this.value="";else this.value=this.operator+this.semver.version;a9("comp",this)}parse(q){let J=this.options.loose?F7[_7.COMPARATORLOOSE]:F7[_7.COMPARATOR],Z=q.match(J);if(!Z)throw TypeError(`Invalid comparator: ${q}`);if(this.operator=Z[1]!==void 0?Z[1]:"",this.operator==="=")this.operator="";if(!Z[2])this.semver=iq;else this.semver=new H7(Z[2],this.options.loose)}toString(){return this.value}test(q){if(a9("Comparator.test",q,this.options.loose),this.semver===iq||q===iq)return!0;if(typeof q==="string")try{q=new H7(q,this.options)}catch(J){return!1}return i9(q,this.operator,this.semver,this.options)}intersects(q,J){if(!(q instanceof i6))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new G7(q.value,J).test(this.value)}else if(q.operator===""){if(q.value==="")return!0;return new G7(this.value,J).test(q.semver)}if(J=X7(J),J.includePrerelease&&(this.value==="<0.0.0-0"||q.value==="<0.0.0-0"))return!1;if(!J.includePrerelease&&(this.value.startsWith("<0.0.0")||q.value.startsWith("<0.0.0")))return!1;if(this.operator.startsWith(">")&&q.operator.startsWith(">"))return!0;if(this.operator.startsWith("<")&&q.operator.startsWith("<"))return!0;if(this.semver.version===q.semver.version&&this.operator.includes("=")&&q.operator.includes("="))return!0;if(i9(this.semver,"<",q.semver,J)&&this.operator.startsWith(">")&&q.operator.startsWith("<"))return!0;if(i9(this.semver,">",q.semver,J)&&this.operator.startsWith("<")&&q.operator.startsWith(">"))return!0;return!1}}N7.exports=i6;var X7=v6(),{safeRe:F7,t:_7}=Xq(),i9=s9(),a9=cq(),H7=T0(),G7=r0()});var aq=u((TG,V7)=>{var Vz=r0(),Bz=(q,J,Z)=>{try{J=new Vz(J,Z)}catch(Q){return!1}return J.test(q)};V7.exports=Bz});var D7=u((MG,B7)=>{var Dz=r0(),Uz=(q,J)=>new Dz(q,J).set.map((Z)=>Z.map((Q)=>Q.value).join(" ").trim().split(" "));B7.exports=Uz});var K7=u((fG,U7)=>{var Kz=T0(),jz=r0(),Iz=(q,J,Z)=>{let Q=null,$=null,W=null;try{W=new jz(J,Z)}catch(Y){return null}return q.forEach((Y)=>{if(W.test(Y)){if(!Q||$.compare(Y)===-1)Q=Y,$=new Kz(Q,Z)}}),Q};U7.exports=Iz});var I7=u((SG,j7)=>{var Lz=T0(),Az=r0(),Rz=(q,J,Z)=>{let Q=null,$=null,W=null;try{W=new Az(J,Z)}catch(Y){return null}return q.forEach((Y)=>{if(W.test(Y)){if(!Q||$.compare(Y)===1)Q=Y,$=new Lz(Q,Z)}}),Q};j7.exports=Rz});var R7=u((hG,A7)=>{var o9=T0(),Pz=r0(),L7=pq(),Ez=(q,J)=>{q=new Pz(q,J);let Z=new o9("0.0.0");if(q.test(Z))return Z;if(Z=new o9("0.0.0-0"),q.test(Z))return Z;Z=null;for(let Q=0;Q<q.set.length;++Q){let $=q.set[Q],W=null;if($.forEach((Y)=>{let z=new o9(Y.semver.version);switch(Y.operator){case">":if(z.prerelease.length===0)z.patch++;else z.prerelease.push(0);z.raw=z.format();case"":case">=":if(!W||L7(z,W))W=z;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${Y.operator}`)}}),W&&(!Z||L7(Z,W)))Z=W}if(Z&&q.test(Z))return Z;return null};A7.exports=Ez});var E7=u((vG,P7)=>{var xz=r0(),kz=(q,J)=>{try{return new xz(q,J).range||"*"}catch(Z){return null}};P7.exports=kz});var a6=u((yG,C7)=>{var Oz=T0(),O7=nq(),{ANY:Cz}=O7,bz=r0(),Tz=aq(),x7=pq(),k7=d6(),Mz=p6(),fz=c6(),Sz=(q,J,Z,Q)=>{q=new Oz(q,Q),J=new bz(J,Q);let $,W,Y,z,X;switch(Z){case">":$=x7,W=Mz,Y=k7,z=">",X=">=";break;case"<":$=k7,W=fz,Y=x7,z="<",X="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(Tz(q,J,Q))return!1;for(let w=0;w<J.set.length;++w){let F=J.set[w],_=null,G=null;if(F.forEach((B)=>{if(B.semver===Cz)B=new O7(">=0.0.0");if(_=_||B,G=G||B,$(B.semver,_.semver,Q))_=B;else if(Y(B.semver,G.semver,Q))G=B}),_.operator===z||_.operator===X)return!1;if((!G.operator||G.operator===z)&&W(q,G.semver))return!1;else if(G.operator===X&&Y(q,G.semver))return!1}return!0};C7.exports=Sz});var T7=u((uG,b7)=>{var hz=a6(),vz=(q,J,Z)=>hz(q,J,">",Z);b7.exports=vz});var f7=u((gG,M7)=>{var yz=a6(),uz=(q,J,Z)=>yz(q,J,"<",Z);M7.exports=uz});var v7=u((mG,h7)=>{var S7=r0(),gz=(q,J,Z)=>{return q=new S7(q,Z),J=new S7(J,Z),q.intersects(J,Z)};h7.exports=gz});var u7=u((lG,y7)=>{var mz=aq(),lz=o0();y7.exports=(q,J,Z)=>{let Q=[],$=null,W=null,Y=q.sort((F,_)=>lz(F,_,Z));for(let F of Y)if(mz(F,J,Z)){if(W=F,!$)$=F}else{if(W)Q.push([$,W]);W=null,$=null}if($)Q.push([$,null]);let z=[];for(let[F,_]of Q)if(F===_)z.push(F);else if(!_&&F===Y[0])z.push("*");else if(!_)z.push(`>=${F}`);else if(F===Y[0])z.push(`<=${_}`);else z.push(`${F} - ${_}`);let X=z.join(" || "),w=typeof J.raw==="string"?J.raw:String(J);return X.length<w.length?X:J}});var p7=u((dG,c7)=>{var g7=r0(),t9=nq(),{ANY:r9}=t9,oq=aq(),e9=o0(),dz=(q,J,Z={})=>{if(q===J)return!0;q=new g7(q,Z),J=new g7(J,Z);let Q=!1;q:for(let $ of q.set){for(let W of J.set){let Y=pz($,W,Z);if(Q=Q||Y!==null,Y)continue q}if(Q)return!1}return!0},cz=[new t9(">=0.0.0-0")],m7=[new t9(">=0.0.0")],pz=(q,J,Z)=>{if(q===J)return!0;if(q.length===1&&q[0].semver===r9)if(J.length===1&&J[0].semver===r9)return!0;else if(Z.includePrerelease)q=cz;else q=m7;if(J.length===1&&J[0].semver===r9)if(Z.includePrerelease)return!0;else J=m7;let Q=new Set,$,W;for(let B of q)if(B.operator===">"||B.operator===">=")$=l7($,B,Z);else if(B.operator==="<"||B.operator==="<=")W=d7(W,B,Z);else Q.add(B.semver);if(Q.size>1)return null;let Y;if($&&W){if(Y=e9($.semver,W.semver,Z),Y>0)return null;else if(Y===0&&($.operator!==">="||W.operator!=="<="))return null}for(let B of Q){if($&&!oq(B,String($),Z))return null;if(W&&!oq(B,String(W),Z))return null;for(let R of J)if(!oq(B,String(R),Z))return!1;return!0}let z,X,w,F,_=W&&!Z.includePrerelease&&W.semver.prerelease.length?W.semver:!1,G=$&&!Z.includePrerelease&&$.semver.prerelease.length?$.semver:!1;if(_&&_.prerelease.length===1&&W.operator==="<"&&_.prerelease[0]===0)_=!1;for(let B of J){if(F=F||B.operator===">"||B.operator===">=",w=w||B.operator==="<"||B.operator==="<=",$){if(G){if(B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===G.major&&B.semver.minor===G.minor&&B.semver.patch===G.patch)G=!1}if(B.operator===">"||B.operator===">="){if(z=l7($,B,Z),z===B&&z!==$)return!1}else if($.operator===">="&&!oq($.semver,String(B),Z))return!1}if(W){if(_){if(B.semver.prerelease&&B.semver.prerelease.length&&B.semver.major===_.major&&B.semver.minor===_.minor&&B.semver.patch===_.patch)_=!1}if(B.operator==="<"||B.operator==="<="){if(X=d7(W,B,Z),X===B&&X!==W)return!1}else if(W.operator==="<="&&!oq(W.semver,String(B),Z))return!1}if(!B.operator&&(W||$)&&Y!==0)return!1}if($&&w&&!W&&Y!==0)return!1;if(W&&F&&!$&&Y!==0)return!1;if(G||_)return!1;return!0},l7=(q,J,Z)=>{if(!q)return J;let Q=e9(q.semver,J.semver,Z);return Q>0?q:Q<0?J:J.operator===">"&&q.operator===">="?J:q},d7=(q,J,Z)=>{if(!q)return J;let Q=e9(q.semver,J.semver,Z);return Q<0?q:Q>0?J:J.operator==="<"&&q.operator==="<="?J:q};c7.exports=dz});var _q=u((cG,i7)=>{var qJ=Xq(),s7=dq(),sz=T0(),n7=d9(),nz=l1(),iz=UZ(),az=jZ(),oz=AZ(),rz=EZ(),tz=kZ(),ez=CZ(),q3=TZ(),J3=fZ(),Z3=o0(),Q3=yZ(),$3=gZ(),W3=l6(),Y3=cZ(),z3=sZ(),w3=pq(),X3=d6(),F3=c9(),_3=p9(),H3=c6(),G3=p6(),N3=s9(),V3=J7(),B3=nq(),D3=r0(),U3=aq(),K3=D7(),j3=K7(),I3=I7(),L3=R7(),A3=E7(),R3=a6(),P3=T7(),E3=f7(),x3=v7(),k3=u7(),O3=p7();i7.exports={parse:nz,valid:iz,clean:az,inc:oz,diff:rz,major:tz,minor:ez,patch:q3,prerelease:J3,compare:Z3,rcompare:Q3,compareLoose:$3,compareBuild:W3,sort:Y3,rsort:z3,gt:w3,lt:X3,eq:F3,neq:_3,gte:H3,lte:G3,cmp:N3,coerce:V3,Comparator:B3,Range:D3,satisfies:U3,toComparators:K3,maxSatisfying:j3,minSatisfying:I3,minVersion:L3,validRange:A3,outside:R3,gtr:P3,ltr:E3,intersects:x3,simplifyRange:k3,subset:O3,SemVer:sz,re:qJ.re,src:qJ.src,tokens:qJ.t,SEMVER_SPEC_VERSION:s7.SEMVER_SPEC_VERSION,RELEASE_TYPES:s7.RELEASE_TYPES,compareIdentifiers:n7.compareIdentifiers,rcompareIdentifiers:n7.rcompareIdentifiers}});var rb=k1(O6(),1);class C6{cla;ins;p1;p2;data;constructor(q,J,Z,Q,$){this.cla=q,this.ins=J,this.p1=Z,this.p2=Q,this.data=$??new Uint8Array}getRawApdu(){let q=Uint8Array.from([this.cla,this.ins,this.p1,this.p2,this.data.length]),J=new Uint8Array(q.length+this.data.length);return J.set(q,0),this.data.length>0&&J.set(this.data,q.length),J}}function TY(q){return typeof q=="string"&&/^0x[0-9a-fA-F]*$/.test(q)}function _1(q){if(q.startsWith("0x")&&(q=q.slice(2)),q.length===0)return new Uint8Array;if(q.length%2!==0&&(q="0"+q),/^[0-9a-fA-F]*$/.test(q)===!1)return null;let J=q.match(/.{1,2}/g)?.map((Z)=>parseInt(Z,16));return!J||J.some(isNaN)?null:new Uint8Array(J)}function D0(q,J=!0){return`${J?"0x":""}${Array.from(q,(Z)=>Z.toString(16).padStart(2,"0")).join("")}`}class mq{_tag="ValueOverflow";originalError;message;constructor(q,J=lq){this.message=`Value overflow for ${q}, max is ${J}`}}class Wq{_tag="DataOverflow";message;originalError;constructor(q,J=0){this.message=J===0?`this.data is already full (value: ${q})`:`this.data will overflow with "${q}", remaining bytes: ${J}`}}class b6{_tag="HexaString";message;originalError;constructor(q){this.message=`Invalid encoded hexa string or length is null: ${q}`}}var MY=4294967295;class T6{constructor(q=MY){this.maxPayloadSize=q}data=new Uint8Array;errors=[];build=()=>this.data;tryBuild=()=>this.hasErrors()?void 0:this.data;add8BitUIntToData=(q)=>this.addNumberToData(q,8n,!1,!1);add16BitUIntToData=(q,J=!0)=>this.addNumberToData(q,16n,!1,J);add32BitUIntToData=(q,J=!0)=>this.addNumberToData(q,32n,!1,J);add64BitUIntToData=(q,J=!0)=>this.addNumberToData(q,64n,!1,J);add128BitUIntToData=(q,J=!0)=>this.addNumberToData(q,128n,!1,J);add256BitUIntToData=(q,J=!0)=>this.addNumberToData(q,256n,!1,J);add16BitIntToData=(q,J=!0)=>this.addNumberToData(q,16n,!0,J);add32BitIntToData=(q,J=!0)=>this.addNumberToData(q,32n,!0,J);add64BitIntToData=(q,J=!0)=>this.addNumberToData(q,64n,!0,J);add128BitIntToData=(q,J=!0)=>this.addNumberToData(q,128n,!0,J);add256BitIntToData=(q,J=!0)=>this.addNumberToData(q,256n,!0,J);addBufferToData=(q)=>this.hasEnoughLengthRemaining(q)?(this.data=Uint8Array.from([...this.data,...q]),this):(this.errors.push(new Wq(q.toString())),this);addHexaStringToData=(q)=>{let J=_1(q);return J===null||J.length===0?(this.errors.push(new b6(q)),this):(this.addBufferToData(J),this)};addAsciiStringToData=(q)=>{let J=new TextEncoder().encode(q);return this.addBufferToData(J),this};encodeInLVFromHexa=(q)=>{let J=_1(q);return J===null||J.length===0?(this.errors.push(new b6(q)),this):this.hasEnoughLengthRemaining(J,!0)?(this.add8BitUIntToData(J.length),this.addBufferToData(J),this):(this.errors.push(new Wq(q)),this)};encodeInLVFromBuffer=(q)=>this.hasEnoughLengthRemaining(q,!0)?(this.add8BitUIntToData(q.length),this.addBufferToData(q),this):(this.errors.push(new Wq(q.toString())),this);encodeInLVFromAscii=(q)=>this.hasEnoughLengthRemaining(q,!0)?(this.add8BitUIntToData(q.length),this.addAsciiStringToData(q),this):(this.errors.push(new Wq(q)),this);encodeInTLVFromAscii=(q,J)=>(this.add8BitUIntToData(q),this.encodeInLVFromAscii(J));encodeInTLVFromHexa=(q,J)=>(this.add8BitUIntToData(q),this.encodeInLVFromHexa(J));encodeInTLVFromBuffer=(q,J)=>(this.add8BitUIntToData(q),this.encodeInLVFromBuffer(J));encodeInTLVFromUInt8=(q,J)=>(this.add8BitUIntToData(q),this.add8BitUIntToData(1),this.add8BitUIntToData(J));encodeInTLVFromUInt16=(q,J,Z=!0)=>(this.add8BitUIntToData(q),this.add8BitUIntToData(2),this.add16BitUIntToData(J,Z));encodeInTLVFromUInt32=(q,J,Z=!0)=>(this.add8BitUIntToData(q),this.add8BitUIntToData(4),this.add32BitUIntToData(J,Z));encodeInTLVFromUInt64=(q,J,Z=!0)=>(this.add8BitUIntToData(q),this.add8BitUIntToData(8),this.add64BitUIntToData(J,Z));getAvailablePayloadLength=()=>this.maxPayloadSize-this.data.length;getErrors=()=>this.errors;hasErrors=()=>this.errors.length!==0;hasEnoughLengthRemaining=(q,J=!1)=>this.data.length+q.length+(J?1:0)<=this.maxPayloadSize;addNumberToData(q,J,Z,Q){let $=this.checkBoundsAndConvert(q,J,Z);if($===void 0)return this;let W=Number(J)/8,Y=new Uint8Array(W);if(Q)for(let z=W-1;z>=0;z--)Y[z]=Number($&0xffn),$>>=8n;else for(let z=0;z<W;z++)Y[z]=Number($&0xffn),$>>=8n;return this.addBufferToData(Y)}checkBoundsAndConvert(q,J,Z){if(typeof q=="number"){if(!Number.isInteger(q)||q>Number.MAX_SAFE_INTEGER){this.errors.push(new mq(q.toString()));return}q=BigInt(q)}if(Z){let Q=1n<<J-1n;if(q>=Q||q<-Q){this.errors.push(new mq(q.toString(),Q-1n));return}if(q<0n){let $=(1n<<J)-1n;q=-q,q=(~q&$)+1n}}else{let Q=1n<<J;if(q<0||q>=Q){this.errors.push(new mq(q.toString(),Q-1n));return}}return q}}var lq=255,ZH=lq+5;class H0{_ins;_cla;_p1;p2;data=new T6(lq);constructor({ins:q,cla:J,p1:Z,p2:Q}){this._cla=J&255,this._ins=q&255,this._p1=Z&255,this.p2=Q&255}build=()=>new C6(this._cla,this._ins,this._p1,this.p2,this.data.build());add8BitUIntToData=(q)=>(this.data.add8BitUIntToData(q),this);add16BitUIntToData=(q)=>(this.data.add16BitUIntToData(q),this);add32BitUIntToData=(q)=>(this.data.add32BitUIntToData(q),this);add64BitUIntToData=(q,J=!0)=>(this.data.add64BitUIntToData(q,J),this);addBufferToData=(q)=>(this.data.addBufferToData(q),this);addHexaStringToData=(q)=>(this.data.addHexaStringToData(q),this);addAsciiStringToData=(q)=>(this.data.addAsciiStringToData(q),this);encodeInLVFromHexa=(q)=>(this.data.encodeInLVFromHexa(q),this);encodeInLVFromBuffer=(q)=>(this.data.encodeInLVFromBuffer(q),this);encodeInLVFromAscii=(q)=>(this.data.encodeInLVFromAscii(q),this);getAvailablePayloadLength=()=>this.data.getAvailablePayloadLength();getErrors=()=>this.data.getErrors()}class M6{constructor(q){this.buffer=q}index=0;testMinimalLength(q){return q<=this.buffer.length-this.index}extract8BitUInt(){if(!this.outOfRange(1))return this.buffer[this.index++]}extract16BitUInt(q=!0){let J=this.extractNumber(16n,!1,q);return J===void 0?void 0:Number(J)}extract16BitInt(q=!0){let J=this.extractNumber(16n,!0,q);return J===void 0?void 0:Number(J)}extract32BitUInt(q=!0){let J=this.extractNumber(32n,!1,q);return J===void 0?void 0:Number(J)}extract32BitInt(q=!0){let J=this.extractNumber(32n,!0,q);return J===void 0?void 0:Number(J)}extract64BitUInt(q=!0){return this.extractNumber(64n,!1,q)}extract64BitInt(q=!0){return this.extractNumber(64n,!0,q)}extract128BitUInt(q=!0){return this.extractNumber(128n,!1,q)}extract128BitInt(q=!0){return this.extractNumber(128n,!0,q)}extract256BitUInt(q=!0){return this.extractNumber(256n,!1,q)}extract256BitInt(q=!0){return this.extractNumber(256n,!0,q)}extractFieldByLength(q){if(this.outOfRange(q))return;if(q===0)return new Uint8Array;let J=this.buffer.slice(this.index,this.index+q);return this.index+=q,J}extractFieldLVEncoded(){let q=this.extract8BitUInt();if(q===void 0)return;if(q===0)return new Uint8Array;let J=this.extractFieldByLength(q);return J===void 0&&this.index--,J}extractFieldTLVEncoded(){if(this.outOfRange(2))return;let q=this.index,J=this.extract8BitUInt(),Z=this.extractFieldLVEncoded();if(J===void 0||Z===void 0){this.index--;return}let Q=this.index;return{tag:J,value:Z,tlv:this.buffer.slice(q,Q)}}encodeToHexaString(q,J=!1){if(q===void 0||q.length===0)return"";let Z=D0(q);return J?Z:Z.slice(2)}encodeToString(q){let J="",Z=0;if(!q)return J;for(;Z<=q.length;){let Q=q[Z];Q&&(J+=String.fromCharCode(Q)),Z++}return J}getCurrentIndex(){return this.index}resetIndex(){this.index=0}getUnparsedRemainingLength(){return this.buffer.length-this.index}outOfRange(q){return this.index+q>this.buffer.length}extractNumber(q,J,Z){let Q=Number(q)/8;if(this.outOfRange(Q))return;let $=0n;if(Z)for(let W=0;W<Q;W++)$=$<<8n|BigInt(this.buffer[W+this.index]);else for(let W=Q-1;W>=0;W--)$=$<<8n|BigInt(this.buffer[W+this.index]);if(J){let W=1n<<q-1n;$&W&&($-=W<<1n)}return this.index+=Q,$}}class z0{parser;constructor(q){this.parser=new M6(q.data)}testMinimalLength=(q)=>this.parser.testMinimalLength(q);extract8BitUInt=()=>this.parser.extract8BitUInt();extract16BitUInt=()=>this.parser.extract16BitUInt();extract32BitUInt=()=>this.parser.extract32BitUInt();extractFieldByLength=(q)=>this.parser.extractFieldByLength(q);extractFieldLVEncoded=()=>this.parser.extractFieldLVEncoded();extractFieldTLVEncoded=()=>this.parser.extractFieldTLVEncoded();encodeToHexaString(q,J=!1){return J?this.parser.encodeToHexaString(q,!0):this.parser.encodeToHexaString(q,!1)}encodeToString=(q)=>this.parser.encodeToString(q);getUnparsedRemainingLength=()=>this.parser.getUnparsedRemainingLength()}class H1{_tag="InvalidStatusWordError";originalError;constructor(q){this.originalError=Error(q??"Invalid status word.")}}class Yq{_tag="InvalidResponseFormatError";originalError;constructor(q){this.originalError=Error(q??"Invalid response format.")}}var f6=((q)=>(q.Error="ERROR",q.Success="SUCCESS",q))(f6||{});function fY(q){return"error"in q&&q.error!==void 0}function i0(q){return fY(q)?{status:"ERROR",error:q.error}:{status:"SUCCESS",data:q.data}}function x1(q){return q.status==="SUCCESS"}function T({data:q,error:J}){return J!==void 0?i0({error:J}):i0({data:q})}function n(q){return x1(q)}class l{static isValidStatusCode(q){return q.length===2}static isSuccessResponse({statusCode:q}){return l.isValidStatusCode(q)?q[0]===144&&q[1]===0:!1}static isLockedDeviceResponse({statusCode:q}){return l.isValidStatusCode(q)?q[0]===85&&q[1]===21||q[0]===105&&q[1]===130||q[0]===83&&q[1]===3:!1}static isRefusedByUser({statusCode:q}){return l.isValidStatusCode(q)?q[0]===85&&q[1]===1||q[0]===105&&q[1]===133:!1}static isAppAlreadyInstalled({statusCode:q}){return l.isValidStatusCode(q)?q[0]===106&&q[1]===128||q[0]===106&&q[1]===129||q[0]===106&&q[1]===142||q[0]===106&&q[1]===143:!1}static isOutOfMemory({statusCode:q}){return l.isValidStatusCode(q)?q[0]===106&&q[1]===132||q[0]===106&&q[1]===133||q[0]===81&&q[1]===2||q[0]===81&&q[1]===3:!1}static isApduThatTriggersDisconnection(q){let J=new Map;return J.set("openApp",new Uint8Array([224,216,0,0])),J.set("closeApp",new Uint8Array([176,167,0,0])),Array.from(J.values()).some((Z)=>{for(let Q=0;Q<4;Q++)if(Z[Q]!==q[Q])return!1;return!0})}}class h0{_tag;originalError;errorCode;message;constructor({tag:q,errorCode:J,originalError:Z,message:Q}){this._tag=q,this.originalError=Z,this.errorCode=J,this.message=Q??"An error occured during device exchange."}}class zq{_tag="UnknownDeviceExchangeError";originalError;message;constructor(q){this.originalError=q,this.message="Unexpected device exchange error happened."}}class SY{_tag="DeviceBusyError";originalError;constructor(q){this.originalError=q??Error("Device is busy, please try again later")}}class hY{_tag="InvalidArgumentError";originalError;constructor(q){this.originalError=Error(q??"Invalid argument.")}}var v0=(q,J)=>Object.keys(J).includes(q);class y9 extends h0{constructor(q){super({tag:"GlobalCommandError",...q})}}var v9={5515:{message:"Device is locked.",tag:"DeviceLockedError"},5501:{message:"Action refused on device.",tag:"ActionRefusedError"},5502:{message:"Pin is not set",tag:"PinNotSetError"},5223:{message:"Device internal error",tag:"DeviceInternalError"},"6e00":{message:"CLA not supported",tag:"DeviceInternalError"},"6d00":{message:"INS not supported",tag:"DeviceInternalError"}};class G0{static handle(q){let J=new z0(q).encodeToHexaString(q.statusCode);return v0(J,v9)?new y9({...v9[J],errorCode:J}):new zq({message:"UnknownError",errorCode:J})}}class wq{name="closeApp";args=void 0;triggersDisconnection=!0;getApdu(){return new H0({cla:176,ins:167,p1:0,p2:0}).build()}parseResponse(q){return l.isSuccessResponse(q)?T({data:void 0}):T({error:G0.handle(q)})}}var ZZ={"681a":{message:"Invalid LANG_ID value."}};class u9 extends h0{constructor({message:q,errorCode:J}){super({message:q,errorCode:J,tag:"DeleteLanguagePackCommandError"})}}class S6{constructor(q){this.args=q}name="deleteLanguagePack";getApdu(){let q={cla:224,ins:51,p1:this.args.languagePackageId,p2:0};return new H0(q).build()}parseResponse(q){let J=new z0(q);if(!l.isSuccessResponse(q)){let Z=J.encodeToHexaString(q.statusCode);return v0(Z,ZZ)?T({error:new u9({...ZZ[Z],errorCode:Z})}):T({error:G0.handle(q)})}return T({data:void 0})}}class a0{name="getAppAndVersion";args=void 0;getApdu(){return new H0({cla:176,ins:1,p1:0,p2:0}).build()}parseResponse(q){if(!l.isSuccessResponse(q))return T({error:G0.handle(q)});let J=new z0(q);if(J.extract8BitUInt()!==1)return T({error:new Yq("getAppAndVersion: format not supported")});let Z=J.encodeToString(J.extractFieldLVEncoded()),Q=J.encodeToString(J.extractFieldLVEncoded());if(J.getUnparsedRemainingLength()===0)return T({data:{name:Z,version:Q}});let $=J.extractFieldLVEncoded();return T({data:{name:Z,version:Q,flags:$}})}}var QZ={"662e":{message:"Invalid state, no background image loaded."},"662f":{message:"Invalid state, device is in recovery mode."}};class g9 extends h0{constructor({message:q,errorCode:J}){super({message:q,errorCode:J,tag:"GetBackgroundImageSizeCommandError"})}}class h6{name="getBackgroundImageSize";getApdu(){return new H0({cla:224,ins:100,p1:0,p2:0}).build()}parseResponse(q){let J=new z0(q);if(!l.isSuccessResponse(q)){let Q=J.encodeToHexaString(q.statusCode);return v0(Q,QZ)?T({error:new g9({...QZ[Q],errorCode:Q})}):T({error:G0.handle(q)})}let Z=J.extract32BitUInt();return Z===void 0?T({error:new H1("Didn't receive any size")}):T({data:Z})}}var $Z=((q)=>(q[q.BATTERY_PERCENTAGE=0]="BATTERY_PERCENTAGE",q[q.BATTERY_VOLTAGE=1]="BATTERY_VOLTAGE",q[q.BATTERY_TEMPERATURE=2]="BATTERY_TEMPERATURE",q[q.BATTERY_CURRENT=3]="BATTERY_CURRENT",q[q.BATTERY_FLAGS=4]="BATTERY_FLAGS",q))($Z||{}),vY=((q)=>(q[q.NONE=0]="NONE",q[q.USB=1]="USB",q[q.QI=2]="QI",q))(vY||{});class WZ{name="getBatteryStatus";args;constructor(q){this.args=q}getApdu(){let q={cla:224,ins:16,p1:0,p2:this.args.statusType};return new H0(q).build()}parseResponse(q){if(!l.isSuccessResponse(q))return T({error:G0.handle(q)});let J=new z0(q),Z=(Q)=>T({error:new Yq(Q)});switch(this.args.statusType){case 0:{let Q=J.extract8BitUInt();return Q===void 0?Z("getBatteryStatus: missing battery percentage in response"):T({data:Q>100?-1:Q})}case 1:{let Q=J.extract16BitUInt();return Q===void 0?Z("getBatteryStatus: missing battery voltage in response"):T({data:Q})}case 2:case 3:{let Q=J.extract8BitUInt();return Q===void 0?Z(this.args.statusType===2?"getBatteryStatus: missing battery temperature in response":"getBatteryStatus: missing battery current in response"):T({data:Q<<24>>24})}case 4:{let Q=J.extract32BitUInt();if(Q===void 0)return Z("getBatteryStatus: missing battery flags in response");let $=!!(Q&8),W=!$&&!!(Q&1);return T({data:{charging:W?2:$?1:0,issueCharging:!!(Q&16),issueTemperature:!!(Q&32),issueBattery:!!(Q&128)}})}default:return Z("getBatteryStatus: unsupported battery status type")}}}var d0=k1(_q(),1);var o=((q)=>(q.NANO_S="nanoS",q.NANO_SP="nanoSP",q.NANO_X="nanoX",q.STAX="stax",q.FLEX="flex",q.APEX="apexp",q))(o||{});class Hq{id;model;name;constructor({id:q,model:J,name:Z}){this.id=q,this.model=J,this.name=Z}}var C3=11415;var rq={Twelve:12,Eighteen:18,TwentyFour:24},U0=((q)=>(q.Unknown="unknown",q.WelcomeScreen1="welcome-screen-1",q.WelcomeScreen2="welcome-screen-2",q.WelcomeScreen3="welcome-screen-3",q.WelcomeScreen4="welcome-screen-4",q.WelcomeScreenReminder="welcome-screen-reminder",q.SetupChoice="setup-choice",q.Pin="pin",q.NewDevice="new-device",q.ConfirmNewDevice="confirm-new-device",q.RestoreRecoveryPhrase="restore-recovery-phrase",q.SafetyWarning="safety-warning",q.DeviceIsReady="device-is-ready",q.ChooseName="choose-name",q.RestoreRecoverBackup="restore-recover-backup",q.SetupRestoreChoice="setup-restore-choice",q.OnboardingStatusCheck="onboarding-status-check",q.RestoreWithRk="restore-with-rk",q))(U0||{});var b3={0:U0.WelcomeScreen1,1:U0.WelcomeScreen2,2:U0.WelcomeScreen3,3:U0.WelcomeScreen4,4:U0.WelcomeScreenReminder,5:U0.SetupChoice,6:U0.Pin,7:U0.NewDevice,8:U0.ConfirmNewDevice,9:U0.RestoreRecoveryPhrase,10:U0.SafetyWarning,11:U0.DeviceIsReady,12:U0.ChooseName,13:U0.RestoreRecoverBackup,14:U0.SetupRestoreChoice,15:U0.OnboardingStatusCheck,16:U0.RestoreWithRk};class JJ{seFlags;constructor(q){this.seFlags=new Uint8Array(4),this.seFlags.set(q.subarray(0,this.seFlags.length))}generalDeviceState(){let q=this.seFlags[0]??0;return{isPinValidated:this._checkNthBitInByte(q,1),hasMcuSerialNumber:this._checkNthBitInByte(q,2),hasValidCertificate:this._checkNthBitInByte(q,3),isCustomAuthorityConnectionAllowed:this._checkNthBitInByte(q,4),isSecureConnectionAllowed:this._checkNthBitInByte(q,5),isOnboarded:this._checkNthBitInByte(q,6),isMcuCodeSigned:this._checkNthBitInByte(q,7),isInRecoveryMode:this._checkNthBitInByte(q,8)}}endorsementInformation(){let q=this.seFlags[1]??0;return{hasEndorsementCertificateInSlot1:(q&1)!==0,hasEndorsementCertificateInSlot2:(q&2)!==0}}wordsInformation(){let q=this.seFlags[2]??0,J=q>>5&3;return{numberOfWords:[rq.TwentyFour,rq.Eighteen,rq.Twelve,void 0][J],currentWordIndex:q&31}}onboardingStatus(){let q=this.seFlags[3]??0;return{onboardingState:b3[q]??U0.Unknown}}_checkNthBitInByte(q,J){return(q>>8-J&1)===1}}class M0{name="getOsVersion";args=void 0;getApdu(){return new H0({cla:224,ins:1,p1:0,p2:0}).build()}parseResponse(q,J){if(!l.isSuccessResponse(q))return T({error:G0.handle(q)});let Z=new z0(q),Q=Z.extract32BitUInt();if(Q===void 0)return T({error:new H1("Missing target ID in OS version")});let $=Z.encodeToString(Z.extractFieldLVEncoded()),W=Z.extractFieldLVEncoded()??new Uint8Array(0),Y=new JJ(W),z={...Y.generalDeviceState(),...Y.endorsementInformation(),...Y.wordsInformation(),...Y.onboardingStatus()};$||($="0.0.0",W=new Uint8Array);let X=(Q&4026531840)!==805306368,w=$.includes("-osu"),F="",_="",G="",B="",R,S,e,s0;if(X){G=$,R=Q;let P0=Z.extractFieldLVEncoded();P0&&(P0.length>=5?(F=Z.encodeToString(P0),S=parseInt(Z.encodeToHexaString(Z.extractFieldLVEncoded()),16)):S=parseInt(Z.encodeToHexaString(P0),16))}else{if(F=$,S=Q,_=Z.encodeToString(Z.extractFieldLVEncoded()),this.isBootloaderVersionSupported(F,J)&&(G=Z.encodeToString(Z.extractFieldLVEncoded())),this.isHardwareVersionSupported(F,J)?B=Z.encodeToHexaString(Z.extractFieldLVEncoded()):B="00",this.isLocalizationSupported(F,J)){let P0=Z.extractFieldLVEncoded();P0!==void 0&&(e=parseInt(Z.encodeToHexaString(P0),16))}if(this.isRecoverSupported(F,J)){let P0=Z.extractFieldLVEncoded();P0!==void 0&&(s0=parseInt(Z.encodeToHexaString(P0),16))}}return T({data:{isBootloader:X,isOsu:w,targetId:Q,seTargetId:S,mcuTargetId:R,seVersion:F,seFlags:W,mcuSephVersion:_,mcuBootloaderVersion:G,hwVersion:B,langId:e,recoverState:s0,secureElementFlags:z}})}isBootloaderVersionSupported(q,J){let Z=d0.coerce(q)??"";switch(J){case o.NANO_S:case o.NANO_X:return d0.gte(Z,"2.0.0");default:return!0}}isHardwareVersionSupported(q,J){let Z=d0.coerce(q)??"";switch(J){case o.NANO_X:return d0.gte(Z,"2.0.0");default:return!1}}isLocalizationSupported(q,J){let Z=d0.coerce(q)??"";switch(J){case o.NANO_S:return!1;case o.NANO_SP:return d0.gte(Z,"1.1.0");case o.NANO_X:return d0.gte(Z,"2.1.0");default:return!0}}isRecoverSupported(q,J){let Z=d0.coerce(q)??"";switch(J){case o.NANO_S:return!1;case o.NANO_SP:return d0.gte(Z,"1.1.2");case o.NANO_X:return d0.gte(Z,"2.2.3");case o.STAX:return d0.gte(Z,"1.4.0");case o.FLEX:return d0.gte(Z,"1.0.1");default:return!0}}}var a7={6624:{message:"Invalid state (List applications command must be sent)"}};class o7 extends h0{constructor({message:q,errorCode:J}){super({message:q,errorCode:J,tag:"ListAppsCommandError"})}}class o6{name="listApps";args;constructor(q={isContinue:!1}){this.args=q}getApdu(){let q={cla:224,ins:this.args.isContinue?223:222,p1:0,p2:0};return new H0(q).build()}parseResponse(q){let J=[],Z=new z0(q);if(!l.isSuccessResponse(q)){let Q=Z.encodeToHexaString(q.statusCode);return v0(Q,a7)?T({error:new o7({...a7[Q],errorCode:Q})}):T({error:G0.handle(q)})}if(q.data.length<=0)return T({data:[]});for(Z.extract8BitUInt();Z.getUnparsedRemainingLength()>0;){let Q=Z.extract8BitUInt(),$=Z.extract16BitUInt();Z.extract16BitUInt();let W=Z.encodeToHexaString(Z.extractFieldByLength(32)),Y=Z.encodeToHexaString(Z.extractFieldByLength(32)),z=Z.encodeToString(Z.extractFieldLVEncoded());J.push({appEntryLength:Q,appSizeInBlocks:$,appCodeHash:W,appFullHash:Y,appName:z})}return T({data:J})}}var r7={"662d":{message:"Invalid LIST_ARG, first command must be sent with P1_LIST_LANGUAGE_PACKS_FIRST."}};class ZJ extends h0{constructor({message:q,errorCode:J}){super({message:q,errorCode:J,tag:"ListLanguagePackCommandError"})}}class r6{constructor(q){this.args=q}name="listLanguagePack";getApdu(){let q={cla:224,ins:52,p1:this.args.firstChunk?0:1,p2:0};return new H0(q).build()}parseResponse(q){let J=new z0(q);if(!l.isSuccessResponse(q)){let Y=J.encodeToHexaString(q.statusCode);return v0(Y,r7)?T({error:new ZJ({...r7[Y],errorCode:Y})}):T({error:G0.handle(q)})}if(J.extract8BitUInt()===void 0)return T({data:void 0});J.extract8BitUInt();let Z=J.extractFieldLVEncoded();if(Z===void 0)return T({error:new H1("Failed to get language pack id")});let Q=J.extractFieldLVEncoded();if(Q===void 0)return T({error:new H1("Failed to get language pack size")});let $=parseInt(D0(Z),16),W=parseInt(D0(Q),16);return T({data:{id:$,size:W}})}}var t7={"422f":{message:"Incorrect structure type"},4230:{message:"Incorrect certificate version"},4231:{message:"Incorrect certificate validity"},4232:{message:"Incorrect certificate validity index"},4233:{message:"Unknown signer key ID"},4234:{message:"Unknown signature algorithm"},4235:{message:"Unknown public key ID"},4236:{message:"Unknown public key usage"},4237:{message:"Incorrect elliptic curve ID"},4238:{message:"Incorrect signature algorithm associated to the public key"},4239:{message:"Unknown target device"},"422d":{message:"Unknown certificate tag"},3301:{message:"Failed to hash data"},"422e":{message:"expected_key_usage doesn't match certificate key usage"},5720:{message:"Failed to verify signature"},4118:{message:"trusted_name buffer is too small to contain the trusted name"},ffff:{message:"Cryptography-related error"}};class e7 extends h0{constructor({message:q,errorCode:J}){super({tag:"ProvidePkiCertificateCommandError",message:q,errorCode:J})}}class qQ{name="loadCertificate";args;triggersDisconnection=!1;constructor(q){this.args=q}getApdu(){let q={cla:176,ins:6,p1:this.args.keyUsage,p2:0};return new H0(q).addBufferToData(this.args.certificate).build()}parseResponse(q){if(l.isSuccessResponse(q))return T({data:void 0});let J=new z0(q).encodeToHexaString(q.statusCode);return v0(J,t7)?T({error:new e7({...t7[J],errorCode:J})}):T({error:G0.handle(q)})}}var JQ={"670a":{message:"No app name provided"},6807:{message:"Unknown application name"}};class ZQ extends h0{constructor({message:q,errorCode:J}){super({tag:"OpenAppCommandError",message:q,errorCode:J})}}class t6{name="openApp";args;triggersDisconnection=!0;constructor(q){this.args=q}getApdu(){return new H0({cla:224,ins:216,p1:0,p2:0}).addAsciiStringToData(this.args.appName).build()}parseResponse(q){if(l.isSuccessResponse(q))return T({data:void 0});let J=new z0(q).encodeToHexaString(q.statusCode);return v0(J,JQ)?T({error:new ZQ({...JQ[J],errorCode:J})}):T({error:G0.handle(q)})}}var g0=((q)=>(q.LOCKED="LOCKED",q.BUSY="BUSY",q.CONNECTED="CONNECTED",q.NOT_CONNECTED="NOT CONNECTED",q))(g0||{});var d1=((q)=>(q.NotStarted="not-started",q.Pending="pending",q.Stopped="stopped",q.Completed="completed",q.Error="error",q))(d1||{});var k=((q)=>(q.None="none",q.UnlockDevice="unlock-device",q.AllowSecureConnection="allow-secure-connection",q.ConfirmOpenApp="confirm-open-app",q.SignTransaction="sign-transaction",q.SignTypedData="sign-typed-data",q.AllowListApps="allow-list-apps",q.VerifyAddress="verify-address",q.SignPersonalMessage="sign-personal-message",q.SignDelegationAuthorization="sign-delegation-authorization",q.Web3ChecksOptIn="web3-checks-opt-in",q.VerifySafeAddress="verify-safe-address",q.RegisterWallet="register-wallet",q.ConfirmLoadImage="confirm-load-image",q.ConfirmCommitImage="confirm-commit-image",q.ConfirmRemoveImage="confirm-remove-image",q.GrantConsent="grant-consent",q.AllowInstallFirmware="allow-install-firmware",q))(k||{});var Z0={of(q){return L0(q)},empty(){return p},zero(){return p},fromNullable(q){return q==null?p:L0(q)},fromFalsy(q){return q?L0(q):p},fromPredicate(q,J){switch(arguments.length){case 1:return(Z)=>Z0.fromPredicate(q,Z);default:return q(J)?L0(J):p}},mapMaybe(q,J){switch(arguments.length){case 1:return(Z)=>Z0.mapMaybe(q,Z);default:return Z0.catMaybes(J.map(q))}},catMaybes(q){let J=[];for(let Z of q)if(Z.isJust())J.push(Z.extract());return J},encase(q){try{return L0(q())}catch{return p}},isMaybe(q){return q instanceof e6||q instanceof q8},sequence(q){let J=[];for(let Z of q)if(Z.isJust())J.push(Z.extract());else return p;return L0(J)},"fantasy-land/of"(q){return this.of(q)},"fantasy-land/empty"(){return this.empty()},"fantasy-land/zero"(){return this.zero()}};class e6{constructor(q){this.__value=q,this["fantasy-land/equals"]=this.equals,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/alt"]=this.alt,this["fantasy-land/chain"]=this.chain,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend,this["fantasy-land/filter"]=this.filter}isJust(){return!0}isNothing(){return!1}inspect(){return`Just(${this.__value})`}toString(){return this.inspect()}toJSON(){let q=this.__value;return q instanceof Date?q.toJSON():q}equals(q){return this.extract()===q.extract()}map(q){return L0(q(this.__value))}ap(q){return q.isJust()?this.map(q.extract()):p}alt(q){return this}altLazy(q){return this}chain(q){return q(this.__value)}chainNullable(q){return Z0.fromNullable(q(this.__value))}join(){return this.__value}reduce(q,J){return q(J,this.__value)}extend(q){return L0(q(this))}unsafeCoerce(){return this.__value}caseOf(q){return"_"in q?q._():q.Just(this.__value)}orDefault(q){return this.__value}orDefaultLazy(q){return this.__value}toList(){return[this.__value]}mapOrDefault(q,J){return q(this.__value)}extract(){return this.__value}extractNullable(){return this.__value}toEither(q){return L(this.__value)}ifJust(q){return q(this.__value),this}ifNothing(q){return this}filter(q){return q(this.__value)?L0(this.__value):p}}e6.prototype.constructor=Z0;class q8{constructor(){this["fantasy-land/equals"]=this.equals,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/alt"]=this.alt,this["fantasy-land/chain"]=this.chain,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend,this["fantasy-land/filter"]=this.filter}isJust(){return!1}isNothing(){return!0}inspect(){return"Nothing"}toString(){return this.inspect()}toJSON(){return this.__value}equals(q){return this.extract()===q.extract()}map(q){return p}ap(q){return p}alt(q){return q}altLazy(q){return q()}chain(q){return p}chainNullable(q){return p}join(){return p}reduce(q,J){return J}extend(q){return p}unsafeCoerce(){throw Error("Maybe#unsafeCoerce was ran on a Nothing")}caseOf(q){return"_"in q?q._():q.Nothing()}orDefault(q){return q}orDefaultLazy(q){return q()}toList(){return[]}mapOrDefault(q,J){return J}extract(){return}extractNullable(){return null}toEither(q){return j(q)}ifJust(q){return this}ifNothing(q){return q(),this}filter(q){return p}}q8.prototype.constructor=Z0;var L0=(q)=>new e6(q),p=new q8;var A0={of(q){return L(q)},lefts(q){let J=[];for(let Z of q)if(Z.isLeft())J.push(Z.extract());return J},rights(q){let J=[];for(let Z of q)if(Z.isRight())J.push(Z.extract());return J},encase(q){try{return L(q())}catch(J){return j(J)}},sequence(q){let J=[];for(let Z of q){if(Z.isLeft())return Z;J.push(Z.extract())}return L(J)},isEither(q){return q instanceof Z8||q instanceof J8},"fantasy-land/of"(q){return A0.of(q)}};class J8{constructor(q){this.__value=q,this._="R",this["fantasy-land/bimap"]=this.bimap,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/equals"]=this.equals,this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend}isLeft(){return!1}isRight(){return!0}toJSON(){return this.__value}inspect(){return`Right(${this.__value})`}toString(){return this.inspect()}bimap(q,J){return L(J(this.__value))}map(q){return L(q(this.__value))}mapLeft(q){return this}ap(q){return q.isRight()?this.map(q.extract()):q}equals(q){return q.isRight()?this.__value===q.extract():!1}chain(q){return q(this.__value)}chainLeft(q){return this}join(){return this.__value}alt(q){return this}altLazy(q){return this}reduce(q,J){return q(J,this.__value)}extend(q){return L(q(this))}unsafeCoerce(){return this.__value}caseOf(q){return"_"in q?q._():q.Right(this.__value)}leftOrDefault(q){return q}orDefault(q){return this.__value}orDefaultLazy(q){return this.__value}leftOrDefaultLazy(q){return q()}ifLeft(q){return this}ifRight(q){return q(this.__value),this}toMaybe(){return L0(this.__value)}leftToMaybe(){return p}extract(){return this.__value}swap(){return j(this.__value)}}J8.prototype.constructor=A0;class Z8{constructor(q){this.__value=q,this._="L",this["fantasy-land/bimap"]=this.bimap,this["fantasy-land/map"]=this.map,this["fantasy-land/ap"]=this.ap,this["fantasy-land/equals"]=this.equals,this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this["fantasy-land/reduce"]=this.reduce,this["fantasy-land/extend"]=this.extend}isLeft(){return!0}isRight(){return!1}toJSON(){return this.__value}inspect(){return`Left(${JSON.stringify(this.__value)})`}toString(){return this.inspect()}bimap(q,J){return j(q(this.__value))}map(q){return this}mapLeft(q){return j(q(this.__value))}ap(q){return q.isLeft()?q:this}equals(q){return q.isLeft()?q.extract()===this.__value:!1}chain(q){return this}chainLeft(q){return q(this.__value)}join(){return this}alt(q){return q}altLazy(q){return q()}reduce(q,J){return J}extend(q){return this}unsafeCoerce(){if(this.__value instanceof Error)throw this.__value;throw Error("Either#unsafeCoerce was ran on a Left")}caseOf(q){return"_"in q?q._():q.Left(this.__value)}leftOrDefault(q){return this.__value}orDefault(q){return q}orDefaultLazy(q){return q()}leftOrDefaultLazy(q){return this.__value}ifLeft(q){return q(this.__value),this}ifRight(q){return this}toMaybe(){return p}leftToMaybe(){return L0(this.__value)}extract(){return this.__value}swap(){return L(this.__value)}}Z8.prototype.constructor=A0;var j=(q)=>new Z8(q),L=(q)=>new J8(q);var G1=(q)=>q;var Q8=(q,J)=>{return typeof J==="bigint"?J.toString():J};var QQ=(q)=>typeof q==="object"&&q!==null&&!Array.isArray(q),z1=(q,J)=>{let Z="";switch(typeof J){case"undefined":Z="undefined";break;case"object":Z=J===null?"null":Array.isArray(J)?"an array with value "+JSON.stringify(J,Q8):"an object with value "+JSON.stringify(J,Q8);break;case"boolean":Z="a boolean";break;case"symbol":Z="a symbol";break;case"function":Z="a function";break;case"bigint":Z=`a bigint with value ${J.toString()}`}return Z=Z||`a ${typeof J} with value ${JSON.stringify(J,Q8)}`,`Expected ${q}, but received ${Z}`},T3=(q)=>{if(Object.keys(q).length===1&&q.oneOf?.length===1&&typeof q.oneOf[0]==="object")Object.assign(q,q.oneOf[0]),delete q.oneOf;return q},M3=(q)=>{if(Array.isArray(q.oneOf))for(let J=0;J<q.oneOf.length;J++){let Z=q.oneOf[J];if(typeof Z==="object"&&Z.oneOf)return q.oneOf.splice(J,1),q.oneOf.push(...Z.oneOf),$Q(q)}return q},$Q=(q)=>{return M3(q),T3(q),q},t0={interface(q){let J=Object.keys(q),Z=($)=>{if(!QQ($))return j(z1("an object",$));let W={};for(let Y of J){if(!$.hasOwnProperty(Y)&&!q[Y]._isOptional)return j(`Problem with property "${Y}": it does not exist in received object ${JSON.stringify($,Q8)}`);let z=q[Y].decode($[Y]);if(z.isLeft())return j(`Problem with the value of property "${Y}": ${z.extract()}`);let X=z.extract();if(X!==void 0)W[Y]=X}return L(W)};return{decode:Z,encode:($)=>{let W={};for(let Y of J)W[Y]=q[Y].encode($[Y]);return W},unsafeDecode:($)=>Z($).mapLeft(Error).unsafeCoerce(),schema:()=>J.reduce(($,W)=>{if(!q[W]._isOptional)$.required.push(W);return $.properties[W]=$Q(q[W].schema()),$},{type:"object",properties:{},required:[]})}},custom({decode:q,encode:J,schema:Z}){return{decode:q,encode:J,unsafeDecode:(Q)=>q(Q).mapLeft(Error).unsafeCoerce(),schema:Z??(()=>({}))}}},WQ=t0.custom({decode:(q)=>typeof q==="string"?L(q):j(z1("a string",q)),encode:G1,schema:()=>({type:"string"})}),YQ=t0.custom({decode:(q)=>typeof q==="number"?L(q):j(z1("a number",q)),encode:G1,schema:()=>({type:"number"})}),iN=t0.custom({decode:(q)=>q===null?L(q):j(z1("a null",q)),encode:G1,schema:()=>({type:"null"})}),f3=t0.custom({decode:(q)=>q===void 0?L(q):j(z1("an undefined",q)),encode:G1}),aN=(q)=>({...S3([q,f3]),schema:q.schema,_isOptional:!0});var oN=t0.custom({decode:(q)=>typeof q==="boolean"?L(q):j(z1("a boolean",q)),encode:G1,schema:()=>({type:"boolean"})}),rN=t0.custom({decode:L,encode:G1,schema:()=>({})});var S3=(q)=>t0.custom({decode:(J)=>{let Z=[];for(let Q of q){let $=Q.decode(J);if($.isRight())return $;else Z.push($.extract())}return j(`One of the following problems occured: ${Z.map((Q,$)=>`(${$}) ${Q}`).join(", ")}`)},encode:(J)=>{for(let Z of q)if(A0.encase(()=>Z.encode(J)).mapLeft(($)=>"").chain(Z.decode).isRight())return Z.encode(J);return J},schema:()=>({oneOf:q.map((J)=>J.schema())})}),tN=(q)=>t0.custom({decode:(J)=>{if(!Array.isArray(J))return j(z1("an array",J));else{let Z=[];for(let Q=0;Q<J.length;Q++){let $=q.decode(J[Q]);if($.isRight())Z.push($.extract());else return j(`Problem with the value at index ${Q}: ${$.extract()}`)}return L(Z)}},encode:(J)=>J.map(q.encode),schema:()=>({type:"array",items:q.schema()})}),h3=t0.custom({decode:(q)=>WQ.decode(q).chain((J)=>isFinite(+J)?L(J):j(z1("a number",q))),encode:G1,schema:YQ.schema}),eN=(q,J)=>t0.custom({decode:(Z)=>{let Q={},$=q===YQ?h3:q;if(!QQ(Z))return j(z1("an object",Z));for(let W of Object.keys(Z))if(Z.hasOwnProperty(W)){let Y=$.decode(W),z=J.decode(Z[W]);if(Y.isRight()&&z.isRight())Q[Y.extract()]=z.extract();else if(Y.isLeft())return j(`Problem with key type of property "${W}": ${Y.extract()}`);else if(z.isLeft())return j(`Problem with the value of property "${W}": ${z.extract()}`)}return L(Q)},encode:(Z)=>{let Q={};for(let $ in Z)if(Z.hasOwnProperty($))Q[q.encode($)]=J.encode(Z[$]);return Q},schema:()=>({type:"object",additionalProperties:J.schema()})}),qV=(...q)=>t0.custom({decode:(J)=>q.includes(J)?L(J):j(z1(q.map((Z)=>JSON.stringify(Z)).join(", "),J)),encode:G1,schema:()=>({oneOf:q.map((J)=>({type:typeof J,enum:[J]}))})});var JV=t0.custom({decode:(q)=>WQ.decode(q).mapLeft((J)=>`Problem with date string: ${J}`).chain((J)=>Number.isNaN(Date.parse(J))?j("Expected a valid date string, but received a string that cannot be parsed"):L(new Date(J))),encode:(q)=>q.toISOString(),schema:()=>({type:"string",format:"date-time"})});var zQ,wQ={liftEither(q){if(q.isRight())return Promise.resolve(q.extract());throw q.extract()},fromPromise(q){return q.then(wQ.liftEither)},throwE(q){throw q}};class QJ{constructor(q){this.runPromise=q,this[zQ]="EitherAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/alt"]=this.alt,this.then=(J,Z)=>{return this.run().then(J,Z)}}leftOrDefault(q){return this.run().then((J)=>J.leftOrDefault(q))}orDefault(q){return this.run().then((J)=>J.orDefault(q))}join(){return h(async(q)=>{let J=await this;if(J.isRight()){let Z=await J.extract();return q.liftEither(Z)}return q.liftEither(J)})}ap(q){return h(async(J)=>{let Z=await q;if(Z.isRight()){let Q=await this.run();if(Q.isRight())return Z.extract()(Q.extract());else return J.liftEither(Q)}return J.liftEither(Z)})}alt(q){return h(async(J)=>{let Z=await this.run();if(Z.isRight())return Z.extract();else{let Q=await q;return J.liftEither(Q)}})}extend(q){return h(async(J)=>{let Z=await this.run();if(Z.isRight()){let Q=h.liftEither(Z);return J.liftEither(L(q(Q)))}return J.liftEither(Z)})}async run(){try{return L(await this.runPromise(wQ))}catch(q){return j(q)}}bimap(q,J){return h(async(Z)=>{let Q=await this.run();try{return await Z.liftEither(Q.bimap(q,J))}catch($){throw await $}})}map(q){return h((J)=>this.runPromise(J).then(q))}mapLeft(q){return h(async(J)=>{try{return await this.runPromise(J)}catch(Z){throw await q(Z)}})}chain(q){return h(async(J)=>{let Z=await this.runPromise(J);return J.fromPromise(q(Z))})}chainLeft(q){return h(async(J)=>{try{return await this.runPromise(J)}catch(Z){return J.fromPromise(q(Z))}})}toMaybeAsync(){return k0(async({liftMaybe:q})=>{let J=await this.run();return q(J.toMaybe())})}swap(){return h(async(q)=>{let J=await this.run();if(J.isRight())q.throwE(J.extract());return q.liftEither(L(J.extract()))})}ifLeft(q){return h(async(J)=>{let Z=await this.run();return Z.ifLeft(q),J.liftEither(Z)})}ifRight(q){return h(async(J)=>{let Z=await this.run();return Z.ifRight(q),J.liftEither(Z)})}void(){return this.map((q)=>{})}caseOf(q){return this.run().then((J)=>J.caseOf(q))}finally(q){return h(({fromPromise:J})=>J(this.run().finally(q)))}}zQ=Symbol.toStringTag;var h=Object.assign((q)=>new QJ(q),{fromPromise:(q)=>h(({fromPromise:J})=>J(q())),liftEither:(q)=>h(({liftEither:J})=>J(q)),lefts:(q)=>Promise.all(q.map((J)=>J.run())).then(A0.lefts),rights:(q)=>Promise.all(q.map((J)=>J.run())).then(A0.rights),sequence:(q)=>h(async(J)=>{let Z=[];for await(let Q of q){if(Q.isLeft())return J.liftEither(Q);Z.push(Q.extract())}return J.liftEither(L(Z))}),all:(q)=>h.fromPromise(async()=>Promise.all(q).then(A0.sequence))});QJ.prototype.constructor=h;var XQ,FQ={liftMaybe(q){if(q.isJust())return Promise.resolve(q.extract());throw p},fromPromise(q){return q.then(FQ.liftMaybe)}};class $J{constructor(q){this.runPromise=q,this[XQ]="MaybeAsync",this["fantasy-land/chain"]=this.chain,this["fantasy-land/filter"]=this.filter,this["fantasy-land/alt"]=this.alt}orDefault(q){return this.run().then((J)=>J.orDefault(q))}join(){return k0(async(q)=>{let J=await this.run();if(J.isJust()){let Z=await J.extract();return q.liftMaybe(Z)}return q.liftMaybe(p)})}ap(q){return k0(async(J)=>{let Z=await q;if(Z.isJust()){let Q=await this.run();if(Q.isJust())return Z.extract()(Q.extract());else return J.liftMaybe(p)}return J.liftMaybe(p)})}alt(q){return k0(async(J)=>{let Z=await this.run();if(Z.isJust())return Z.extract();else{let Q=await q;return J.liftMaybe(Q)}})}extend(q){return k0(async(J)=>{let Z=await this.run();if(Z.isJust()){let Q=k0.liftMaybe(Z);return J.liftMaybe(L0(q(Q)))}return J.liftMaybe(p)})}filter(q){return k0(async(J)=>{let Z=await this.run();return J.liftMaybe(Z.filter(q))})}async run(){try{return L0(await this.runPromise(FQ))}catch{return p}}map(q){return k0((J)=>this.runPromise(J).then(q))}chain(q){return k0(async(J)=>{let Z=await this.runPromise(J);return J.fromPromise(q(Z))})}toEitherAsync(q){return h(async({liftEither:J})=>{let Z=await this.run();return J(Z.toEither(q))})}ifJust(q){return k0(async(J)=>{let Z=await this.run();return Z.ifJust(q),J.liftMaybe(Z)})}ifNothing(q){return k0(async(J)=>{let Z=await this.run();return Z.ifNothing(q),J.liftMaybe(Z)})}void(){return this.map((q)=>{})}caseOf(q){return this.run().then((J)=>J.caseOf(q))}finally(q){return k0(({fromPromise:J})=>J(this.run().finally(q)))}then(q,J){return this.run().then(q,J)}}XQ=Symbol.toStringTag;var k0=Object.assign((q)=>new $J(q),{catMaybes:(q)=>Promise.all(q).then(Z0.catMaybes),fromPromise:(q)=>k0(({fromPromise:J})=>J(q())),liftMaybe:(q)=>k0(({liftMaybe:J})=>J(q))});$J.prototype.constructor=k0;function v3(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function y3(){let q=v3();if(q.__xstate__)return q.__xstate__;return}var _Q=(q)=>{if(typeof window>"u")return;let J=y3();if(J)J.register(q)};class zJ{constructor(q){this._process=q,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){if(this._current)this._current.next=null,this._last=this._current}enqueue(q){let J={value:q,next:null};if(this._current){this._last.next=J,this._last=J;return}if(this._current=J,this._last=J,this._active)this.flush()}flush(){while(this._current){let q=this._current;this._process(q.value),this._current=q.next}this._last=null}}var _J=".",u3="",HJ="",g3="#",m3="*",DQ="xstate.init";var s1="xstate.stop";function l3(q,J){return{type:`xstate.after.${q}.${J}`}}function wJ(q,J){return{type:`xstate.done.state.${q}`,output:J}}function d3(q,J){return{type:`xstate.done.actor.${q}`,output:J,actorId:q}}function UQ(q,J){return{type:`xstate.error.actor.${q}`,error:J,actorId:q}}function GJ(q){return{type:DQ,input:q}}function N1(q){setTimeout(()=>{throw q})}var c3=(()=>typeof Symbol==="function"&&Symbol.observable||"@@observable")();function NJ(q,J){let Z=HQ(q),Q=HQ(J);if(typeof Q==="string"){if(typeof Z==="string")return Q===Z;return!1}if(typeof Z==="string")return Z in Q;return Object.keys(Z).every(($)=>{if(!($ in Q))return!1;return NJ(Z[$],Q[$])})}function Y8(q){if(IQ(q))return q;let J=[],Z="";for(let Q=0;Q<q.length;Q++){switch(q.charCodeAt(Q)){case 92:Z+=q[Q+1],Q++;continue;case 46:J.push(Z),Z="";continue}Z+=q[Q]}return J.push(Z),J}function HQ(q){if(hQ(q))return q.value;if(typeof q!=="string")return q;let J=Y8(q);return KQ(J)}function KQ(q){if(q.length===1)return q[0];let J={},Z=J;for(let Q=0;Q<q.length-1;Q++)if(Q===q.length-2)Z[q[Q]]=q[Q+1];else{let $=Z;Z={},$[q[Q]]=Z}return J}function VJ(q,J){let Z={},Q=Object.keys(q);for(let $=0;$<Q.length;$++){let W=Q[$];Z[W]=J(q[W],W,q,$)}return Z}function jQ(q){if(IQ(q))return q;return[q]}function V1(q){if(q===void 0)return[];return jQ(q)}function XJ(q,J,Z,Q){if(typeof q==="function")return q({context:J,event:Z,self:Q});return q}function IQ(q){return Array.isArray(q)}function p3(q){return q.type.startsWith("xstate.error.actor")}function c1(q){return jQ(q).map((J)=>{if(typeof J>"u"||typeof J==="string")return{target:J};return J})}function LQ(q){if(q===void 0||q===u3)return;return V1(q)}function $8(q,J,Z){let Q=typeof q==="object",$=Q?q:void 0;return{next:(Q?q.next:q)?.bind($),error:(Q?q.error:J)?.bind($),complete:(Q?q.complete:Z)?.bind($)}}function BJ(q,J){return`${J}.${q}`}function eq(q,J){let Z=J.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!Z)return q.implementations.actors[J];let[,Q,$]=Z,Y=q.getStateNodeById($).config.invoke;return(Array.isArray(Y)?Y[Q]:Y).src}function GQ(q,J){return`${q.sessionId}.${J}`}var s3=0;function n3(q,J){let Z=new Map,Q=new Map,$=new WeakMap,W=new Set,Y={},{clock:z,logger:X}=J,w={schedule:(G,B,R,S,e=Math.random().toString(36).slice(2))=>{let s0={source:G,target:B,event:R,delay:S,id:e,startedAt:Date.now()},P0=GQ(G,e);_._snapshot._scheduledEvents[P0]=s0;let T9=z.setTimeout(()=>{delete Y[P0],delete _._snapshot._scheduledEvents[P0],_._relay(G,B,R)},S);Y[P0]=T9},cancel:(G,B)=>{let R=GQ(G,B),S=Y[R];if(delete Y[R],delete _._snapshot._scheduledEvents[R],S!==void 0)z.clearTimeout(S)},cancelAll:(G)=>{for(let B in _._snapshot._scheduledEvents){let R=_._snapshot._scheduledEvents[B];if(R.source===G)w.cancel(G,R.id)}}},F=(G)=>{if(!W.size)return;let B={...G,rootId:q.sessionId};W.forEach((R)=>R.next?.(B))},_={_snapshot:{_scheduledEvents:(J?.snapshot&&J.snapshot.scheduler)??{}},_bookId:()=>`x:${s3++}`,_register:(G,B)=>{return Z.set(G,B),G},_unregister:(G)=>{Z.delete(G.sessionId);let B=$.get(G);if(B!==void 0)Q.delete(B),$.delete(G)},get:(G)=>{return Q.get(G)},_set:(G,B)=>{let R=Q.get(G);if(R&&R!==B)throw Error(`Actor with system ID '${G}' already exists.`);Q.set(G,B),$.set(B,G)},inspect:(G)=>{let B=$8(G);return W.add(B),{unsubscribe(){W.delete(B)}}},_sendInspectionEvent:F,_relay:(G,B,R)=>{_._sendInspectionEvent({type:"@xstate.event",sourceRef:G,actorRef:B,event:R}),B._send(R)},scheduler:w,getSnapshot:()=>{return{_scheduledEvents:{..._._snapshot._scheduledEvents}}},start:()=>{let G=_._snapshot._scheduledEvents;_._snapshot._scheduledEvents={};for(let B in G){let{source:R,target:S,event:e,delay:s0,id:P0}=G[B];w.schedule(R,S,e,s0,P0)}},_clock:z,_logger:X};return _}var WJ=!1,z8=1,m0=function(q){return q[q.NotStarted=0]="NotStarted",q[q.Running=1]="Running",q[q.Stopped=2]="Stopped",q}({}),i3={clock:{setTimeout:(q,J)=>{return setTimeout(q,J)},clearTimeout:(q)=>{return clearTimeout(q)}},logger:console.log.bind(console),devTools:!1};class DJ{constructor(q,J){this.logic=q,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new zJ(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=m0.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];let Z={...i3,...J},{clock:Q,logger:$,parent:W,syncSnapshot:Y,id:z,systemId:X,inspect:w}=Z;if(this.system=W?W.system:n3(this,{clock:Q,logger:$}),w&&!W)this.system.inspect($8(w));if(this.sessionId=this.system._bookId(),this.id=z??this.sessionId,this.logger=J?.logger??this.system._logger,this.clock=J?.clock??this.system._clock,this._parent=W,this._syncSnapshot=Y,this.options=Z,this.src=Z.src??q,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:(F)=>{this._deferred.push(F)},system:this.system,stopChild:(F)=>{if(F._parent!==this)throw Error(`Cannot stop child actor ${F.id} of ${this.id} because it is not a child`);F._stop()},emit:(F)=>{let _=this.eventListeners.get(F.type),G=this.eventListeners.get("*");if(!_&&!G)return;let B=[..._?_.values():[],...G?G.values():[]];for(let R of B)R(F)},actionExecutor:(F)=>{let _=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:F.type,params:F.params}}),!F.exec)return;let G=WJ;try{WJ=!0,F.exec(F.info,F.params)}finally{WJ=G}};if(this._processingStatus===m0.Running)_();else this._deferred.push(_)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),X)this._systemId=X,this.system._set(X,this);if(this._initState(J?.snapshot??J?.state),X&&this._snapshot.status!=="active")this.system._unregister(this)}_initState(q){try{this._snapshot=q?this.logic.restoreSnapshot?this.logic.restoreSnapshot(q,this._actorScope):q:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(J){this._snapshot={status:"error",output:void 0,error:J}}}update(q,J){this._snapshot=q;let Z;while(Z=this._deferred.shift())try{Z()}catch(Q){this._deferred.length=0,this._snapshot={...q,status:"error",error:Q}}switch(this._snapshot.status){case"active":for(let Q of this.observers)try{Q.next?.(q)}catch($){N1($)}break;case"done":for(let Q of this.observers)try{Q.next?.(q)}catch($){N1($)}if(this._stopProcedure(),this._complete(),this._doneEvent=d3(this.id,this._snapshot.output),this._parent)this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:J,snapshot:q})}subscribe(q,J,Z){let Q=$8(q,J,Z);if(this._processingStatus!==m0.Stopped)this.observers.add(Q);else switch(this._snapshot.status){case"done":try{Q.complete?.()}catch($){N1($)}break;case"error":{let $=this._snapshot.error;if(!Q.error)N1($);else try{Q.error($)}catch(W){N1(W)}break}}return{unsubscribe:()=>{this.observers.delete(Q)}}}on(q,J){let Z=this.eventListeners.get(q);if(!Z)Z=new Set,this.eventListeners.set(q,Z);let Q=J.bind(void 0);return Z.add(Q),{unsubscribe:()=>{Z.delete(Q)}}}start(){if(this._processingStatus===m0.Running)return this;if(this._syncSnapshot)this.subscribe({next:(Z)=>{if(Z.status==="active")this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:Z})},error:()=>{}});if(this.system._register(this.sessionId,this),this._systemId)this.system._set(this._systemId,this);this._processingStatus=m0.Running;let q=GJ(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:q}),this._snapshot.status){case"done":return this.update(this._snapshot,q),this;case"error":return this._error(this._snapshot.error),this}if(!this._parent)this.system.start();if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(Z){return this._snapshot={...this._snapshot,status:"error",error:Z},this._error(Z),this}if(this.update(this._snapshot,q),this.options.devTools)this.attachDevTools();return this.mailbox.start(),this}_process(q){let J,Z;try{J=this.logic.transition(this._snapshot,q,this._actorScope)}catch(Q){Z={err:Q}}if(Z){let{err:Q}=Z;this._snapshot={...this._snapshot,status:"error",error:Q},this._error(Q);return}if(this.update(J,q),q.type===s1)this._stopProcedure(),this._complete()}_stop(){if(this._processingStatus===m0.Stopped)return this;if(this.mailbox.clear(),this._processingStatus===m0.NotStarted)return this._processingStatus=m0.Stopped,this;return this.mailbox.enqueue({type:s1}),this}stop(){if(this._parent)throw Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(let q of this.observers)try{q.complete?.()}catch(J){N1(J)}this.observers.clear()}_reportError(q){if(!this.observers.size){if(!this._parent)N1(q);return}let J=!1;for(let Z of this.observers){let Q=Z.error;J||=!Q;try{Q?.(q)}catch($){N1($)}}if(this.observers.clear(),J)N1(q)}_error(q){if(this._stopProcedure(),this._reportError(q),this._parent)this.system._relay(this,this._parent,UQ(this.id,q))}_stopProcedure(){if(this._processingStatus!==m0.Running)return this;return this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new zJ(this._process.bind(this)),this._processingStatus=m0.Stopped,this.system._unregister(this),this}_send(q){if(this._processingStatus===m0.Stopped)return;this.mailbox.enqueue(q)}send(q){this.system._relay(void 0,this,q)}attachDevTools(){let{devTools:q}=this.options;if(q)(typeof q==="function"?q:_Q)(this)}toJSON(){return{xstate$$type:z8,id:this.id}}getPersistedSnapshot(q){return this.logic.getPersistedSnapshot(this._snapshot,q)}[c3](){return this}getSnapshot(){return this._snapshot}}function e0(q,...[J]){return new DJ(q,J)}function a3(q,J,Z,Q,{sendId:$}){let W=typeof $==="function"?$(Z,Q):$;return[J,{sendId:W},void 0]}function o3(q,J){q.defer(()=>{q.system.scheduler.cancel(q.self,J.sendId)})}function UJ(q){function J(Z,Q){}return J.type="xstate.cancel",J.sendId=q,J.resolve=a3,J.execute=o3,J}function r3(q,J,Z,Q,{id:$,systemId:W,src:Y,input:z,syncSnapshot:X}){let w=typeof Y==="string"?eq(J.machine,Y):Y,F=typeof $==="function"?$(Z):$,_,G=void 0;if(w)G=typeof z==="function"?z({context:J.context,event:Z.event,self:q.self}):z,_=e0(w,{id:F,src:Y,parent:q.self,syncSnapshot:X,systemId:W,input:G});return[b1(J,{children:{...J.children,[F]:_}}),{id:$,systemId:W,actorRef:_,src:Y,input:G},void 0]}function t3(q,{actorRef:J}){if(!J)return;q.defer(()=>{if(J._processingStatus===m0.Stopped)return;J.start()})}function KJ(...[q,{id:J,systemId:Z,input:Q,syncSnapshot:$=!1}={}]){function W(Y,z){}return W.type="xstate.spawnChild",W.id=J,W.systemId=Z,W.src=q,W.input=Q,W.syncSnapshot=$,W.resolve=r3,W.execute=t3,W}function e3(q,J,Z,Q,{actorRef:$}){let W=typeof $==="function"?$(Z,Q):$,Y=typeof W==="string"?J.children[W]:W,z=J.children;if(Y)z={...z},delete z[Y.id];return[b1(J,{children:z}),Y,void 0]}function q2(q,J){if(!J)return;if(q.system._unregister(J),J._processingStatus!==m0.Running){q.stopChild(J);return}q.defer(()=>{q.stopChild(J)})}function w8(q){function J(Z,Q){}return J.type="xstate.stopChild",J.actorRef=q,J.resolve=e3,J.execute=q2,J}function J2(q,{context:J,event:Z},{guards:Q}){return Q.every(($)=>Bq($,J,Z,q))}function Z2(q){function J(Z,Q){return!1}return J.check=J2,J.guards=q,J}function Bq(q,J,Z,Q){let{machine:$}=Q,W=typeof q==="function",Y=W?q:$.implementations.guards[typeof q==="string"?q:q.type];if(!W&&!Y)throw Error(`Guard '${typeof q==="string"?q:q.type}' is not implemented.'.`);if(typeof Y!=="function")return Bq(Y,J,Z,Q);let z={context:J,event:Z},X=W||typeof q==="string"?void 0:("params"in q)?typeof q.params==="function"?q.params({context:J,event:Z}):q.params:void 0;if(!("check"in Y))return Y(z,X);return Y.check(Q,z,Y)}var jJ=(q)=>q.type==="atomic"||q.type==="final";function Nq(q){return Object.values(q.states).filter((J)=>J.type!=="history")}function q6(q,J){let Z=[];if(J===q)return Z;let Q=q.parent;while(Q&&Q!==J)Z.push(Q),Q=Q.parent;return Z}function J6(q){let J=new Set(q),Z=RQ(J);for(let Q of J)if(Q.type==="compound"&&(!Z.get(Q)||!Z.get(Q).length))NQ(Q).forEach(($)=>J.add($));else if(Q.type==="parallel")for(let $ of Nq(Q)){if($.type==="history")continue;if(!J.has($)){let W=NQ($);for(let Y of W)J.add(Y)}}for(let Q of J){let $=Q.parent;while($)J.add($),$=$.parent}return J}function AQ(q,J){let Z=J.get(q);if(!Z)return{};if(q.type==="compound"){let $=Z[0];if($){if(jJ($))return $.key}else return{}}let Q={};for(let $ of Z)Q[$.key]=AQ($,J);return Q}function RQ(q){let J=new Map;for(let Z of q){if(!J.has(Z))J.set(Z,[]);if(Z.parent){if(!J.has(Z.parent))J.set(Z.parent,[]);J.get(Z.parent).push(Z)}}return J}function PQ(q,J){let Z=J6(J);return AQ(q,RQ(Z))}function X8(q,J){if(J.type==="compound")return Nq(J).some((Z)=>Z.type==="final"&&q.has(Z));if(J.type==="parallel")return Nq(J).every((Z)=>X8(q,Z));return J.type==="final"}var Z6=(q)=>q[0]===g3;function EQ(q,J){return q.transitions.get(J)||[...q.transitions.keys()].filter((Q)=>{if(Q===m3)return!0;if(!Q.endsWith(".*"))return!1;let $=Q.split("."),W=J.split(".");for(let Y=0;Y<$.length;Y++){let z=$[Y],X=W[Y];if(z==="*")return Y===$.length-1;if(z!==X)return!1}return!0}).sort((Q,$)=>$.length-Q.length).flatMap((Q)=>q.transitions.get(Q))}function xQ(q){let J=q.config.after;if(!J)return[];let Z=($)=>{let W=l3($,q.id),Y=W.type;return q.entry.push(AJ(W,{id:Y,delay:$})),q.exit.push(UJ(Y)),Y};return Object.keys(J).flatMap(($)=>{let W=J[$],Y=typeof W==="string"?{target:W}:W,z=Number.isNaN(+$)?$:+$,X=Z(z);return V1(Y).map((w)=>({...w,event:X,delay:z}))}).map(($)=>{let{delay:W}=$;return{...O1(q,$.event,$),delay:W}})}function O1(q,J,Z){let Q=LQ(Z.target),$=Z.reenter??!1,W=Q2(q,Q),Y={...Z,actions:V1(Z.actions),guard:Z.guard,target:W,source:q,reenter:$,eventType:J,toJSON:()=>({...Y,source:`#${q.id}`,target:W?W.map((z)=>`#${z.id}`):void 0})};return Y}function kQ(q){let J=new Map;if(q.config.on)for(let Z of Object.keys(q.config.on)){if(Z===HJ)throw Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');let Q=q.config.on[Z];J.set(Z,c1(Q).map(($)=>O1(q,Z,$)))}if(q.config.onDone){let Z=`xstate.done.state.${q.id}`;J.set(Z,c1(q.config.onDone).map((Q)=>O1(q,Z,Q)))}for(let Z of q.invoke){if(Z.onDone){let Q=`xstate.done.actor.${Z.id}`;J.set(Q,c1(Z.onDone).map(($)=>O1(q,Q,$)))}if(Z.onError){let Q=`xstate.error.actor.${Z.id}`;J.set(Q,c1(Z.onError).map(($)=>O1(q,Q,$)))}if(Z.onSnapshot){let Q=`xstate.snapshot.${Z.id}`;J.set(Q,c1(Z.onSnapshot).map(($)=>O1(q,Q,$)))}}for(let Z of q.after){let Q=J.get(Z.eventType);if(!Q)Q=[],J.set(Z.eventType,Q);Q.push(Z)}return J}function OQ(q,J){let Z=typeof J==="string"?q.states[J]:J?q.states[J.target]:void 0;if(!Z&&J)throw Error(`Initial state node "${J}" not found on parent state node #${q.id}`);let Q={source:q,actions:!J||typeof J==="string"?[]:V1(J.actions),eventType:null,reenter:!1,target:Z?[Z]:[],toJSON:()=>({...Q,source:`#${q.id}`,target:Z?[`#${Z.id}`]:[]})};return Q}function Q2(q,J){if(J===void 0)return;return J.map((Z)=>{if(typeof Z!=="string")return Z;if(Z6(Z))return q.machine.getStateNodeById(Z);let Q=Z[0]===_J;if(Q&&!q.parent)return tq(q,Z.slice(1));let $=Q?q.key+Z:Z;if(q.parent)try{return tq(q.parent,$)}catch(W){throw Error(`Invalid transition definition for state node '${q.id}':
15
+ ${W.message}`)}else throw Error(`Invalid target: "${Z}" is not a valid target from the root node. Did you mean ".${Z}"?`)})}function CQ(q){let J=LQ(q.config.target);if(!J)return q.parent.initial;return{target:J.map((Z)=>typeof Z==="string"?tq(q.parent,Z):Z)}}function p1(q){return q.type==="history"}function NQ(q){let J=IJ(q);for(let Z of J)for(let Q of q6(Z,q))J.add(Q);return J}function IJ(q){let J=new Set;function Z(Q){if(J.has(Q))return;if(J.add(Q),Q.type==="compound")Z(Q.initial.target[0]);else if(Q.type==="parallel")for(let $ of Nq(Q))Z($)}return Z(q),J}function Vq(q,J){if(Z6(J))return q.machine.getStateNodeById(J);if(!q.states)throw Error(`Unable to retrieve child state '${J}' from '${q.id}'; no child states exist.`);let Z=q.states[J];if(!Z)throw Error(`Child state '${J}' does not exist on '${q.id}'`);return Z}function tq(q,J){if(typeof J==="string"&&Z6(J))try{return q.machine.getStateNodeById(J)}catch{}let Z=Y8(J).slice(),Q=q;while(Z.length){let $=Z.shift();if(!$.length)break;Q=Vq(Q,$)}return Q}function Dq(q,J){if(typeof J==="string"){let $=q.states[J];if(!$)throw Error(`State '${J}' does not exist on '${q.id}'`);return[q,$]}let Z=Object.keys(J),Q=Z.map(($)=>Vq(q,$)).filter(Boolean);return[q.machine.root,q].concat(Q,Z.reduce(($,W)=>{let Y=Vq(q,W);if(!Y)return $;let z=Dq(Y,J[W]);return $.concat(z)},[]))}function $2(q,J,Z,Q){let W=Vq(q,J).next(Z,Q);if(!W||!W.length)return q.next(Z,Q);return W}function W2(q,J,Z,Q){let $=Object.keys(J),W=Vq(q,$[0]),Y=F8(W,J[$[0]],Z,Q);if(!Y||!Y.length)return q.next(Z,Q);return Y}function Y2(q,J,Z,Q){let $=[];for(let W of Object.keys(J)){let Y=J[W];if(!Y)continue;let z=Vq(q,W),X=F8(z,Y,Z,Q);if(X)$.push(...X)}if(!$.length)return q.next(Z,Q);return $}function F8(q,J,Z,Q){if(typeof J==="string")return $2(q,J,Z,Q);if(Object.keys(J).length===1)return W2(q,J,Z,Q);return Y2(q,J,Z,Q)}function z2(q){return Object.keys(q.states).map((J)=>q.states[J]).filter((J)=>J.type==="history")}function C1(q,J){let Z=q;while(Z.parent&&Z.parent!==J)Z=Z.parent;return Z.parent===J}function w2(q,J){let Z=new Set(q),Q=new Set(J);for(let $ of Z)if(Q.has($))return!0;for(let $ of Q)if(Z.has($))return!0;return!1}function bQ(q,J,Z){let Q=new Set;for(let $ of q){let W=!1,Y=new Set;for(let z of Q)if(w2(FJ([$],J,Z),FJ([z],J,Z)))if(C1($.source,z.source))Y.add(z);else{W=!0;break}if(!W){for(let z of Y)Q.delete(z);Q.add($)}}return Array.from(Q)}function X2(q){let[J,...Z]=q;for(let Q of q6(J,void 0))if(Z.every(($)=>C1($,Q)))return Q}function LJ(q,J){if(!q.target)return[];let Z=new Set;for(let Q of q.target)if(p1(Q))if(J[Q.id])for(let $ of J[Q.id])Z.add($);else for(let $ of LJ(CQ(Q),J))Z.add($);else Z.add(Q);return[...Z]}function TQ(q,J){let Z=LJ(q,J);if(!Z)return;if(!q.reenter&&Z.every(($)=>$===q.source||C1($,q.source)))return q.source;let Q=X2(Z.concat(q.source));if(Q)return Q;if(q.reenter)return;return q.source.machine.root}function FJ(q,J,Z){let Q=new Set;for(let $ of q)if($.target?.length){let W=TQ($,Z);if($.reenter&&$.source===W)Q.add(W);for(let Y of J)if(C1(Y,W))Q.add(Y)}return[...Q]}function F2(q,J){if(q.length!==J.size)return!1;for(let Z of q)if(!J.has(Z))return!1;return!0}function W8(q,J,Z,Q,$,W){if(!q.length)return J;let Y=new Set(J._nodes),z=J.historyValue,X=bQ(q,Y,z),w=J;if(!$)[w,z]=N2(w,Q,Z,X,Y,z,W,Z.actionExecutor);w=n1(w,Q,Z,X.flatMap((_)=>_.actions),W,void 0),w=H2(w,Q,Z,X,Y,W,z,$);let F=[...Y];if(w.status==="done")w=n1(w,Q,Z,F.sort((_,G)=>G.order-_.order).flatMap((_)=>_.exit),W,void 0);try{if(z===J.historyValue&&F2(J._nodes,Y))return w;return b1(w,{_nodes:F,historyValue:z})}catch(_){throw _}}function _2(q,J,Z,Q,$){if(Q.output===void 0)return;let W=wJ($.id,$.output!==void 0&&$.parent?XJ($.output,q.context,J,Z.self):void 0);return XJ(Q.output,q.context,W,Z.self)}function H2(q,J,Z,Q,$,W,Y,z){let X=q,w=new Set,F=new Set;if(G2(Q,Y,F,w),z)F.add(q.machine.root);let _=new Set;for(let G of[...w].sort((B,R)=>B.order-R.order)){$.add(G);let B=[];B.push(...G.entry);for(let R of G.invoke)B.push(KJ(R.src,{...R,syncSnapshot:!!R.onSnapshot}));if(F.has(G)){let R=G.initial.actions;B.push(...R)}if(X=n1(X,J,Z,B,W,G.invoke.map((R)=>R.id)),G.type==="final"){let R=G.parent,S=R?.type==="parallel"?R:R?.parent,e=S||G;if(R?.type==="compound")W.push(wJ(R.id,G.output!==void 0?XJ(G.output,X.context,J,Z.self):void 0));while(S?.type==="parallel"&&!_.has(S)&&X8($,S))_.add(S),W.push(wJ(S.id)),e=S,S=S.parent;if(S)continue;X=b1(X,{status:"done",output:_2(X,J,Z,X.machine.root,e)})}}return X}function G2(q,J,Z,Q){for(let $ of q){let W=TQ($,J);for(let z of $.target||[]){if(!p1(z)&&($.source!==z||$.source!==W||$.reenter))Q.add(z),Z.add(z);Gq(z,J,Z,Q)}let Y=LJ($,J);for(let z of Y){let X=q6(z,W);if(W?.type==="parallel")X.push(W);MQ(Q,J,Z,X,!$.source.parent&&$.reenter?void 0:W)}}}function Gq(q,J,Z,Q){if(p1(q))if(J[q.id]){let $=J[q.id];for(let W of $)Q.add(W),Gq(W,J,Z,Q);for(let W of $)YJ(W,q.parent,Q,J,Z)}else{let $=CQ(q);for(let W of $.target){if(Q.add(W),$===q.parent?.initial)Z.add(q.parent);Gq(W,J,Z,Q)}for(let W of $.target)YJ(W,q.parent,Q,J,Z)}else if(q.type==="compound"){let[$]=q.initial.target;if(!p1($))Q.add($),Z.add($);Gq($,J,Z,Q),YJ($,q,Q,J,Z)}else if(q.type==="parallel"){for(let $ of Nq(q).filter((W)=>!p1(W)))if(![...Q].some((W)=>C1(W,$))){if(!p1($))Q.add($),Z.add($);Gq($,J,Z,Q)}}}function MQ(q,J,Z,Q,$){for(let W of Q){if(!$||C1(W,$))q.add(W);if(W.type==="parallel"){for(let Y of Nq(W).filter((z)=>!p1(z)))if(![...q].some((z)=>C1(z,Y)))q.add(Y),Gq(Y,J,Z,q)}}}function YJ(q,J,Z,Q,$){MQ(Z,Q,$,q6(q,J))}function N2(q,J,Z,Q,$,W,Y,z){let X=q,w=FJ(Q,$,W);w.sort((_,G)=>G.order-_.order);let F;for(let _ of w)for(let G of z2(_)){let B;if(G.history==="deep")B=(R)=>jJ(R)&&C1(R,_);else B=(R)=>{return R.parent===_};F??={...W},F[G.id]=Array.from($).filter(B)}for(let _ of w)X=n1(X,J,Z,[..._.exit,..._.invoke.map((G)=>w8(G.id))],Y,void 0),$.delete(_);return[X,F||W]}function V2(q,J){return q.implementations.actions[J]}function fQ(q,J,Z,Q,$,W){let{machine:Y}=q,z=q;for(let X of Q){let w=typeof X==="function",F=w?X:V2(Y,typeof X==="string"?X:X.type),_={context:z.context,event:J,self:Z.self,system:Z.system},G=w||typeof X==="string"?void 0:("params"in X)?typeof X.params==="function"?X.params({context:z.context,event:J}):X.params:void 0;if(!F||!("resolve"in F)){Z.actionExecutor({type:typeof X==="string"?X:typeof X==="object"?X.type:X.name||"(anonymous)",info:_,params:G,exec:F});continue}let B=F,[R,S,e]=B.resolve(Z,z,_,G,F,$);if(z=R,"retryResolve"in B)W?.push([B,S]);if("execute"in B)Z.actionExecutor({type:B.type,info:_,params:S,exec:B.execute.bind(null,Z,S)});if(e)z=fQ(z,J,Z,e,$,W)}return z}function n1(q,J,Z,Q,$,W){let Y=W?[]:void 0,z=fQ(q,J,Z,Q,{internalQueue:$,deferredActorIds:W},Y);return Y?.forEach(([X,w])=>{X.retryResolve(Z,z,w)}),z}function _8(q,J,Z,Q){let $=q,W=[];function Y(w,F,_){Z.system._sendInspectionEvent({type:"@xstate.microstep",actorRef:Z.self,event:F,snapshot:w,_transitions:_}),W.push(w)}if(J.type===s1)return $=b1(VQ($,J,Z),{status:"stopped"}),Y($,J,[]),{snapshot:$,microstates:W};let z=J;if(z.type!==DQ){let w=z,F=p3(w),_=BQ(w,$);if(F&&!_.length)return $=b1(q,{status:"error",error:w.error}),Y($,w,[]),{snapshot:$,microstates:W};$=W8(_,q,Z,z,!1,Q),Y($,w,_)}let X=!0;while($.status==="active"){let w=X?B2($,z):[],F=w.length?$:void 0;if(!w.length){if(!Q.length)break;z=Q.shift(),w=BQ(z,$)}$=W8(w,$,Z,z,!1,Q),X=$!==F,Y($,z,w)}if($.status!=="active")VQ($,z,Z);return{snapshot:$,microstates:W}}function VQ(q,J,Z){return n1(q,J,Z,Object.values(q.children).map((Q)=>w8(Q)),[],void 0)}function BQ(q,J){return J.machine.getTransitionData(J,q)}function B2(q,J){let Z=new Set,Q=q._nodes.filter(jJ);for(let $ of Q)q:for(let W of[$].concat(q6($,void 0))){if(!W.always)continue;for(let Y of W.always)if(Y.guard===void 0||Bq(Y.guard,q.context,J,q)){Z.add(Y);break q}}return bQ(Array.from(Z),new Set(q._nodes),q.historyValue)}function SQ(q,J){let Z=J6(Dq(q,J));return PQ(q,[...Z])}function hQ(q){return!!q&&typeof q==="object"&&"machine"in q&&"value"in q}var D2=function(J){return NJ(J,this.value)},U2=function(J){return this.tags.has(J)},K2=function(J){let Z=this.machine.getTransitionData(this,J);return!!Z?.length&&Z.some((Q)=>Q.target!==void 0||Q.actions.length)},j2=function(){let{_nodes:J,tags:Z,machine:Q,getMeta:$,toJSON:W,can:Y,hasTag:z,matches:X,...w}=this;return{...w,tags:Array.from(Z)}},I2=function(){return this._nodes.reduce((J,Z)=>{if(Z.meta!==void 0)J[Z.id]=Z.meta;return J},{})};function Q6(q,J){return{status:q.status,output:q.output,error:q.error,machine:J,context:q.context,_nodes:q._nodes,value:PQ(J.root,q._nodes),tags:new Set(q._nodes.flatMap((Z)=>Z.tags)),children:q.children,historyValue:q.historyValue||{},matches:D2,hasTag:U2,can:K2,getMeta:I2,toJSON:j2}}function b1(q,J={}){return Q6({...q,...J},q.machine)}function vQ(q,J){let{_nodes:Z,tags:Q,machine:$,children:W,context:Y,can:z,hasTag:X,matches:w,getMeta:F,toJSON:_,...G}=q,B={};for(let S in W){let e=W[S];B[S]={snapshot:e.getPersistedSnapshot(J),src:e.src,systemId:e._systemId,syncSnapshot:e._syncSnapshot}}return{...G,context:yQ(Y),children:B}}function yQ(q){let J;for(let Z in q){let Q=q[Z];if(Q&&typeof Q==="object")if("sessionId"in Q&&"send"in Q&&"ref"in Q)J??=Array.isArray(q)?q.slice():{...q},J[Z]={xstate$$type:z8,id:Q.id};else{let $=yQ(Q);if($!==Q)J??=Array.isArray(q)?q.slice():{...q},J[Z]=$}}return J??q}function L2(q,J,Z,Q,{event:$,id:W,delay:Y},{internalQueue:z}){let X=J.machine.implementations.delays;if(typeof $==="string")throw Error(`Only event objects may be used with raise; use raise({ type: "${$}" }) instead`);let w=typeof $==="function"?$(Z,Q):$,F;if(typeof Y==="string"){let _=X&&X[Y];F=typeof _==="function"?_(Z,Q):_}else F=typeof Y==="function"?Y(Z,Q):Y;if(typeof F!=="number")z.push(w);return[J,{event:w,id:W,delay:F},void 0]}function A2(q,J){let{event:Z,delay:Q,id:$}=J;if(typeof Q==="number"){q.defer(()=>{let W=q.self;q.system.scheduler.schedule(W,W,Z,Q,$)});return}}function AJ(q,J){function Z(Q,$){}return Z.type="xstate.raise",Z.event=q,Z.id=J?.id,Z.delay=J?.delay,Z.resolve=L2,Z.execute=A2,Z}function pQ(q,J){return{config:q,transition:(Z,Q,$)=>{return{...Z,context:q(Z.context,Q,$)}},getInitialSnapshot:(Z,Q)=>{return{status:"active",output:void 0,error:void 0,context:typeof J==="function"?J({input:Q}):J}},getPersistedSnapshot:(Z)=>Z,restoreSnapshot:(Z)=>Z}}var uQ=new WeakMap;function RJ(q){return{config:q,start:(Z,Q)=>{let{self:$,system:W,emit:Y}=Q,z={receivers:void 0,dispose:void 0};uQ.set($,z),z.dispose=q({input:Z.input,system:W,self:$,sendBack:(X)=>{if($.getSnapshot().status==="stopped")return;if($._parent)W._relay($,$._parent,X)},receive:(X)=>{z.receivers??=new Set,z.receivers.add(X)},emit:Y})},transition:(Z,Q,$)=>{let W=uQ.get($.self);if(Q.type===s1)return Z={...Z,status:"stopped",error:void 0},W.dispose?.(),Z;return W.receivers?.forEach((Y)=>Y(Q)),Z},getInitialSnapshot:(Z,Q)=>{return{status:"active",output:void 0,error:void 0,input:Q}},getPersistedSnapshot:(Z)=>Z,restoreSnapshot:(Z)=>Z}}var gQ="xstate.observable.next",mQ="xstate.observable.error",lQ="xstate.observable.complete";function O0(q){return{config:q,transition:(Z,Q)=>{if(Z.status!=="active")return Z;switch(Q.type){case gQ:return{...Z,context:Q.data};case mQ:return{...Z,status:"error",error:Q.data,input:void 0,_subscription:void 0};case lQ:return{...Z,status:"done",input:void 0,_subscription:void 0};case s1:return Z._subscription.unsubscribe(),{...Z,status:"stopped",input:void 0,_subscription:void 0};default:return Z}},getInitialSnapshot:(Z,Q)=>{return{status:"active",output:void 0,error:void 0,context:void 0,input:Q,_subscription:void 0}},start:(Z,{self:Q,system:$,emit:W})=>{if(Z.status==="done")return;Z._subscription=q({input:Z.input,system:$,self:Q,emit:W}).subscribe({next:(Y)=>{$._relay(Q,Q,{type:gQ,data:Y})},error:(Y)=>{$._relay(Q,Q,{type:mQ,data:Y})},complete:()=>{$._relay(Q,Q,{type:lQ})}})},getPersistedSnapshot:({_subscription:Z,...Q})=>Q,restoreSnapshot:(Z)=>({...Z,_subscription:void 0})}}var dQ="xstate.promise.resolve",cQ="xstate.promise.reject",H8=new WeakMap;function d(q){return{config:q,transition:(Z,Q,$)=>{if(Z.status!=="active")return Z;switch(Q.type){case dQ:{let W=Q.data;return{...Z,status:"done",output:W,input:void 0}}case cQ:return{...Z,status:"error",error:Q.data,input:void 0};case s1:return H8.get($.self)?.abort(),{...Z,status:"stopped",input:void 0};default:return Z}},start:(Z,{self:Q,system:$,emit:W})=>{if(Z.status!=="active")return;let Y=new AbortController;H8.set(Q,Y),Promise.resolve(q({input:Z.input,system:$,self:Q,signal:Y.signal,emit:W})).then((X)=>{if(Q.getSnapshot().status!=="active")return;H8.delete(Q),$._relay(Q,Q,{type:dQ,data:X})},(X)=>{if(Q.getSnapshot().status!=="active")return;H8.delete(Q),$._relay(Q,Q,{type:cQ,data:X})})},getInitialSnapshot:(Z,Q)=>{return{status:"active",output:void 0,error:void 0,input:Q}},getPersistedSnapshot:(Z)=>Z,restoreSnapshot:(Z)=>Z}}var AV=pQ((q)=>{return},void 0);function R2(q,{machine:J,context:Z},Q,$){let W=(Y,z)=>{if(typeof Y==="string"){let X=eq(J,Y);if(!X)throw Error(`Actor logic '${Y}' not implemented in machine '${J.id}'`);let w=e0(X,{id:z?.id,parent:q.self,syncSnapshot:z?.syncSnapshot,input:typeof z?.input==="function"?z.input({context:Z,event:Q,self:q.self}):z?.input,src:Y,systemId:z?.systemId});return $[w.id]=w,w}else return e0(Y,{id:z?.id,parent:q.self,syncSnapshot:z?.syncSnapshot,input:z?.input,src:Y,systemId:z?.systemId})};return(Y,z)=>{let X=W(Y,z);return $[X.id]=X,q.defer(()=>{if(X._processingStatus===m0.Stopped)return;X.start()}),X}}function P2(q,J,Z,Q,{assignment:$}){if(!J.context)throw Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");let W={},Y={context:J.context,event:Z.event,spawn:R2(q,J,Z.event,W),self:q.self,system:q.system},z={};if(typeof $==="function")z=$(Y,Q);else for(let w of Object.keys($)){let F=$[w];z[w]=typeof F==="function"?F(Y,Q):F}let X=Object.assign({},J.context,z);return[b1(J,{context:X,children:Object.keys(W).length?{...J.children,...W}:J.children}),void 0,void 0]}function N(q){function J(Z,Q){}return J.type="xstate.assign",J.assignment=q,J.resolve=P2,J}function E2(q,J,Z,Q,{event:$}){let W=typeof $==="function"?$(Z,Q):$;return[J,{event:W},void 0]}function x2(q,{event:J}){q.defer(()=>q.emit(J))}function PJ(q){function J(Z,Q){}return J.type="xstate.emit",J.event=q,J.resolve=E2,J.execute=x2,J}var sQ=new WeakMap;function Uq(q,J,Z){let Q=sQ.get(q);if(!Q)Q={[J]:Z()},sQ.set(q,Q);else if(!(J in Q))Q[J]=Z();return Q[J]}var k2={},$6=(q)=>{if(typeof q==="string")return{type:q};if(typeof q==="function"){if("resolve"in q)return{type:q.type};return{type:q.name}}return q};class EJ{constructor(q,J){if(this.config=q,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=J._parent,this.key=J._key,this.machine=J._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(_J),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?VJ(this.config.states,(Z,Q)=>{return new EJ(Z,{_parent:this,_key:Q,_machine:this.machine})}):k2,this.type==="compound"&&!this.config.initial)throw Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=V1(this.config.entry).slice(),this.exit=V1(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=V1(q.tags).slice()}_initialize(){if(this.transitions=kQ(this),this.config.always)this.always=c1(this.config.always).map((q)=>O1(this,HJ,q));Object.keys(this.states).forEach((q)=>{this.states[q]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map($6),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map((q)=>`#${q.id}`),source:`#${this.id}`,actions:this.initial.actions.map($6),eventType:null})}:void 0,history:this.history,states:VJ(this.states,(q)=>{return q.definition}),on:this.on,transitions:[...this.transitions.values()].flat().map((q)=>({...q,actions:q.actions.map($6)})),entry:this.entry.map($6),exit:this.exit.map($6),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return Uq(this,"invoke",()=>V1(this.config.invoke).map((q,J)=>{let{src:Z,systemId:Q}=q,$=q.id??BJ(this.id,J),W=typeof Z==="string"?Z:`xstate.invoke.${BJ(this.id,J)}`;return{...q,src:W,id:$,systemId:Q,toJSON(){let{onDone:Y,onError:z,...X}=q;return{...X,type:"xstate.invoke",src:W,id:$}}}}))}get on(){return Uq(this,"on",()=>{return[...this.transitions].flatMap(([J,Z])=>Z.map((Q)=>[J,Q])).reduce((J,[Z,Q])=>{return J[Z]=J[Z]||[],J[Z].push(Q),J},{})})}get after(){return Uq(this,"delayedTransitions",()=>xQ(this))}get initial(){return Uq(this,"initial",()=>OQ(this,this.config.initial))}next(q,J){let Z=J.type,Q=[],$,W=Uq(this,`candidates-${Z}`,()=>EQ(this,Z));for(let Y of W){let{guard:z}=Y,X=q.context,w=!1;try{w=!z||Bq(z,X,J,q)}catch(F){let _=typeof z==="string"?z:typeof z==="object"?z.type:void 0;throw Error(`Unable to evaluate guard ${_?`'${_}' `:""}in transition for event '${Z}' in state node '${this.id}':
16
+ ${F.message}`)}if(w){Q.push(...Y.actions),$=Y;break}}return $?[$]:void 0}get events(){return Uq(this,"events",()=>{let{states:q}=this,J=new Set(this.ownEvents);if(q)for(let Z of Object.keys(q)){let Q=q[Z];if(Q.states)for(let $ of Q.events)J.add(`${$}`)}return Array.from(J)})}get ownEvents(){let q=new Set([...this.transitions.keys()].filter((J)=>{return this.transitions.get(J).some((Z)=>!(!Z.target&&!Z.actions.length&&!Z.reenter))}));return Array.from(q)}}var O2="#";class xJ{constructor(q,J){this.config=q,this.version=void 0,this.schemas=void 0,this.implementations=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.id=q.id||"(machine)",this.implementations={actors:J?.actors??{},actions:J?.actions??{},delays:J?.delays??{},guards:J?.guards??{}},this.version=this.config.version,this.schemas=this.config.schemas,this.transition=this.transition.bind(this),this.getInitialSnapshot=this.getInitialSnapshot.bind(this),this.getPersistedSnapshot=this.getPersistedSnapshot.bind(this),this.restoreSnapshot=this.restoreSnapshot.bind(this),this.start=this.start.bind(this),this.root=new EJ(q,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(q){let{actions:J,guards:Z,actors:Q,delays:$}=this.implementations;return new xJ(this.config,{actions:{...J,...q.actions},guards:{...Z,...q.guards},actors:{...Q,...q.actors},delays:{...$,...q.delays}})}resolveState(q){let J=SQ(this.root,q.value),Z=J6(Dq(this.root,J));return Q6({_nodes:[...Z],context:q.context||{},children:{},status:X8(Z,this.root)?"done":q.status||"active",output:q.output,error:q.error,historyValue:q.historyValue},this)}transition(q,J,Z){return _8(q,J,Z,[]).snapshot}microstep(q,J,Z){return _8(q,J,Z,[]).microstates}getTransitionData(q,J){return F8(this.root,q.value,q,J)||[]}getPreInitialState(q,J,Z){let{context:Q}=this.config,$=Q6({context:typeof Q!=="function"&&Q?Q:{},_nodes:[this.root],children:{},status:"active"},this);if(typeof Q==="function")return n1($,J,q,[N(({spawn:Y,event:z,self:X})=>Q({spawn:Y,input:z.input,self:X}))],Z,void 0);return $}getInitialSnapshot(q,J){let Z=GJ(J),Q=[],$=this.getPreInitialState(q,Z,Q),W=W8([{target:[...IJ(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],$,q,Z,!0,Q),{snapshot:Y}=_8(W,Z,q,Q);return Y}start(q){Object.values(q.children).forEach((J)=>{if(J.getSnapshot().status==="active")J.start()})}getStateNodeById(q){let J=Y8(q),Z=J.slice(1),Q=Z6(J[0])?J[0].slice(O2.length):J[0],$=this.idMap.get(Q);if(!$)throw Error(`Child state node '#${Q}' does not exist on machine '${this.id}'`);return tq($,Z)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedSnapshot(q,J){return vQ(q,J)}restoreSnapshot(q,J){let Z={},Q=q.children;Object.keys(Q).forEach((z)=>{let X=Q[z],w=X.snapshot,F=X.src,_=typeof F==="string"?eq(this,F):F;if(!_)return;let G=e0(_,{id:z,parent:J.self,syncSnapshot:X.syncSnapshot,snapshot:w,src:F,systemId:X.systemId});Z[z]=G});let $=Q6({...q,children:Z,_nodes:Array.from(J6(Dq(this.root,q.value)))},this),W=new Set;function Y(z,X){if(W.has(z))return;W.add(z);for(let w in z){let F=z[w];if(F&&typeof F==="object"){if("xstate$$type"in F&&F.xstate$$type===z8){z[w]=X[F.id];continue}Y(F,X)}}}return Y($.context,Z),$}}function C2(q,J){return new xJ(q,J)}function i({schemas:q,actors:J,actions:Z,guards:Q,delays:$}){return{createMachine:(W)=>C2({...W,schemas:q},{actors:J,actions:Z,guards:Q,delays:$})}}class G8{_tag="DeviceNotOnboardedError";originalError;constructor(q){this.originalError=Error(q??"Device not onboarded.")}}class B1{_tag="DeviceLockedError";originalError;constructor(q){this.originalError=Error(q??"Device locked.")}}class i1{_tag="UnsupportedFirmwareDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class T1{_tag="RefusedByUserDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class N8{_tag="AppAlreadyInstalledDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class D1{_tag="OutOfMemoryDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class q0{_tag="UnknownDAError";originalError;constructor(q){this.originalError=Error(q??"Unknown error.")}}class kJ{_tag="UnsupportedApplicationDAError";originalError;constructor(q){this.originalError=Error(q??"Application currently not supported.")}}class OJ{_tag="MissingLanguagePackagesForOSDAError";originalError;constructor(q){this.originalError=Error(q??"Missing Language Packages for OS DAError.")}}class CJ{_tag="MissingLanguagePackageDAError";originalError;constructor(q){this.originalError=Error(q??"Missing Language Package DAError.")}}class V8{_tag="DeleteLanguagePackDAError";originalError;constructor(q){this.originalError=Error(q??"Delete language pack failed.")}}class bJ{_tag="NetworkDAError";originalError;constructor(q){this.originalError=Error(q??"Network error.")}}var t=60000;import{first as S2,from as h2,interval as v2,map as y2,switchMap as u2}from"rxjs";import{timeout as g2}from"rxjs/operators";import{Observable as b2,ReplaySubject as T2,share as M2}from"rxjs";var nQ={subscribers:[],error:()=>{},warn:()=>{},info:()=>{},debug:()=>{}},TJ=(q)=>nQ;class a{input;inspect=!1;logger;loggerFactory;constructor(q){this.input=q.input,this.inspect=!!q.inspect,this.logger=q.logger,this.loggerFactory=q.loggerFactory}getLoggerFactory(q){return this.loggerFactory??q.loggerFactory??TJ}_execute(q){let J=this.makeStateMachine(q);return!this.logger&&J.id&&(this.logger=this.getLoggerFactory(q)(J.id)),this._subscribeToStateMachine(J)}_subscribeToStateMachine(q){let J=e0(q,{input:this.input}),Z=new T2,Q=!1,$=(z)=>{let{context:X,status:w,output:F,error:_}=z;if(this.logger&&!Q&&(Q=!0,this.logger.debug("[XStateDeviceAction] Input",{data:{input:X.input}})),this.logger&&(w==="active"||w==="done")){let G=typeof z.value=="string"?z.value:JSON.stringify(z.value);this.logger.debug(`[XStateDeviceAction] State: ${G}`,{data:{internalState:X._internalState,intermediateValue:X.intermediateValue}})}switch(w){case"active":Z.next({status:d1.Pending,intermediateValue:X.intermediateValue});break;case"done":F.caseOf({Left:(G)=>{Z.next({status:d1.Error,error:G})},Right:(G)=>{Z.next({status:d1.Completed,output:G})}}),Z.complete();break;case"error":Z.error(_),Z.complete();break;case"stopped":Z.next({status:d1.Stopped}),Z.complete();break;default:this._exhaustiveMatchingGuard(w)}},W=new b2((z)=>{let X=Z.subscribe(z);return()=>{Y.unsubscribe(),X.unsubscribe(),J.stop()}}),Y=J.subscribe($);return J.start(),{observable:W.pipe(M2()),cancel:()=>{J.stop(),Y.unsubscribe(),$(J.getSnapshot())}}}_exhaustiveMatchingGuard(q){throw console.log("_exhaustiveMatchingGuard status",q),Error(`Unhandled status: ${q}`)}}var B8="BOLOS",f2=["BOLOS","OLOS","OLOS\x00"],a1=(q)=>q!=null&&f2.includes(q);var D8=Object.freeze({GET_APP_AND_VERSION:"os.waitForAppAndVersion.steps.getAppAndVersion",UNLOCK_DEVICE:"os.waitForAppAndVersion.steps.unlockDevice"});var iQ=(q)=>!n(q)&&("errorCode"in q.error)&&q.error.errorCode==="5515",m2=(q)=>!n(q)&&("errorCode"in q.error)&&q.error.errorCode==="6e00";class U8 extends a{makeStateMachine(q){let{getAppAndVersion:J,waitForDeviceUnlock:Z}=this.extractDependencies(q),Q=this.input.unlockTimeout??t;return i({types:{input:{unlockTimeout:Q},context:{},output:{}},actors:{getAppAndVersion:d(J),waitForDeviceUnlock:O0(Z)},guards:{isDeviceLocked:({context:$})=>$._internalState.locked,hasError:({context:$})=>$._internalState.error!==null},actions:{assignErrorDeviceLocked:N({_internalState:($)=>({...$.context._internalState,error:new B1})}),assignErrorFromEvent:N({_internalState:($)=>({...$.context._internalState,error:$.event.error})})}}).createMachine({id:"WaitForAppAndVersionDeviceAction",initial:"GetAppAndVersion",context:($)=>({input:{unlockTimeout:$.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:D8.GET_APP_AND_VERSION},_internalState:{appAndVersion:null,locked:!1,error:null}}),states:{GetAppAndVersion:{entry:N({intermediateValue:($)=>({...$.context.intermediateValue,step:D8.GET_APP_AND_VERSION,requiredUserInteraction:k.None})}),invoke:{src:"getAppAndVersion",onDone:{target:"CheckGetAppAndVersionResult",actions:N({_internalState:($)=>n($.event.output)?{...$.context._internalState,locked:!1,appAndVersion:$.event.output.data}:iQ($.event.output)?{...$.context._internalState,locked:!0}:m2($.event.output)?{...$.context._internalState,locked:!1,appAndVersion:{name:B8,version:"0.0.0"}}:{...$.context._internalState,error:$.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CheckGetAppAndVersionResult:{always:[{guard:"hasError",target:"Error"},{guard:"isDeviceLocked",target:"AwaitingForDeviceUnlocked"},{target:"Success"}]},AwaitingForDeviceUnlocked:{entry:N({intermediateValue:($)=>({...$.context.intermediateValue,requiredUserInteraction:k.UnlockDevice,step:D8.UNLOCK_DEVICE})}),invoke:{id:"AwaitingForDeviceUnlocked",src:"waitForDeviceUnlock",input:($)=>({unlockTimeout:Q}),onDone:{target:"GetAppAndVersion",actions:N({_internalState:($)=>({...$.context._internalState,locked:!1})})},onError:{target:"Error",actions:"assignErrorDeviceLocked"}}},Success:{type:"final"},Error:{type:"final"}},output:($)=>{let{context:W}=$,{error:Y,appAndVersion:z}=W._internalState;return Y?j(Y):L(z)}})}extractDependencies(q){return{getAppAndVersion:()=>q.sendCommand(new a0),waitForDeviceUnlock:({input:J})=>v2(1000).pipe(u2(()=>h2(q.sendCommand(new a0))),S2((Z)=>!iQ(Z)),y2(()=>{}),g2(J.unlockTimeout))}}}var m=((q)=>(q[q.Connected=0]="Connected",q[q.ReadyWithoutSecureChannel=1]="ReadyWithoutSecureChannel",q[q.ReadyWithSecureChannel=2]="ReadyWithSecureChannel",q))(m||{});var MJ=Object.freeze({WAIT_FOR_APP_AND_VERSION:"os.getDeviceStatus.steps.waitForAppAndVersion",ONBOARD_CHECK:"os.getDeviceStatus.steps.onboardCheck"});var l2=(q)=>({mcu:q.mcuSephVersion,bootloader:q.mcuBootloaderVersion,os:q.seVersion,metadata:q});class Kq extends a{makeStateMachine(q){let{getOsVersion:J,getDeviceSessionState:Z,setDeviceSessionState:Q}=this.extractDependencies(q),$=this.input.unlockTimeout??t,W=this.input.allowNonOnboardedDevice??!0,Y=(X)=>{let w=Z();w.sessionStateType!==m.Connected&&Q({...w,firmwareVersion:l2(X),isSecureConnectionAllowed:X.secureElementFlags.isSecureConnectionAllowed})},z=new U8({input:{unlockTimeout:$}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:$,allowNonOnboardedDevice:W},context:{},output:{}},actors:{waitForAppAndVersion:z,getOsVersion:d(J)},guards:{isCurrentAppBolos:({context:X})=>a1(X._internalState.currentApp),isOnboardedFromOsVersion:({context:X})=>X._internalState.osVersionMetadata?.secureElementFlags.isOnboarded===!0,isAllowedNonOnboardedDevice:({context:X})=>{let w=X._internalState.osVersionMetadata?.secureElementFlags;return X.input.allowNonOnboardedDevice===!0&&w?.isOnboarded===!1},hasError:({context:X})=>X._internalState.error!==null},actions:{assignErrorDeviceNotOnboarded:N({_internalState:(X)=>({...X.context._internalState,error:new G8})}),assignErrorFromEvent:N({_internalState:(X)=>({...X.context._internalState,error:X.event.error})})}}).createMachine({id:"GetDeviceStatusDeviceAction",initial:"DeviceReady",context:(X)=>{let w=Z(),{sessionStateType:F}=w;return{input:{unlockTimeout:X.input.unlockTimeout,allowNonOnboardedDevice:X.input.allowNonOnboardedDevice??!0},intermediateValue:{requiredUserInteraction:k.None,step:MJ.WAIT_FOR_APP_AND_VERSION},_internalState:{onboarded:!1,currentApp:F===m.ReadyWithoutSecureChannel?w.currentApp.name:null,currentAppVersion:null,osVersionMetadata:null,error:null}}},states:{DeviceReady:{always:{target:"WaitForAppAndVersion"}},WaitForAppAndVersion:{invoke:{src:"waitForAppAndVersion",input:(X)=>({unlockTimeout:X.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:X.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"WaitForAppAndVersionResultCheck",actions:N({_internalState:(X)=>X.event.output.caseOf({Left:(w)=>({...X.context._internalState,error:w}),Right:(w)=>{let F=Z();return F.sessionStateType!==m.Connected?Q({...F,currentApp:w}):Q({deviceModelId:F.deviceModelId,sessionStateType:m.ReadyWithoutSecureChannel,deviceStatus:g0.CONNECTED,currentApp:w,installedApps:[],isSecureConnectionAllowed:!1}),{...X.context._internalState,currentApp:w.name,currentAppVersion:w.version}}})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},WaitForAppAndVersionResultCheck:{always:[{guard:"hasError",target:"Error"},{target:"OnboardingCheck"}]},OnboardingCheck:{entry:N({intermediateValue:(X)=>({...X.context.intermediateValue,requiredUserInteraction:k.None,step:MJ.ONBOARD_CHECK})}),always:[{guard:"isCurrentAppBolos",target:"GetOsVersion"},{target:"Success",actions:N({_internalState:(X)=>({...X.context._internalState,onboarded:!0})})}]},GetOsVersion:{invoke:{src:"getOsVersion",onDone:{target:"OnboardingResultCheck",actions:N({_internalState:(X)=>n(X.event.output)?(Y(X.event.output.data),{...X.context._internalState,osVersionMetadata:X.event.output.data}):{...X.context._internalState,error:X.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},OnboardingResultCheck:{always:[{guard:"hasError",target:"Error"},{guard:"isOnboardedFromOsVersion",target:"Success",actions:N({_internalState:(X)=>({...X.context._internalState,onboarded:!0})})},{guard:"isAllowedNonOnboardedDevice",target:"Success"},{target:"Error",actions:"assignErrorDeviceNotOnboarded"}]},Success:{type:"final"},Error:{type:"final"}},output:(X)=>{let{context:w}=X,{error:F,currentApp:_,currentAppVersion:G}=w._internalState;return F?j(F):L({currentApp:_,currentAppVersion:G})}})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new M0),getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}class R0{_tag="GeneralDmkError";originalError;constructor(q){q instanceof Error?this.originalError=q:q!==void 0&&(this.originalError=Error(String(q)))}}class d2 extends R0{constructor(q){super(q);this.err=q}_tag="DeviceAlreadyDiscoveredError"}class c2 extends R0{constructor(q){super(q);this.err=q}_tag="DeviceNotRecognizedError"}class p2 extends R0{constructor(q){super(q);this.err=q}_tag="NoAccessibleDeviceError"}class s2 extends R0{_tag="ConnectionOpeningError";constructor(q){super(q)}}class n2 extends R0{constructor(q){super(q);this.err=q}_tag="UnknownDeviceError"}class o1 extends R0{constructor(q){super(q);this.err=q}_tag="TransportNotSupportedError"}class i2 extends R0{constructor(q){super(q);this.err=q}_tag="SendApduConcurrencyError"}class fJ extends R0{constructor(q){super(q);this.err=q}_tag="SendApduTimeoutError"}class SJ extends R0{constructor(q){super(q);this.err=q}_tag="SendCommandTimeoutError"}class a2 extends R0{constructor(q){super(q);this.err=q}_tag="SendApduEmptyResponseError"}class o2 extends R0{constructor(q){super(q);this.err=q}_tag="DisconnectError"}class r2 extends R0{constructor(q){super(q);this.err=q}_tag="ReconnectionFailedError"}class t2 extends R0{constructor(q){super(q);this.err=q}_tag="DeviceNotInitializedError"}class e2 extends R0{constructor(q){super(q);this.err=q}_tag="NoTransportsProvidedError"}class hJ extends R0{constructor(q){super(q);this.err=q}_tag="TransportAlreadyExistsError"}class r1 extends R0{constructor(q){super(q);this.err=q}_tag="DeviceDisconnectedWhileSendingError"}class W6 extends R0{constructor(q){super(q);this.err=q}_tag="AlreadySendingApduError"}class vJ extends R0{constructor(q){super(q);this.err=q}_tag="DeviceDisconnectedBeforeSendingApdu"}class yJ extends R0{constructor(q){super(q);this.err=q}_tag="NoTransportProvidedError"}var aQ=Object.freeze({LIST_APPS:"os.openApp.steps.listApps",ONBOARD_CHECK:"os.openApp.steps.onboardCheck",GET_DEVICE_STATUS:"os.openApp.steps.getDeviceStatus",DASHBOARD_CHECK:"os.openApp.steps.dashboardCheck",CONFIRM_OPEN_APP:"os.openApp.steps.confirmOpenApp",CLOSE_APP:"os.openApp.steps.closeApp"});class M1 extends a{makeStateMachine(q){let{closeApp:J,openApp:Z,getDeviceSessionState:Q,setDeviceSessionState:$}=this.extractDependencies(q),W=this.input.unlockTimeout??t,Y=new Kq({input:{unlockTimeout:W,allowNonOnboardedDevice:!1}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{closeApp:d(J),openApp:d(Z),getDeviceStatus:Y},guards:{isRequestedAppOpen:({context:z})=>z._internalState.currentlyRunningApp===null?!1:z._internalState.currentlyRunningApp===z.input.appName,isDashboardOpen:({context:z})=>{if(z._internalState.currentlyRunningApp===null)throw Error("context.currentlyRunningApp === null");return a1(z._internalState.currentlyRunningApp)},hasDisconnectedWhileSending:({context:z})=>z._internalState.error!==null&&z._internalState.error instanceof r1,hasError:({context:z})=>z._internalState.error!==null},actions:{assignUserActionNeededOpenApp:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:k.ConfirmOpenApp})}),assignNoUserActionNeeded:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:k.None})}),assignErrorFromEvent:N({_internalState:(z)=>({...z.context._internalState,error:z.event.error})}),assignNoError:N({_internalState:(z)=>({...z.context._internalState,error:null})})}}).createMachine({id:"OpenAppDeviceAction",initial:"DeviceReady",context:({input:z})=>{let X=Q(),{sessionStateType:w}=X;return{input:z,intermediateValue:{requiredUserInteraction:k.None,step:aQ.GET_DEVICE_STATUS},_internalState:{error:null,currentlyRunningApp:w===m.ReadyWithoutSecureChannel?X.currentApp.name:null}}},states:{DeviceReady:{always:{target:"GetDeviceStatus"}},GetDeviceStatus:{invoke:{id:"deviceStatus",src:"getDeviceStatus",input:(z)=>({unlockTimeout:z.context.input.unlockTimeout,allowNonOnboardedDevice:!1}),onSnapshot:{actions:N({intermediateValue:(z)=>z.event.snapshot.context.intermediateValue})},onDone:{target:"CheckDeviceStatus",actions:N({_internalState:(z)=>z.event.output.caseOf({Right:(X)=>{let w=Q();return w.sessionStateType!==m.Connected&&$({...w,currentApp:{name:X.currentApp,version:X.currentAppVersion}}),{...z.context._internalState,currentlyRunningApp:X.currentApp}},Left:(X)=>({...z.context._internalState,currentlyRunningApp:null,error:X})})})},onError:{target:"Error",actions:[N({_internalState:(z)=>({...z.context._internalState,currentlyRunningApp:null})}),"assignErrorFromEvent"]}}},CheckDeviceStatus:{always:[{target:"ApplicationReady",guard:"isRequestedAppOpen",actions:"assignNoError"},{target:"Error",guard:"hasError"},{target:"DashboardCheck"}]},DashboardCheck:{always:[{target:"OpenApplication",guard:"isDashboardOpen"},"CloseApplication"]},OpenApplication:{entry:"assignUserActionNeededOpenApp",exit:"assignNoUserActionNeeded",invoke:{src:"openApp",input:({context:z})=>({appName:z.input.appName}),onDone:{target:"OpenApplicationResultCheck",actions:N({_internalState:(z)=>n(z.event.output)?{...z.context._internalState,currentlyRunningApp:z.context.input.appName}:{...z.context._internalState,error:z.event.output.error}})},onError:{target:"OpenApplicationResultCheck",actions:"assignErrorFromEvent"}}},OpenApplicationResultCheck:{always:[{target:"GetDeviceStatus",guard:"hasDisconnectedWhileSending"},{target:"Error",guard:"hasError"},{target:"GetDeviceStatus"}]},CloseApplication:{invoke:{src:"closeApp",onDone:{target:"CloseApplicationResultCheck",actions:N({_internalState:(z)=>n(z.event.output)?{...z.context._internalState,currentlyRunningApp:B8}:{...z.context._internalState,error:z.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CloseApplicationResultCheck:{always:[{target:"Error",guard:"hasError"},{target:"OpenApplication"}]},ApplicationReady:{always:"Success"},Success:{type:"final",actions:"assignNoError"},Error:{type:"final"}},output:({context:z})=>z._internalState.error?j(z._internalState.error):L(void 0)})}extractDependencies(q){return{closeApp:async()=>q.sendCommand(new wq),openApp:async(J)=>q.sendCommand(new t6({appName:J.input.appName})),getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}var K8=Object.freeze({OPEN_APP:"os.callTaskInApp.steps.openApp",CALL_TASK:"os.callTaskInApp.steps.callTask"});class oQ extends a{makeStateMachine(q){let{callTask:J}=this.extractDependencies(q);return i({types:{input:{},context:{},output:{}},actors:{callTask:d(J),openAppStateMachine:new M1({input:{appName:this.input.appName}}).makeStateMachine(q)},guards:{skipOpenApp:()=>this.input.skipOpenApp,noInternalError:({context:Z})=>Z._internalState.error===null},actions:{assignErrorFromEvent:N({_internalState:(Z)=>({...Z.context._internalState,error:Z.event.error})})}}).createMachine({id:"CallTaskInAppDeviceAction",initial:"InitialState",context:({input:Z})=>({input:Z,intermediateValue:{requiredUserInteraction:k.None,step:K8.OPEN_APP},_internalState:{taskResponse:null,error:null}}),states:{InitialState:{always:[{target:"CallTask",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",input:{appName:this.input.appName},src:"openAppStateMachine",onSnapshot:{actions:N({intermediateValue:(Z)=>Z.event.snapshot.context.intermediateValue})},onDone:{actions:N({_internalState:(Z)=>Z.event.output.caseOf({Right:()=>Z.context._internalState,Left:(Q)=>({...Z.context._internalState,error:Q})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"CallTask",guard:"noInternalError"},"Error"]},CallTask:{entry:N({intermediateValue:{requiredUserInteraction:this.input.requiredUserInteraction,step:K8.CALL_TASK}}),exit:N({intermediateValue:{requiredUserInteraction:k.None,step:K8.CALL_TASK}}),invoke:{id:"callTask",src:"callTask",input:(Z)=>Z.context.input.task,onDone:{target:"CallTaskResultCheck",actions:[N({_internalState:({event:Z,context:Q})=>x1(Z.output)?{...Q._internalState,taskResponse:Z.output.data}:{...Q._internalState,error:Z.output.error}})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CallTaskResultCheck:{always:[{target:"Success",guard:"noInternalError"},"Error"]},Success:{type:"final"},Error:{type:"final"}},output:({context:Z})=>Z._internalState.taskResponse?L(Z._internalState.taskResponse):j(Z._internalState.error||new q0("No error in final state"))})}extractDependencies(q){return{callTask:(J)=>J.input(q)}}}var Y6=Object.freeze({GET_DEVICE_STATUS:"os.goToDashboard.steps.getDeviceStatus",DASHBOARD_CHECK:"os.goToDashboard.steps.dashboardCheck",CLOSE_APP:"os.goToDashboard.steps.closeApp",CONFIRM_DASHBOARD_OPEN:"os.goToDashboard.steps.confirmDashboardOpen"});class f0 extends a{makeStateMachine(q){let{getDeviceSessionState:J,setDeviceSessionState:Z,closeApp:Q,getAppAndVersion:$}=this.extractDependencies(q),W=this.input.unlockTimeout??t,Y=new Kq({input:{unlockTimeout:W}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:W},context:{},output:{}},actors:{getAppAndVersion:d($),closeApp:d(Q),getDeviceStatus:Y},guards:{hasError:({context:z})=>z._internalState.error!==null,isDashboardOpen:({context:z})=>z._internalState.currentApp!==null&&a1(z._internalState.currentApp)},actions:{assignErrorFromEvent:N({_internalState:(z)=>({...z.context._internalState,error:z.event.error})})}}).createMachine({id:"GoToDashboardDeviceAction",initial:"DeviceReady",context:(z)=>{let X=J();return{input:{unlockTimeout:z.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:Y6.GET_DEVICE_STATUS},_internalState:{currentApp:"currentApp"in X?X.currentApp.name:null,error:null}}},states:{DeviceReady:{always:{target:"GetDeviceStatus"}},GetDeviceStatus:{invoke:{id:"deviceStatus",src:"getDeviceStatus",input:(z)=>({unlockTimeout:z.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(z)=>z.event.snapshot.context.intermediateValue})},onDone:{target:"CheckDeviceStatus",actions:N({_internalState:(z)=>z.event.output.caseOf({Right:(X)=>({...z.context._internalState,currentApp:X.currentApp}),Left:(X)=>({...z.context._internalState,error:X})})})}}},CheckDeviceStatus:{always:[{target:"Error",guard:"hasError"},{target:"DashboardCheck"}]},DashboardCheck:{always:[{target:"Success",guard:"isDashboardOpen"},{target:"Error",guard:"hasError"},{target:"Error",guard:(z)=>z.context._internalState.currentApp===null,actions:N({_internalState:(z)=>({...z.context._internalState,error:new q0("currentApp === null")}),intermediateValue:(z)=>({requiredUserInteraction:k.None,step:Y6.DASHBOARD_CHECK})})},{target:"CloseApp"}]},CloseApp:{invoke:{src:"closeApp",onDone:{target:"CloseAppCheck",actions:N({_internalState:(z)=>n(z.event.output)?z.context._internalState:{...z.context._internalState,error:z.event.output.error},intermediateValue:(z)=>({requiredUserInteraction:k.None,step:Y6.CLOSE_APP})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},CloseAppCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetAppAndVersion",reenter:!0}]},GetAppAndVersion:{invoke:{src:"getAppAndVersion",onDone:{target:"DashboardCheck",actions:N({_internalState:(z)=>{if(n(z.event.output)){let X=J();return X.sessionStateType!==m.Connected&&Z({...X,currentApp:z.event.output.data}),{...z.context._internalState,currentApp:z.event.output.data.name}}return{...z.context._internalState,error:z.event.output.error}},intermediateValue:(z)=>({requiredUserInteraction:k.None,step:Y6.CONFIRM_DASHBOARD_OPEN})})}}},Success:{type:"final"},Error:{type:"final"}},output:(z)=>z.context._internalState.error?j(z.context._internalState.error):L(void 0)})}extractDependencies(q){return{closeApp:async()=>q.sendCommand(new wq),getAppAndVersion:async()=>q.sendCommand(new a0),getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}var uJ=Object.freeze({GO_TO_DASHBOARD:"os.listApps.steps.goToDashboard",LIST_APPS:"os.listApps.steps.listApps"});class jq extends a{makeStateMachine(q){let{listApps:J}=this.extractDependencies(q),Z=this.input.unlockTimeout??t,Q=new f0({input:{unlockTimeout:Z}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:Z},context:{},output:{}},actors:{listApps:d(J),goToDashboard:Q},guards:{hasError:({context:$})=>$._internalState.error!==null,hasMoreApps:($)=>$.context._internalState.shouldContinue},actions:{assignAllowListApps:N({intermediateValue:($)=>({requiredUserInteraction:k.AllowListApps,step:uJ.LIST_APPS})}),assignErrorFromEvent:N({_internalState:($)=>({...$.context._internalState,error:$.event.error})})}}).createMachine({id:"ListAppsDeviceAction",initial:"DeviceReady",context:($)=>({input:{unlockTimeout:$.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:uJ.GO_TO_DASHBOARD},_internalState:{error:null,apps:[],shouldContinue:!1}}),states:{DeviceReady:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"dashboard",src:"goToDashboard",input:($)=>({unlockTimeout:$.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:($)=>$.event.snapshot.context.intermediateValue})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:($)=>$.event.output.caseOf({Right:()=>$.context._internalState,Left:(W)=>({...$.context._internalState,error:W})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"ListApps"}]},ListApps:{entry:"assignAllowListApps",invoke:{src:"listApps",input:($)=>!1,onDone:{target:"Continue",actions:N({_internalState:($)=>n($.event.output)?{...$.context._internalState,apps:$.context._internalState.apps.concat($.event.output.data),shouldContinue:$.event.output.data.length>=2}:{...$.context._internalState,error:$.event.output.error},intermediateValue:($)=>({...$.context.intermediateValue,requiredUserInteraction:k.None})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListAppsCheck:{always:[{target:"Error",guard:"hasError"},"ListAppsContinue"]},ListAppsContinue:{invoke:{src:"listApps",input:($)=>!0,onDone:{target:"Continue",actions:N({_internalState:($)=>n($.event.output)?{...$.context._internalState,apps:$.context._internalState.apps.concat($.event.output.data),shouldContinue:$.event.output.data.length>=2}:{...$.context._internalState,error:$.event.output.error}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Continue:{always:[{target:"ListAppsContinue",guard:"hasMoreApps"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:($)=>$.context._internalState.error?j($.context._internalState.error):L($.context._internalState.apps)})}extractDependencies(q){return{listApps:async({input:J})=>{let Z=new o6({isContinue:J});return q.sendCommand(Z)}}}}var rQ=k1(_q(),1);class j8{_tag="InvalidGetFirmwareMetadataResponseError";originalError;constructor(q){this.originalError=Error(q??"Invalid Firmware Metadata response error.")}}class z6{_tag="GetApplicationsMetadataTaskError";originalError;constructor(q){this.originalError=Error(q??"Failed to get applications metadata.")}}var qw="0000000000000000000000000000000000000000000000000000000000000000";class gJ{constructor(q,J){this.api=q,this.args=J}async run(){let q=this.args.installedApps.filter((F)=>this.isApplication(F)),J=this.api.getManagerApiService(),Z=q.map((F)=>F.hash),Q=await J.getAppsByHash(Z).chain((F)=>J.getAppList(this.args.firmwareVersion.metadata).map((_)=>({applications:F,catalog:_})));if(Q.isLeft())return i0({error:new z6("Cannot get the application catalog")});let{applications:$,catalog:W}=Q.unsafeCoerce(),Y=$.reduce((F,_,G)=>{if(_!==null)return[...F,_];let B=q[G],R=W.find((S)=>S.versionName===B.name);return R?[...F,R]:F},[]),z=$.filter((F)=>F!==null).reduce((F,_)=>{let G=W.find((B)=>B.versionName===_.versionName);return G&&rQ.gt(G.version,_.version)?[...F,G]:F},[]),X=[];for(let F=0;;F++){let _=await this.api.sendCommand(new r6({firstChunk:F===0}));if(!n(_)||_.data===void 0)break;X=[...X,_.data]}let w=await J.getLanguagePackages(this.args.deviceVersion,this.args.firmware);return w.isRight()?i0({data:{applications:Y,applicationsUpdates:z,installedLanguages:X,catalog:{applications:W,languagePackages:w.extract()}}}):i0({error:new z6("Cannot get the languages catalog")})}isApplication(q){return q.hashCode!==qw}}class mJ{constructor(q){this.api=q}async run(){let q=await this.api.sendCommand(new M0);if(!n(q))return i0({error:q.error});let J={mcu:q.data.mcuSephVersion,bootloader:q.data.mcuBootloaderVersion,os:q.data.seVersion,metadata:q.data},Z=this.api.getManagerApiService(),Q=await Z.getDeviceVersion(q.data).chain((F)=>Z.getFirmwareVersion(q.data,F).map((_)=>({deviceVersion:F,currentFirmware:_})));if(Q.isLeft())return i0({error:new j8});let{deviceVersion:$,currentFirmware:W}=Q.unsafeCoerce(),Y=await this.getAvailableUpdate(Z,W,$,J),z={currentFirmware:W,availableUpdate:Y},X={},w=await this.api.sendCommand(new h6);return n(w)&&(X={size:w.data}),i0({data:{deviceVersion:$,firmware:W,firmwareVersion:J,firmwareUpdateContext:z,customImage:X}})}async getAvailableUpdate(q,J,Z,Q){let $=await q.getLatestFirmwareVersion(J,Z);if($.isLeft())return;let W=$.unsafeCoerce();if(!W.isNothing())return this.getFirmwareUpdate(q,W.unsafeCoerce(),Q)}async getFirmwareUpdate(q,J,Z){let Q=await q.getNextFirmwareVersion(J);if(Q.isLeft())return;let $=await q.getMcuList();if($.isLeft())return;let W=Q.unsafeCoerce(),Y=$.unsafeCoerce().find((z)=>z.name===Z.mcu);return{osuFirmware:J,finalFirmware:W,mcuUpdateRequired:Y===void 0||!W.mcuVersions.includes(Y.id)}}}function I8(q){return Array.isArray(q)&&q.every((J)=>typeof J=="object"&&J!==null&&("flags"in J)&&("hash"in J)&&("hash_code_data"in J)&&("name"in J)&&typeof J.flags=="number"&&typeof J.hash=="string"&&typeof J.hash_code_data=="string"&&typeof J.name=="string")}var Iq=null;if(typeof WebSocket<"u")Iq=WebSocket;else if(typeof MozWebSocket<"u")Iq=MozWebSocket;else if(typeof global<"u")Iq=global.WebSocket||global.MozWebSocket;else if(typeof window<"u")Iq=window.WebSocket||window.MozWebSocket;else if(typeof self<"u")Iq=self.WebSocket||self.MozWebSocket;var L8=Iq;import{Observable as Dw}from"rxjs";var Jw=((q)=>(q.GenuineCheck="GenuineCheck",q.ListInstalledApps="ListInstalledApps",q.UpdateMcu="UpdateMcu",q.UpdateFirmware="UpdateFirmware",q.InstallApp="InstallApp",q.UninstallApp="UninstallApp",q))(Jw||{}),U1=((q)=>(q.EXCHANGE="exchange",q.BULK="bulk",q.ERROR="error",q.WARNING="warning",q.SUCCESS="success",q))(U1||{}),A8=((q)=>(q.SUCCESS="success",q.ERROR="error",q))(A8||{}),M=((q)=>(q.Opened="opened",q.Closed="closed",q.PermissionRequested="permission-requested",q.PermissionGranted="permission-granted",q.PreExchange="pre-exchange",q.Exchange="exchange",q.DeviceId="device-id",q.Progress="progress",q.Warning="warning",q.Error="error",q.Result="result",q))(M||{});var tQ="0000";function eQ(q){return q[0]===224&&q[1]===81}function q$(q){return q[0]===224&&q[1]===82}function J$(q){try{let J=new z0(q);return J.extractFieldLVEncoded()?J.extractFieldLVEncoded()??null:null}catch{return null}}function Z$(q){return q===tQ}var R8=BigInt(4294967295),Q$=BigInt(32);function Zw(q,J=!1){if(J)return{h:Number(q&R8),l:Number(q>>Q$&R8)};return{h:Number(q>>Q$&R8)|0,l:Number(q&R8)|0}}function $$(q,J=!1){let Z=q.length,Q=new Uint32Array(Z),$=new Uint32Array(Z);for(let W=0;W<Z;W++){let{h:Y,l:z}=Zw(q[W],J);[Q[W],$[W]]=[Y,z]}return[Q,$]}var W$=(q,J,Z)=>q<<Z|J>>>32-Z,Y$=(q,J,Z)=>J<<Z|q>>>32-Z,z$=(q,J,Z)=>J<<Z-32|q>>>64-Z,w$=(q,J,Z)=>q<<Z-32|J>>>64-Z;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Qw(q){return q instanceof Uint8Array||ArrayBuffer.isView(q)&&q.constructor.name==="Uint8Array"}function lJ(q){if(!Number.isSafeInteger(q)||q<0)throw Error("positive integer expected, got "+q)}function w6(q,...J){if(!Qw(q))throw Error("Uint8Array expected");if(J.length>0&&!J.includes(q.length))throw Error("Uint8Array expected of length "+J+", got length="+q.length)}function dJ(q,J=!0){if(q.destroyed)throw Error("Hash instance has been destroyed");if(J&&q.finished)throw Error("Hash#digest() has already been called")}function X$(q,J){w6(q);let Z=J.outputLen;if(q.length<Z)throw Error("digestInto() expects output buffer of length at least "+Z)}function F$(q){return new Uint32Array(q.buffer,q.byteOffset,Math.floor(q.byteLength/4))}function cJ(...q){for(let J=0;J<q.length;J++)q[J].fill(0)}function rD(q){return new DataView(q.buffer,q.byteOffset,q.byteLength)}function tD(q,J){return q<<32-J|q>>>J}function eD(q,J){return q<<J|q>>>32-J>>>0}var $w=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Ww(q){return q<<24&4278190080|q<<8&16711680|q>>>8&65280|q>>>24&255}function Yw(q){for(let J=0;J<q.length;J++)q[J]=Ww(q[J]);return q}var pJ=$w?(q)=>q:Yw;function zw(q){if(typeof q!=="string")throw Error("string expected");return new Uint8Array(new TextEncoder().encode(q))}function sJ(q){if(typeof q==="string")q=zw(q);return w6(q),q}class nJ{}function _$(q){let J=(Q)=>q().update(sJ(Q)).digest(),Z=q();return J.outputLen=Z.outputLen,J.blockLen=Z.blockLen,J.create=()=>q(),J}var ww=BigInt(0),X6=BigInt(1),Xw=BigInt(2),Fw=BigInt(7),_w=BigInt(256),Hw=BigInt(113),N$=[],V$=[],B$=[];for(let q=0,J=X6,Z=1,Q=0;q<24;q++){[Z,Q]=[Q,(2*Z+3*Q)%5],N$.push(2*(5*Q+Z)),V$.push((q+1)*(q+2)/2%64);let $=ww;for(let W=0;W<7;W++)if(J=(J<<X6^(J>>Fw)*Hw)%_w,J&Xw)$^=X6<<(X6<<BigInt(W))-X6;B$.push($)}var D$=$$(B$,!0),Gw=D$[0],Nw=D$[1],H$=(q,J,Z)=>Z>32?z$(q,J,Z):W$(q,J,Z),G$=(q,J,Z)=>Z>32?w$(q,J,Z):Y$(q,J,Z);function Vw(q,J=24){let Z=new Uint32Array(10);for(let Q=24-J;Q<24;Q++){for(let Y=0;Y<10;Y++)Z[Y]=q[Y]^q[Y+10]^q[Y+20]^q[Y+30]^q[Y+40];for(let Y=0;Y<10;Y+=2){let z=(Y+8)%10,X=(Y+2)%10,w=Z[X],F=Z[X+1],_=H$(w,F,1)^Z[z],G=G$(w,F,1)^Z[z+1];for(let B=0;B<50;B+=10)q[Y+B]^=_,q[Y+B+1]^=G}let $=q[2],W=q[3];for(let Y=0;Y<24;Y++){let z=V$[Y],X=H$($,W,z),w=G$($,W,z),F=N$[Y];$=q[F],W=q[F+1],q[F]=X,q[F+1]=w}for(let Y=0;Y<50;Y+=10){for(let z=0;z<10;z++)Z[z]=q[Y+z];for(let z=0;z<10;z++)q[Y+z]^=~Z[(z+2)%10]&Z[(z+4)%10]}q[0]^=Gw[Q],q[1]^=Nw[Q]}cJ(Z)}class iJ extends nJ{constructor(q,J,Z,Q=!1,$=24){super();if(this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=q,this.suffix=J,this.outputLen=Z,this.enableXOF=Q,this.rounds=$,lJ(Z),!(0<q&&q<200))throw Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=F$(this.state)}clone(){return this._cloneInto()}keccak(){pJ(this.state32),Vw(this.state32,this.rounds),pJ(this.state32),this.posOut=0,this.pos=0}update(q){dJ(this),q=sJ(q),w6(q);let{blockLen:J,state:Z}=this,Q=q.length;for(let $=0;$<Q;){let W=Math.min(J-this.pos,Q-$);for(let Y=0;Y<W;Y++)Z[this.pos++]^=q[$++];if(this.pos===J)this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:q,suffix:J,pos:Z,blockLen:Q}=this;if(q[Z]^=J,(J&128)!==0&&Z===Q-1)this.keccak();q[Q-1]^=128,this.keccak()}writeInto(q){dJ(this,!1),w6(q),this.finish();let J=this.state,{blockLen:Z}=this;for(let Q=0,$=q.length;Q<$;){if(this.posOut>=Z)this.keccak();let W=Math.min(Z-this.posOut,$-Q);q.set(J.subarray(this.posOut,this.posOut+W),Q),this.posOut+=W,Q+=W}return q}xofInto(q){if(!this.enableXOF)throw Error("XOF is not possible for this instance");return this.writeInto(q)}xof(q){return lJ(q),this.xofInto(new Uint8Array(q))}digestInto(q){if(X$(q,this),this.finished)throw Error("digest() was already called");return this.writeInto(q),this.destroy(),q}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,cJ(this.state)}_cloneInto(q){let{blockLen:J,suffix:Z,outputLen:Q,rounds:$,enableXOF:W}=this;return q||(q=new iJ(J,Z,Q,W,$)),q.state32.set(this.state32),q.pos=this.pos,q.posOut=this.posOut,q.finished=this.finished,q.rounds=$,q.suffix=Z,q.outputLen=Q,q.enableXOF=W,q.destroyed=this.destroyed,q}}var Bw=(q,J,Z)=>_$(()=>new iJ(J,q,Z));var U$=(()=>Bw(6,136,32))();class aJ{sha3_256(q){return U$(q)}}var Lq=((q)=>(q[q.AppAlreadyInstalled=0]="AppAlreadyInstalled",q[q.DeviceLocked=1]="DeviceLocked",q[q.OutOfMemory=2]="OutOfMemory",q[q.RefusedByUser=3]="RefusedByUser",q[q.Unknown=4]="Unknown",q))(Lq||{});class oJ{constructor(q){this.error=q,this.originalError=q}_tag="WebSocketConnectionError";originalError}class x0{constructor(q,J=4){this.error=q,this.errorType=J,this.originalError=q}_tag="SecureChannelError";originalError;mapDAErrors(){switch(this.errorType){case 1:return new B1;case 3:return new T1;default:return this}}mapInstallDAErrors(){switch(this.errorType){case 1:return new B1;case 3:return new T1;case 0:return new N8;case 2:return new D1;default:return this}}mapUpdateFirmwareDAErrors(){switch(this.errorType){case 2:return new D1;case 1:return new B1;case 3:return new T1;case 4:return new q0;default:return this}}mapFlashMcuDAErrors(){switch(this.errorType){case 1:return new B1;case 4:return new q0;default:return this}}}class c0{constructor(q,J){if(this._api=q,this._args=J,this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new x0(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`);this._cryptoService=this._args.cryptoService??new aJ}_connection;_cryptoService;_deviceIdCaptured=!1;run(){return new Dw((q)=>{let J=!1,Z=!1,Q=!1,$=(W)=>{q.next({type:M.Error,error:W}),q.complete(),Z=!0};return this._connection.onopen=()=>{q.next({type:M.Opened})},this._connection.onerror=(W)=>{Z||(q.next({type:M.Error,error:new x0({url:this._connection.url,errorMessage:W.message})}),q.complete())},this._connection.onclose=()=>{Z||(Q?q.next({type:M.Closed}):q.next({type:M.Error,error:new x0({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),q.complete())},this._connection.onmessage=async(W)=>{if(J)return;let Y;try{let z=JSON.parse(String(W.data));if(this.isInMessageType(z))Y=z;else throw Error("Data does not match InMessageType")}catch{$(new x0({url:this._connection.url,errorMessage:`Invalid message received: ${String(W.data)}`}));return}switch(Y.query){case U1.EXCHANGE:{let{nonce:z,data:X}=Y;if(typeof X!="string"){$(new x0(`${U1.EXCHANGE} data type should be an APDU`));return}let w=_1(X);if(w===null||w.length<5){$(new x0(`Received invalid APDU data: ${X}`));return}q.next({type:M.PreExchange,payload:{nonce:z,apdu:w}});let F=!1;eQ(w)&&!this.isSecureConnectionAllowed()&&(F=!0,q.next({type:M.PermissionRequested}));let _=await this._api.sendApdu(w);if(J)return;_.caseOf({Left:(G)=>{$(new x0(G))},Right:(G)=>{let B,R=this.mapDeviceError(G);if(R===null){if(B=A8.SUCCESS,!this._deviceIdCaptured&&q$(w)){this._deviceIdCaptured=!0;let e=J$(G);if(e){let s0=this._cryptoService.sha3_256(e);q.next({type:M.DeviceId,payload:{deviceId:s0}})}}q.next({type:M.Exchange,payload:{nonce:z,apdu:w,data:G.data,status:G.statusCode}}),F&&q.next({type:M.PermissionGranted})}else B=A8.ERROR,$(R);let S={nonce:z,response:B,data:D0(G.data,!1)};this._connection.send(JSON.stringify(S))}});break}case U1.BULK:{if(Z=!0,this._connection.close(),!Array.isArray(Y.data)||Y.data.length===0||!Y.data.every((z)=>typeof z=="string")){$(new x0("Invalid bulk data received"));return}for(let z=0,X=Y.data.length;z<X;z++){let w=_1(Y.data[z]);if(w===null||w.length<5){$(new x0(`Received invalid APDU bulk data: ${Y.data[z]}`));return}let F=await this._api.sendApdu(w);if(J)return;if(F.isLeft()){$(new x0(F.extract()));return}else if(F.isRight()){let _=this.mapDeviceError(F.extract());if(_===null)q.next({type:M.Progress,payload:{progress:+Number((z+1)/X).toFixed(2),index:z,total:X}});else{$(_);return}}}Q=!0,q.complete();break}case U1.SUCCESS:{if(Z)break;let z=Y.result??Y.data;z&&q.next({type:M.Result,payload:z??""}),Q=!0,q.complete();break}case U1.WARNING:{if(Z)break;q.next({type:M.Warning,payload:{message:String(Y.data)}});break}case U1.ERROR:{if(Z)break;$(new x0({url:this._connection.url,errorMessage:String(Y.data)}))}}},()=>{J=!0,this._connection.readyState===L8.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){let q=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in q&&q.isSecureConnectionAllowed}isInMessageType(q){if(typeof q!="object"||!q)return!1;let J=q;return typeof J.uuid=="string"&&typeof J.session=="string"&&typeof J.query=="string"&&Object.values(U1).includes(J.query)&&typeof J.nonce=="number"}mapDeviceError(q){return l.isSuccessResponse(q)?null:l.isLockedDeviceResponse(q)?new x0({url:this._connection.url,errorMessage:"Device is locked"},Lq.DeviceLocked):l.isRefusedByUser(q)?new x0({url:this._connection.url,errorMessage:"User refused on the device"},Lq.RefusedByUser):l.isAppAlreadyInstalled(q)?new x0({url:this._connection.url,errorMessage:"App already installed"},Lq.AppAlreadyInstalled):l.isOutOfMemory(q)?new x0({url:this._connection.url,errorMessage:"Out of memory"},Lq.OutOfMemory):new x0({url:this._connection.url,errorMessage:`Invalid status code: ${D0(q.statusCode)}`})}}var t1=Object.freeze({GET_DEVICE_METADATA:"os.getDeviceMetadata.steps.getDeviceMetadata",GO_TO_DASHBOARD:"os.getDeviceMetadata.steps.goToDashboard",GET_FIRMWARE_METADATA:"os.getDeviceMetadata.steps.getFirmwareMetadata",LIST_APPS_SECURE_CHANNEL:"os.getDeviceMetadata.steps.listAppsSecureChannel",LIST_APPS:"os.getDeviceMetadata.steps.listApps",GET_APPLICATIONS_METADATA:"os.getDeviceMetadata.steps.getApplicationsMetadata"});class f1 extends a{makeStateMachine(q){let{getDeviceMetadata:J,getFirmwareMetadata:Z,getApplicationsMetadata:Q,listAppsSecureChannel:$}=this.extractDependencies(q),W=this.input.unlockTimeout??t,Y=new f0({input:{unlockTimeout:W}}).makeStateMachine(q),z=new jq({input:{unlockTimeout:W}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:W},context:{},output:{}},actors:{goToDashboard:Y,getDeviceMetadata:d(J),getFirmwareMetadata:d(Z),getApplicationsMetadata:d(Q),listApps:z,listAppsSecureChannel:O0($)},guards:{hasError:({context:X})=>X._internalState.error!==null,hasMetadata:({context:X})=>X._internalState.firmwareVersion!==null&&X._internalState.firmwareUpdateContext!==null&&X._internalState.customImage!==null&&X._internalState.applications!==null&&X._internalState.applicationsUpdates!==null&&X._internalState.installedLanguages!==null&&X._internalState.catalog!==null,forceUpdate:({context:X})=>!!X.input.forceUpdate,useSecureChannel:({context:X})=>!!X.input.useSecureChannel},actions:{assignErrorFromEvent:N({_internalState:(X)=>({...X.context._internalState,error:X.event.error})})}}).createMachine({id:"GetDeviceMetadataDeviceAction",initial:"DeviceReady",context:(X)=>({input:{useSecureChannel:X.input.useSecureChannel,forceUpdate:X.input.forceUpdate,unlockTimeout:X.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:t1.GET_DEVICE_METADATA},_internalState:{error:null,deviceVersion:null,firmware:null,firmwareVersion:null,firmwareUpdateContext:null,customImage:null,installedApps:null,applications:null,applicationsUpdates:null,installedLanguages:null,catalog:null}}),states:{DeviceReady:{always:[{target:"GoToDashboard",guard:"forceUpdate"},{target:"GetDeviceMetadataFromContext"}]},GetDeviceMetadataFromContext:{invoke:{src:"getDeviceMetadata",onDone:{target:"GetDeviceMetadataFromContextResultCheck",actions:N({_internalState:(X)=>X.event.output===null?X.context._internalState:{...X.context._internalState,firmwareVersion:X.event.output.firmwareVersion,firmwareUpdateContext:X.event.output.firmwareUpdateContext,customImage:X.event.output.customImage,applications:X.event.output.applications,applicationsUpdates:X.event.output.applicationsUpdates,installedLanguages:X.event.output.installedLanguages,catalog:X.event.output.catalog}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceMetadataFromContextResultCheck:{always:[{target:"Success",guard:"hasMetadata"},{target:"GoToDashboard"}]},GoToDashboard:{exit:N({intermediateValue:{requiredUserInteraction:k.None,step:t1.GO_TO_DASHBOARD}}),invoke:{id:"dashboard",src:"goToDashboard",input:(X)=>({unlockTimeout:X.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(X)=>X.event.snapshot.context.intermediateValue})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(X)=>X.event.output.caseOf({Right:()=>X.context._internalState,Left:(w)=>({...X.context._internalState,error:w})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetFirmwareMetadata"}]},GetFirmwareMetadata:{invoke:{src:"getFirmwareMetadata",onDone:{target:"GetFirmwareMetadataResultCheck",actions:N({_internalState:(X)=>{if(x1(X.event.output)){let w=q.getDeviceSessionState();return w.sessionStateType!==m.Connected&&q.setDeviceSessionState({...w,firmwareVersion:X.event.output.data.firmwareVersion,firmwareUpdateContext:X.event.output.data.firmwareUpdateContext,customImage:X.event.output.data.customImage}),{...X.context._internalState,deviceVersion:X.event.output.data.deviceVersion,firmware:X.event.output.data.firmware,firmwareVersion:X.event.output.data.firmwareVersion,firmwareUpdateContext:X.event.output.data.firmwareUpdateContext,customImage:X.event.output.data.customImage}}return{...X.context._internalState,error:X.event.output.error}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetFirmwareMetadataResultCheck:{always:[{guard:"hasError",target:"Error"},{guard:"useSecureChannel",target:"ListAppsSecureChannel"},{target:"ListApps"}]},ListAppsSecureChannel:{exit:N({intermediateValue:{requiredUserInteraction:k.None,step:t1.LIST_APPS_SECURE_CHANNEL}}),invoke:{id:"listAppsSecureChannel",src:"listAppsSecureChannel",input:(X)=>({firmware:X.context._internalState.firmware,firmwareVersion:X.context._internalState.firmwareVersion}),onSnapshot:{actions:N({intermediateValue:(X)=>{switch(X.event.snapshot.context?.type){case M.DeviceId:return{...X.context.intermediateValue,deviceId:X.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...X.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:{let w=q.getDeviceSessionState();return w.sessionStateType!==m.Connected&&q.setDeviceSessionState({...w,isSecureConnectionAllowed:!0}),{...X.context.intermediateValue,requiredUserInteraction:k.None}}default:return{...X.context.intermediateValue}}},_internalState:(X)=>{if(X.event.snapshot.context?.type===M.Error)return{...X.context._internalState,error:X.event.snapshot.context.error.mapDAErrors()};if(X.event.snapshot.context?.type===M.Result){if(I8(X.event.snapshot.context.payload))return{...X.context._internalState,installedApps:X.event.snapshot.context.payload.map((w)=>({name:w.name,hash:w.hash,hashCode:w.hash_code_data}))};throw Error(`Invalid result ${JSON.stringify(X.event.snapshot.context.payload)}`)}return{...X.context._internalState}}})},onDone:{target:"ListAppsCheck"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListApps:{exit:N({intermediateValue:{requiredUserInteraction:k.None,step:t1.LIST_APPS}}),invoke:{id:"listApps",src:"listApps",input:(X)=>({unlockTimeout:X.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(X)=>X.event.snapshot.context.intermediateValue})},onDone:{target:"ListAppsCheck",actions:N({_internalState:(X)=>X.event.output.isLeft()?{...X.context._internalState,error:X.event.output.extract()}:{...X.context._internalState,installedApps:X.event.output.unsafeCoerce().map((w)=>({name:w.appName,hash:w.appFullHash,hashCode:w.appCodeHash}))}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetApplicationsMetadata"}]},GetApplicationsMetadata:{invoke:{src:"getApplicationsMetadata",input:(X)=>({deviceVersion:X.context._internalState.deviceVersion,firmware:X.context._internalState.firmware,firmwareVersion:X.context._internalState.firmwareVersion,installedApps:X.context._internalState.installedApps}),onDone:{target:"GetApplicationsMetadataResultCheck",actions:N({_internalState:(X)=>{if(x1(X.event.output)){let w=q.getDeviceSessionState();return w.sessionStateType!==m.Connected&&q.setDeviceSessionState({...w,installedApps:X.event.output.data.applications,appsUpdates:X.event.output.data.applicationsUpdates,installedLanguages:X.event.output.data.installedLanguages,catalog:X.event.output.data.catalog}),{...X.context._internalState,applications:X.event.output.data.applications,applicationsUpdates:X.event.output.data.applicationsUpdates,installedLanguages:X.event.output.data.installedLanguages,catalog:X.event.output.data.catalog}}return{...X.context._internalState,error:X.event.output.error}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetApplicationsMetadataResultCheck:{always:[{guard:"hasError",target:"Error"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(X)=>{let{context:w}=X,{error:F,firmwareVersion:_,firmwareUpdateContext:G,customImage:B,applications:R,applicationsUpdates:S,installedLanguages:e,catalog:s0}=w._internalState;return F?j(F):L({firmwareVersion:_,firmwareUpdateContext:G,customImage:B,applications:R,applicationsUpdates:S,installedLanguages:e,catalog:s0})}})}extractDependencies(q){return{getDeviceMetadata:()=>{let J=q.getDeviceSessionState();return J.sessionStateType===m.Connected||J.firmwareVersion?.metadata===void 0||J.firmwareUpdateContext===void 0||J.customImage===void 0||J.installedApps.length===0||J.appsUpdates===void 0||J.installedLanguages===void 0||J.catalog===void 0?Promise.resolve(null):Promise.resolve({firmwareVersion:J.firmwareVersion,firmwareUpdateContext:J.firmwareUpdateContext,customImage:J.customImage,applications:J.installedApps,applicationsUpdates:J.appsUpdates,installedLanguages:J.installedLanguages,catalog:J.catalog})},getFirmwareMetadata:async()=>new mJ(q).run(),getApplicationsMetadata:async(J)=>new gJ(q,{deviceVersion:J.input.deviceVersion,firmware:J.input.firmware,firmwareVersion:J.input.firmwareVersion,installedApps:J.input.installedApps}).run(),listAppsSecureChannel:(J)=>{let{firmware:Z,firmwareVersion:Q}=J.input,$=q.getSecureChannelService().listInstalledApps(Q.metadata,Z);return new c0(q,{connection:$}).run()}}}}import{Observable as Uw}from"rxjs";class rJ{constructor(q,J){this.api=q,this.args=J}run(){return new Uw((q)=>{(async()=>{let J;try{let Q=await fetch(this.args.apduInstallUrl);if(!Q.ok)throw Error(`HTTP ${Q.status} ${Q.statusText}`);J=await Q.text()}catch(Q){throw new bJ(`Failed to fetch APDUs: ${Q instanceof Error?Q.message:String(Q)}`)}let Z=J.split(/\r?\n/).filter(Boolean);if(typeof J!="string"||Z.length===0)throw new q0(`Language pack install script contains no APDUs: ${this.args.apduInstallUrl}`);for(let Q=0;Q<Z.length;Q++){let $=Z[Q],W=_1($);if(W===null||W.length<5)throw new q0(`Invalid APDU data: ${$}`);let Y=(await this.api.sendApdu(W)).caseOf({Left:(z)=>new q0(`Device communication error: ${String(z)}`),Right:(z)=>l.isRefusedByUser(z)?new T1("Language install refused on device."):l.isOutOfMemory(z)?new D1("Not enough space for language pack."):l.isSuccessResponse(z)?null:new q0(`Unexpected device response: ${D0(z.statusCode)}`)});if(Y)throw Y;q.next({type:"progress",progress:(Q+1)/Z.length})}})().then(()=>q.complete(),(J)=>q.error(J))})}}var Kw={0:"english",1:"french",2:"spanish",3:"brazilian",4:"german",5:"russian",6:"turkish",7:"thai"},K$=Object.freeze({DEVICE_READY:"os.installLanguagePackage.steps.deviceReady",GET_DEVICE_METADATA:"os.installLanguagePackage.steps.getDeviceMetadata",DELETE_CURRENT_LANGUAGE_PACK:"os.installLanguagePackage.steps.deleteCurrentLanguagePack",INSTALL_LANGUAGE_PACK:"os.installLanguagePackage.steps.installLanguagePack"});class j$ extends a{makeStateMachine(q){let{deleteCurrentLanguagePack:J,installLanguagePack:Z}=this.extractDependencies(q),Q=this.input.unlockTimeout??t,$=this.input.language,{None:W}=k,{DEVICE_READY:Y,GET_DEVICE_METADATA:z,DELETE_CURRENT_LANGUAGE_PACK:X,INSTALL_LANGUAGE_PACK:w}=K$,F=new f1({input:{unlockTimeout:Q}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:Q,language:$},context:{},output:{}},actors:{getDeviceMetadata:F,deleteCurrentLanguagePack:d(J),installLanguagePack:O0(({input:_})=>Z(_.apduInstallUrl))},guards:{isDefaultLanguage:({context:_})=>_.input.language==="english",hasError:({context:_})=>_._internalState.error!==null,shouldSkipInstall:({context:_})=>_._internalState.shouldSkipInstall},actions:{assignErrorFromEvent:N({_internalState:(_)=>({..._.context._internalState,error:_.event.error,shouldSkipInstall:!1})}),assignGetDeviceMetadataSnapshot:N({intermediateValue:(_)=>{let G=_.event.snapshot.context.intermediateValue;return G.step===t1.GET_DEVICE_METADATA?{...G,step:z}:G}}),assignGetDeviceMetadataDone:N({_internalState:(_)=>_.event.output.caseOf({Right:(G)=>{let B=G.catalog.languagePackages;if(!B)return{..._.context._internalState,error:new OJ(`Language packages not found for OS ${G?.firmwareVersion?.os}.`)};let R=B.find((S)=>S.language===$);return R?(G.installedLanguages??[]).map(({id:S})=>S).includes(R.languagePackageId)?{..._.context._internalState,shouldSkipInstall:!0}:{..._.context._internalState,languagePackage:R}:{..._.context._internalState,error:new CJ(`Language package not found for ${$}.`)}},Left:(G)=>({..._.context._internalState,error:G})})}),assignDeleteCurrentLanguagePackSnapshot:N({intermediateValue:(_)=>({requiredUserInteraction:W,step:X})}),assignDeleteCurrentLanguagePackDone:N({_internalState:(_)=>{let G=_.event.output;return n(G)?_.context._internalState:{..._.context._internalState,error:new V8("message"in G.error?G.error.message:"Delete language pack failed.")}}}),assignInstallLanguagePackSnapshot:N({intermediateValue:(_)=>{let G=_.event.snapshot.context,B=_.context,R="progress"in B.intermediateValue?B.intermediateValue.progress??0:0;return{requiredUserInteraction:W,step:w,progress:G?.type==="progress"?G.progress:R}}})}}).createMachine({id:"InstallLanguagePackageDeviceAction",initial:"CheckRequestedLanguage",context:(_)=>({input:{unlockTimeout:_.input.unlockTimeout,language:_.input.language},intermediateValue:{requiredUserInteraction:W,step:Y,progress:0},_internalState:{error:null,languagePackage:null,shouldSkipInstall:!1}}),states:{CheckRequestedLanguage:{always:[{guard:"isDefaultLanguage",target:"DeleteCurrentLanguagePack"},{target:"GetDeviceMetadata"}]},GetDeviceMetadata:{invoke:{id:"GetDeviceMetadata",src:"getDeviceMetadata",input:({context:_})=>({unlockTimeout:_.input.unlockTimeout,forceUpdate:!0,useSecureChannel:!0}),onSnapshot:{actions:"assignGetDeviceMetadataSnapshot"},onDone:{target:"LanguagePackCheck",actions:"assignGetDeviceMetadataDone"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},LanguagePackCheck:{always:[{guard:"hasError",target:"Error"},{guard:"shouldSkipInstall",target:"Success"},{target:"DeleteCurrentLanguagePack"}]},DeleteCurrentLanguagePack:{invoke:{id:"DeleteCurrentLanguagePack",src:"deleteCurrentLanguagePack",onSnapshot:{actions:"assignDeleteCurrentLanguagePackSnapshot"},onDone:{target:"DeleteCurrentLanguagePackResultCheck",actions:"assignDeleteCurrentLanguagePackDone"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},DeleteCurrentLanguagePackResultCheck:{always:[{guard:"hasError",target:"Error"},{guard:"isDefaultLanguage",target:"Success"},{target:"InstallLanguagePack"}]},InstallLanguagePack:{invoke:{id:"InstallLanguagePack",src:"installLanguagePack",input:({context:_})=>({apduInstallUrl:_._internalState.languagePackage.apduInstallUrl}),onSnapshot:{actions:"assignInstallLanguagePackSnapshot"},onDone:{target:"Success"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final"},Error:{type:"final"}},output:(_)=>_.context._internalState.error!==null?j(_.context._internalState.error):L(void 0)})}extractDependencies(q){return{deleteCurrentLanguagePack:()=>q.sendCommand(new S6({languagePackageId:255})),installLanguagePack:(J)=>new rJ(q,{apduInstallUrl:J}).run()}}}var tJ=k1(_q(),1);class eJ{constructor(q,J){this.api=q,this.args=J;let Z=q.getDeviceModel();this.deviceModelId=Z.id}deviceModelId;run(){let q=this.api.getDeviceSessionState();if(q.sessionStateType===m.Connected)return{error:new q0("Invalid device state")};if(q.catalog===void 0)return{error:new q0("Device apps metadata not fetched")};let J=[],Z=[],Q=[];for(let $ of this.args.applications){let W=q.catalog.applications.find((z)=>z.versionName===$.name),Y=q.installedApps.find((z)=>z.versionName===$.name);if(Y!==void 0&&this.validateConstraint(Y,W,$.constraints)){Z=[...Z,$.name];continue}if(W!==void 0&&this.validateConstraint(W,void 0,$.constraints))J=[...J,W];else if(this.args.allowMissingApplication)Q=[...Q,$.name];else return q.firmwareUpdateContext?.availableUpdate!==void 0&&W!==void 0?{error:new i1(`Application ${$.name} needs latest firmware`)}:q.firmwareUpdateContext?.availableUpdate!==void 0?{error:new i1(`Application ${$.name} needs latest firmware`)}:{error:new kJ(`Application ${$.name} not supported for this device`)}}return J=[...J.reduce(($,W)=>{let Y=W.parentName;if(Y){let z=q.catalog.applications.find((w)=>w.versionName===Y),X=q.installedApps.find((w)=>w.versionName===Y);if(z&&!X)return[...$,z]}return $},[]),...J],{installPlan:J.filter(($,W)=>J.findIndex((Y)=>Y.versionName===$.versionName)===W),missingApplications:Q,alreadyInstalled:Z}}validateConstraint(q,J,Z){if(Z===void 0)return!0;for(let Q of Z)if(!(Q.exemptModels!==void 0&&Q.exemptModels.includes(this.deviceModelId))&&!(Q.applicableModels!==void 0&&!Q.applicableModels.includes(this.deviceModelId)))return Q.minVersion==="latest"?!J||tJ.gte(q.version,J.version):tJ.gte(q.version,Q.minVersion);return!0}}var jw=1;class q5{constructor(q,J){this.api=q,this.args=J,this.deviceModel=q.getDeviceModel()}deviceModel;run(){let q=this.api.getDeviceSessionState();if(q.sessionStateType===m.Connected)return{error:new q0("Invalid device state")};let{firmwareUpdateContext:J,customImage:Z,firmwareVersion:Q,installedLanguages:$,installedApps:W}=q;if(J===void 0||Z===void 0||Q===void 0||$===void 0)return{error:new q0("Device metadata not fetched")};let{blockSize:Y,totalMemoryBlocks:z}=this.getMemoryConstants(Q),X=this.getCurrentMemoryBlocksUsage({firmwareUpdateContext:J,customImage:Z,installedApps:W,installedLanguages:$,blockSize:Y}),w=this.getInstallPlanMemoryBlocksUsage(this.args.installPlan,Y);return{outOfMemory:X+w>=z-jw}}getMemoryConstants(q){let J=this.deviceModel.getBlockSize({firmwareVersion:q.os}),Z=Math.floor(this.deviceModel.memorySize/J);return{blockSize:J,totalMemoryBlocks:Z}}getCurrentMemoryBlocksUsage({firmwareUpdateContext:q,customImage:J,installedApps:Z,installedLanguages:Q,blockSize:$}){let W=(F)=>Math.ceil(F/$),Y=W(q.currentFirmware.bytes||0),z=W(J.size||0),X=Z.reduce((F,_)=>F+W(_.bytes||0),0),w=Q.reduce((F,_)=>F+W(_.size),0);return Y+z+X+w}getInstallPlanMemoryBlocksUsage(q,J){let Z=(Q)=>Math.ceil(Q/J);return q.reduce((Q,$)=>Q+Z($.bytes||0),0)}}var I$=Object.freeze({UPDATE_DEVICE_METADATA:"os.installOrUpdateApps.steps.updateDeviceMetadata",BUILD_INSTALL_PLAN:"os.installOrUpdateApps.steps.buildInstallPlan",CHECK_IF_ENOUGH_MEMORY:"os.installOrUpdateApps.steps.checkIfEnoughMemory",INSTALL_APPLICATION:"os.installOrUpdateApps.steps.installApplication"});class P8 extends a{makeStateMachine(q){let{buildInstallPlan:J,predictOutOfMemory:Z,installApp:Q}=this.extractDependencies(q),$=this.input.unlockTimeout??t,W=new f1({input:{unlockTimeout:$,useSecureChannel:!0,forceUpdate:!1}}).makeStateMachine(q),Y=new f0({input:{unlockTimeout:$}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:$},context:{},output:{}},actors:{updateMetadata:W,buildInstallPlan:d(J),predictOutOfMemory:d(Z),goToDashboard:Y,installApp:O0(Q)},guards:{hasError:({context:z})=>z._internalState.error!==null,hasInstallPlan:(z)=>z.context.intermediateValue.installPlan!==null,hasMoreApps:(z)=>z.context._internalState.currentIndex<z.context.intermediateValue.installPlan.installPlan.length},actions:{assignErrorFromEvent:N({_internalState:(z)=>({...z.context._internalState,error:z.event.error})}),nextAppIndex:N({_internalState:(z)=>({...z.context._internalState,currentIndex:z.context._internalState.currentIndex+1})}),cleanupDeviceState:()=>{let z=q.getDeviceSessionState();z.sessionStateType!==m.Connected&&q.setDeviceSessionState({...z,installedApps:[],appsUpdates:void 0})}}}).createMachine({id:"InstallOrUpdateAppsDeviceAction",initial:"DeviceReady",context:(z)=>({input:{applications:z.input.applications,allowMissingApplication:z.input.allowMissingApplication,unlockTimeout:z.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:I$.UPDATE_DEVICE_METADATA,installPlan:null},_internalState:{error:null,osVersion:null,currentIndex:0}}),states:{DeviceReady:{always:[{target:"UpdateDeviceMetadata"}]},UpdateDeviceMetadata:{exit:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{id:"updateMetadata",src:"updateMetadata",input:(z)=>({unlockTimeout:z.context.input.unlockTimeout,useSecureChannel:!0,forceUpdate:!1}),onSnapshot:{actions:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:z.event.snapshot.context.intermediateValue.requiredUserInteraction,deviceId:z.event.snapshot.context.intermediateValue.deviceId??z.context.intermediateValue.deviceId})})},onDone:{target:"UpdateDeviceMetadataCheck",actions:N({_internalState:(z)=>z.event.output.caseOf({Right:(X)=>({...z.context._internalState,osVersion:X.firmwareVersion.metadata}),Left:(X)=>({...z.context._internalState,error:X})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},UpdateDeviceMetadataCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"hasInstallPlan"},{target:"BuildInstallPlan"}]},BuildInstallPlan:{invoke:{src:"buildInstallPlan",input:(z)=>({applications:z.context.input.applications,allowMissingApplication:z.context.input.allowMissingApplication}),onDone:{target:"BuildInstallPlanCheck",actions:N({_internalState:(z)=>("error"in z.event.output)?{...z.context._internalState,error:z.event.output.error}:z.context._internalState,intermediateValue:(z)=>("error"in z.event.output)?z.context.intermediateValue:{...z.context.intermediateValue,installPlan:{installPlan:z.event.output.installPlan,alreadyInstalled:z.event.output.alreadyInstalled,missingApplications:z.event.output.missingApplications,currentIndex:0,currentProgress:0}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},BuildInstallPlanCheck:{always:[{guard:"hasError",target:"Error"},{target:"PredictOutOfMemory",guard:"hasMoreApps"},{target:"Success"}]},PredictOutOfMemory:{invoke:{src:"predictOutOfMemory",input:(z)=>({installPlan:z.context.intermediateValue.installPlan.installPlan}),onDone:{target:"PredictOutOfMemoryCheck",actions:N({_internalState:(z)=>("error"in z.event.output)?{...z.context._internalState,error:z.event.output.error}:z.event.output.outOfMemory?{...z.context._internalState,error:new D1("Not enough memory for those applications")}:z.context._internalState})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},PredictOutOfMemoryCheck:{always:[{guard:"hasError",target:"Error"},{target:"GoToDashboard"}]},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(z)=>({unlockTimeout:z.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:z.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(z)=>z.event.output.caseOf({Right:()=>z.context._internalState,Left:(X)=>({...z.context._internalState,error:X})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"InstallApp",actions:"cleanupDeviceState"}]},InstallApp:{exit:N({intermediateValue:(z)=>({...z.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{id:"installApp",src:"installApp",input:(z)=>({osVersion:z.context._internalState.osVersion,application:z.context.intermediateValue.installPlan.installPlan[z.context._internalState.currentIndex]}),onSnapshot:{actions:N({intermediateValue:(z)=>{switch(z.event.snapshot.context?.type){case M.DeviceId:return{...z.context.intermediateValue,deviceId:z.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...z.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:{let X=q.getDeviceSessionState();return X.sessionStateType!==m.Connected&&q.setDeviceSessionState({...X,isSecureConnectionAllowed:!0}),{...z.context.intermediateValue,requiredUserInteraction:k.None}}case M.Progress:return{...z.context.intermediateValue,installPlan:{...z.context.intermediateValue.installPlan,currentIndex:z.context._internalState.currentIndex,currentProgress:z.event.snapshot.context.payload.progress}};default:return z.context.intermediateValue}},_internalState:(z)=>z.event.snapshot.context?.type===M.Error?{...z.context._internalState,error:z.event.snapshot.context.error.mapInstallDAErrors()}:z.context._internalState})},onDone:{target:"InstallAppCheck",actions:"nextAppIndex"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},InstallAppCheck:{always:[{target:"Error",guard:"hasError"},{target:"InstallApp",guard:"hasMoreApps"},{target:"UpdateDeviceMetadata"}]},Success:{type:"final"},Error:{type:"final"}},output:(z)=>{let{context:X}=z,{error:w}=X._internalState,{installPlan:F}=X.intermediateValue;return w?j(w):L({successfullyInstalled:F.installPlan,alreadyInstalled:F.alreadyInstalled,missingApplications:F.missingApplications})}})}extractDependencies(q){return{buildInstallPlan:(J)=>Promise.resolve(new eJ(q,{applications:J.input.applications,allowMissingApplication:J.input.allowMissingApplication}).run()),predictOutOfMemory:(J)=>Promise.resolve(new q5(q,{installPlan:J.input.installPlan}).run()),installApp:(J)=>{let{osVersion:Z,application:Q}=J.input,$=q.getSecureChannelService().installApp(Z,Q);return new c0(q,{connection:$}).run()}}}}var J5=Object.freeze({LIST_APPS:"os.listAppsWithMetadata.steps.listApps",FETCH_METADATA:"os.listAppsWithMetadata.steps.fetchMetadata",SAVE_SESSION:"os.listAppsWithMetadata.steps.saveSession"});class L$ extends a{makeStateMachine(q){let{getAppsByHash:J,setDeviceSessionState:Z,getDeviceSessionState:Q}=this.extractDependencies(q),$=this.input.unlockTimeout??t,W=new jq({input:{unlockTimeout:$}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:$},context:{},output:{}},actors:{listApps:W,getAppsByHash:d(J),updateDeviceSessionState:RJ(({input:Y,sendBack:z})=>{let{appsWithMetadata:X}=Y,w=X.filter((_)=>_!==null),F={...Q(),installedApps:w};try{Z(F),z({type:"done"})}catch(_){z({type:"error",error:_})}})},guards:{hasError:({context:Y})=>Y._internalState.error!==null,hasNoAppsInstalled:({context:Y})=>Y._internalState.apps.length===0},actions:{assignErrorFromEvent:N({_internalState:(Y)=>({...Y.context._internalState,error:Y.event.error})})}}).createMachine({id:"ListAppsWithMetadataDeviceAction",initial:"DeviceReady",context:(Y)=>({input:Y.input,_internalState:{error:null,apps:[],appsWithMetadata:[]},intermediateValue:{requiredUserInteraction:k.None,step:J5.LIST_APPS}}),states:{DeviceReady:{always:{target:"ListApps"}},ListApps:{invoke:{id:"listApps",src:"listApps",input:(Y)=>({unlockTimeout:Y.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(Y)=>Y.event.snapshot.context.intermediateValue})},onDone:{target:"ListAppsCheck",actions:N({intermediateValue:(Y)=>({requiredUserInteraction:k.None,step:J5.LIST_APPS}),_internalState:(Y)=>Y.event.output.caseOf({Right:(z)=>({...Y.context._internalState,apps:z}),Left:(z)=>({...Y.context._internalState,error:z})})})}}},ListAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"hasNoAppsInstalled",actions:N({_internalState:(Y)=>({...Y.context._internalState,appsWithMetadata:[]})})},{target:"FetchMetadata"}]},FetchMetadata:{invoke:{id:"getAppsByHash",src:"getAppsByHash",input:(Y)=>Y.context._internalState.apps,onDone:{target:"FetchMetadataCheck",actions:N({_internalState:(Y)=>Y.event.output.caseOf({Right:(z)=>({...Y.context._internalState,appsWithMetadata:z}),Left:(z)=>({...Y.context._internalState,error:z})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},FetchMetadataCheck:{always:[{target:"Error",guard:"hasError"},{target:"SaveSession"}]},SaveSession:{invoke:{src:"updateDeviceSessionState",input:(Y)=>({appsWithMetadata:Y.context._internalState.appsWithMetadata})},on:{done:{target:"Success"},error:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final"},Error:{type:"final"}},output:(Y)=>Y.context._internalState.error?j(Y.context._internalState.error):L(Y.context._internalState.appsWithMetadata)})}extractDependencies(q){return{getAppsByHash:({input:J})=>{let Z=J.reduce((Q,$)=>$.appFullHash?Q.concat($.appFullHash):Q,[]);return q.getManagerApiService().getAppsByHash(Z)},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}var A$=Object.freeze({GET_DEVICE_METADATA:"os.openAppWithDependencies.steps.getDeviceMetadata",INSTALL_OR_UPDATE_APPS:"os.openAppWithDependencies.steps.installOrUpdateApps",OPEN_APP:"os.openAppWithDependencies.steps.openApp"});class R$ extends a{makeStateMachine(q){let J=this.input.unlockTimeout??t,Z=new f1({input:{unlockTimeout:J,useSecureChannel:!0,forceUpdate:!1}}).makeStateMachine(q),Q=new P8({input:{unlockTimeout:J,applications:[...this.input.dependencies,this.input.application],allowMissingApplication:this.input.allowMissingApplication??!1}}).makeStateMachine(q),$=new M1({input:{unlockTimeout:J,appName:this.input.application.name}}).makeStateMachine(q);return i({types:{input:{unlockTimeout:J},context:{},output:{}},actors:{getMetadata:Z,installApps:Q,openApp:$},guards:{hasError:({context:W})=>W._internalState.error!==null},actions:{assignErrorFromEvent:N({_internalState:(W)=>({...W.context._internalState,error:W.event.error})})}}).createMachine({id:"OpenAppWithDependenciesDeviceAction",initial:"DeviceReady",context:(W)=>({input:{application:W.input.application,dependencies:W.input.dependencies,requireLatestFirmware:W.input.requireLatestFirmware,unlockTimeout:W.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None,step:A$.GET_DEVICE_METADATA,installPlan:null},_internalState:{error:null,deviceMetadata:null,installResult:null}}),states:{DeviceReady:{always:[{target:"GetDeviceMetadata"}]},GetDeviceMetadata:{exit:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{id:"getMetadata",src:"getMetadata",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout,useSecureChannel:!0,forceUpdate:!1}),onSnapshot:{actions:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:W.event.snapshot.context.intermediateValue.requiredUserInteraction,deviceId:W.event.snapshot.context.intermediateValue.deviceId??W.context.intermediateValue.deviceId})})},onDone:{target:"GetDeviceMetadataCheck",actions:N({_internalState:(W)=>W.event.output.caseOf({Right:(Y)=>W.context.input.requireLatestFirmware&&Y.firmwareUpdateContext.availableUpdate!==void 0?{...W.context._internalState,error:new i1("Firmware is not the latest version")}:{...W.context._internalState,deviceMetadata:Y},Left:(Y)=>({...W.context._internalState,error:Y})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceMetadataCheck:{always:[{target:"Error",guard:"hasError"},{target:"InstallDependencies"}]},InstallDependencies:{exit:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{src:"installApps",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout,applications:[...W.context.input.dependencies,W.context.input.application],allowMissingApplication:this.input.allowMissingApplication??!1}),onSnapshot:{actions:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:W.event.snapshot.context.intermediateValue.requiredUserInteraction,installPlan:W.event.snapshot.context.intermediateValue.installPlan,deviceId:W.event.snapshot.context.intermediateValue.deviceId??W.context.intermediateValue.deviceId})})},onDone:{target:"InstallDependenciesCheck",actions:N({_internalState:(W)=>W.event.output.caseOf({Right:(Y)=>({...W.context._internalState,installResult:Y}),Left:(Y)=>({...W.context._internalState,error:Y})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},InstallDependenciesCheck:{always:[{guard:"hasError",target:"Error"},{target:"OpenApp"}]},OpenApp:{exit:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:k.None})}),invoke:{src:"openApp",input:(W)=>({unlockTimeout:W.context.input.unlockTimeout,appName:W.context.input.application.name}),onSnapshot:{actions:N({intermediateValue:(W)=>({...W.context.intermediateValue,requiredUserInteraction:W.event.snapshot.context.intermediateValue.requiredUserInteraction,installPlan:null})})},onDone:{target:"OpenAppCheck",actions:N({_internalState:(W)=>W.event.output.caseOf({Right:()=>W.context._internalState,Left:(Y)=>({...W.context._internalState,error:Y})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},OpenAppCheck:{always:[{guard:"hasError",target:"Error"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(W)=>{let{context:Y}=W,{error:z,deviceMetadata:X,installResult:w}=Y._internalState;return z?j(z):L({deviceMetadata:X,installResult:w})}})}}var E8=Object.freeze({OPEN_APP:"os.sendCommandInApp.steps.openApp",SEND_COMMAND:"os.sendCommandInApp.steps.sendCommand"});class P$ extends a{makeStateMachine(q){let{sendCommand:J}=this.extractDependencies(q);return i({types:{input:{},context:{},output:{}},actors:{sendCommand:d(J),openAppStateMachine:new M1({input:{appName:this.input.appName}}).makeStateMachine(q)},guards:{skipOpenApp:()=>this.input.skipOpenApp,noInternalError:({context:Z})=>Z._internalState.error===null},actions:{assignErrorFromEvent:N({_internalState:(Z)=>({...Z.context._internalState,error:Z.event.error})})}}).createMachine({id:"SendCommandInAppDeviceAction",initial:"InitialState",context:({input:Z})=>({input:Z,intermediateValue:{requiredUserInteraction:k.None,step:E8.OPEN_APP},_internalState:{commandResponse:null,error:null}}),states:{InitialState:{always:[{target:"SendCommand",guard:"skipOpenApp"},"OpenAppDeviceAction"]},OpenAppDeviceAction:{invoke:{id:"openAppStateMachine",input:{appName:this.input.appName},src:"openAppStateMachine",onSnapshot:{actions:N({intermediateValue:(Z)=>Z.event.snapshot.context.intermediateValue})},onDone:{actions:N({_internalState:(Z)=>Z.event.output.caseOf({Right:()=>Z.context._internalState,Left:(Q)=>({...Z.context._internalState,error:Q})})}),target:"CheckOpenAppDeviceActionResult"}}},CheckOpenAppDeviceActionResult:{always:[{target:"SendCommand",guard:"noInternalError"},"Error"]},SendCommand:{entry:N({intermediateValue:{requiredUserInteraction:this.input.requiredUserInteraction,step:E8.SEND_COMMAND}}),exit:N({intermediateValue:{requiredUserInteraction:k.None,step:E8.SEND_COMMAND}}),invoke:{id:"sendCommand",src:"sendCommand",input:({context:Z})=>Z.input.command,onDone:{target:"SendCommandResultCheck",actions:[N({_internalState:({event:Z,context:Q})=>n(Z.output)?{...Q._internalState,commandResponse:Z.output.data}:{...Q._internalState,error:Z.output.error}})]},onError:{target:"Error",actions:"assignErrorFromEvent"}}},SendCommandResultCheck:{always:[{target:"Success",guard:"noInternalError"},"Error"]},Success:{type:"final"},Error:{type:"final"}},output:({context:Z})=>Z._internalState.commandResponse?L(Z._internalState.commandResponse):j(Z._internalState.error||new q0("No error in final state"))})}extractDependencies(q){return{sendCommand:(J)=>q.sendCommand(J.input)}}}var Lj=k1(O6(),1);var wj=k1(O6(),1);function K1(q,J){return Reflect.getOwnMetadata(J,q)}function F6(q,J,Z){Reflect.defineMetadata(J,Z,q)}function w1(q,J,Z,Q){let $=Q(K1(q,J)??Z());Reflect.defineMetadata(J,$,q)}function K0(q){return(typeof q=="object"&&q!==null||typeof q=="function")&&typeof q.then=="function"}function S0(q){switch(typeof q){case"string":case"symbol":return q.toString();case"function":return q.name;default:throw Error(`Unexpected ${typeof q} service id type`)}}var Z5=Symbol.for("@inversifyjs/common/islazyServiceIdentifier");class Aq{[Z5];#q;constructor(q){this.#q=q,this[Z5]=!0}static is(q){return typeof q=="object"&&q!==null&&q[Z5]===!0}unwrap(){return this.#q()}}var Q5="@inversifyjs/container/bindingId";function I1(){let q=K1(Object,Q5)??0;return q===Number.MAX_SAFE_INTEGER?F6(Object,Q5,Number.MIN_SAFE_INTEGER):w1(Object,Q5,()=>q,(J)=>J+1),q}var n0={Request:"Request",Singleton:"Singleton",Transient:"Transient"},_0={ConstantValue:"ConstantValue",DynamicValue:"DynamicValue",Factory:"Factory",Instance:"Instance",Provider:"Provider",ResolvedValue:"ResolvedValue",ServiceRedirection:"ServiceRedirection"};function*l$(...q){for(let J of q)yield*J}class G6{#q;#J;#$;constructor(q){this.#q=new Map,this.#J={};for(let J of Reflect.ownKeys(q))this.#J[J]=new Map;this.#$=q}add(q,J){this.#Z(q).push(J);for(let Z of Reflect.ownKeys(J))this.#Y(Z,J[Z]).push(q)}clone(){let q=Reflect.ownKeys(this.#$),J=new G6(this.#$);this.#z(this.#q,J.#q);for(let Z of q)this.#z(this.#J[Z],J.#J[Z]);return J}get(q,J){return this.#J[q].get(J)}getAllKeys(q){return this.#J[q].keys()}removeByRelation(q,J){let Z=this.get(q,J);if(Z===void 0)return;let Q=new Set(Z);for(let $ of Q){let W=this.#q.get($);if(W===void 0)throw Error("Expecting model relation, none found");for(let Y of W)Y[q]===J&&this.#W($,Y);this.#q.delete($)}}#Z(q){let J=this.#q.get(q);return J===void 0&&(J=[],this.#q.set(q,J)),J}#Y(q,J){let Z=this.#J[q].get(J);return Z===void 0&&(Z=[],this.#J[q].set(J,Z)),Z}#z(q,J){for(let[Z,Q]of q)J.set(Z,[...Q])}#W(q,J){for(let Z of Reflect.ownKeys(J))this.#Q(q,Z,J[Z])}#Q(q,J,Z){let Q=this.#J[J].get(Z);if(Q!==void 0){let $=Q.indexOf(q);$!==-1&&Q.splice($,1),Q.length===0&&this.#J[J].delete(Z)}}}var _6,q1,H6;(function(q){q.moduleId="moduleId",q.serviceId="serviceId"})(_6||(_6={}));class Eq{#q;#J;constructor(q,J){this.#q=J??new G6({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#J=q}static build(q){return new Eq(q)}add(q,J){this.#q.add(q,J)}clone(){return new Eq(this.#J,this.#q.clone())}get(q){let J=[],Z=this.#q.get(_6.serviceId,q);Z!==void 0&&J.push(Z);let Q=this.#J?.get(q);if(Q!==void 0&&J.push(Q),J.length!==0)return l$(...J)}removeAllByModuleId(q){this.#q.removeByRelation(_6.moduleId,q)}removeAllByServiceId(q){this.#q.removeByRelation(_6.serviceId,q)}}(function(q){q.id="id",q.moduleId="moduleId",q.serviceId="serviceId"})(q1||(q1={}));class xq{#q;#J;constructor(q,J){this.#q=J??new G6({id:{isOptional:!1},moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#J=q}static build(q){return new xq(q)}clone(){return new xq(this.#J,this.#q.clone())}get(q){return this.getNonParentBindings(q)??this.#J?.get(q)}getById(q){return this.#q.get(q1.id,q)??this.#J?.getById(q)}getByModuleId(q){return this.#q.get(q1.moduleId,q)??this.#J?.getByModuleId(q)}getNonParentBindings(q){return this.#q.get(q1.serviceId,q)}getNonParentBoundServices(){return this.#q.getAllKeys(q1.serviceId)}removeById(q){this.#q.removeByRelation(q1.id,q)}removeAllByModuleId(q){this.#q.removeByRelation(q1.moduleId,q)}removeAllByServiceId(q){this.#q.removeByRelation(q1.serviceId,q)}set(q){let J={[q1.id]:q.id,[q1.serviceId]:q.serviceIdentifier};q.moduleId!==void 0&&(J[q1.moduleId]=q.moduleId),this.#q.add(q,J)}}(function(q){q.moduleId="moduleId",q.serviceId="serviceId"})(H6||(H6={}));class kq{#q;#J;constructor(q,J){this.#q=J??new G6({moduleId:{isOptional:!0},serviceId:{isOptional:!1}}),this.#J=q}static build(q){return new kq(q)}add(q,J){this.#q.add(q,J)}clone(){return new kq(this.#J,this.#q.clone())}get(q){let J=[],Z=this.#q.get(H6.serviceId,q);Z!==void 0&&J.push(Z);let Q=this.#J?.get(q);if(Q!==void 0&&J.push(Q),J.length!==0)return l$(...J)}removeAllByModuleId(q){this.#q.removeByRelation(H6.moduleId,q)}removeAllByServiceId(q){this.#q.removeByRelation(H6.serviceId,q)}}var Rq="@inversifyjs/core/classMetadataReflectKey";function Pq(){return{constructorArguments:[],lifecycle:{postConstructMethodName:void 0,preDestroyMethodName:void 0},properties:new Map,scope:void 0}}var d$="@inversifyjs/core/pendingClassMetadataCountReflectKey",$5=Symbol.for("@inversifyjs/core/InversifyCoreError");class w0 extends Error{[$5];kind;constructor(q,J,Z){super(J,Z),this[$5]=!0,this.kind=q}static is(q){return typeof q=="object"&&q!==null&&q[$5]===!0}static isErrorOfKind(q,J){return w0.is(q)&&q.kind===J}}var X0,Oq,j1;function N6(q){let J=K1(q,Rq)??Pq();if(!function(Z){let Q=K1(Z,d$);return Q!==void 0&&Q!==0}(q))return function(Z,Q){let $=[];if(Q.length<Z.length)throw new w0(X0.missingInjectionDecorator,`Found unexpected missing metadata on type "${Z.name}". "${Z.name}" constructor requires at least ${Z.length.toString()} arguments, found ${Q.length.toString()} instead.
17
17
  Are you using @inject, @multiInject or @unmanaged decorators in every non optional constructor argument?
18
18
 
19
- If you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let W=0;W<Q.length;++W)Q[W]===void 0&&$.push(W);if($.length>0)throw new z0(w0.missingInjectionDecorator,`Found unexpected missing metadata on type "${Z.name}" at constructor indexes "${$.join('", "')}".
19
+ If you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`);for(let W=0;W<Q.length;++W)Q[W]===void 0&&$.push(W);if($.length>0)throw new w0(X0.missingInjectionDecorator,`Found unexpected missing metadata on type "${Z.name}" at constructor indexes "${$.join('", "')}".
20
20
 
21
21
  Are you using @inject, @multiInject or @unmanaged decorators at those indexes?
22
22
 
23
23
  If you're using typescript and want to rely on auto injection, set "emitDecoratorMetadata" compiler option to true`)}(q,J.constructorArguments),J;(function(Z,Q){let $=[];for(let W=0;W<Q.constructorArguments.length;++W){let Y=Q.constructorArguments[W];Y!==void 0&&Y.kind!==Oq.unknown||$.push(` - Missing or incomplete metadata for type "${Z.name}" at constructor argument with index ${W.toString()}.
24
24
  Every constructor parameter must be decorated either with @inject, @multiInject or @unmanaged decorator.`)}for(let[W,Y]of Q.properties)Y.kind===Oq.unknown&&$.push(` - Missing or incomplete metadata for type "${Z.name}" at property "${W.toString()}".
25
- This property must be decorated either with @inject or @multiInject decorator.`);if($.length===0)throw new z0(w0.unknown,`Unexpected class metadata for type "${Z.name}" with uncompletion traces.
25
+ This property must be decorated either with @inject or @multiInject decorator.`);if($.length===0)throw new w0(X0.unknown,`Unexpected class metadata for type "${Z.name}" with uncompletion traces.
26
26
  This might be caused by one of the following reasons:
27
27
 
28
28
  1. A third party library is targeting inversify reflection metadata.
29
- 2. A bug is causing the issue. Consider submiting an issue to fix it.`);throw new z0(w0.missingInjectionDecorator,`Invalid class metadata at type ${Z.name}:
29
+ 2. A bug is causing the issue. Consider submiting an issue to fix it.`);throw new w0(X0.missingInjectionDecorator,`Invalid class metadata at type ${Z.name}:
30
30
 
31
31
  ${$.join(`
32
32
 
33
- `)}`)})(q,J)}function Dw(){return 0}function Uw(q){return(J)=>{J!==void 0&&J.kind===Oq.unknown&&z1(q,g$,Dw,(Z)=>Z-1)}}function m$(q,J){return(...Z)=>(Q)=>{if(Q===void 0)return q(...Z);if(Q.kind===j1.unmanaged)throw new z0(w0.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found");return J(Q,...Z)}}function l$(q){if(q.kind!==Oq.unknown&&q.isFromTypescriptParamType!==!0)throw new z0(w0.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found")}(function(q){q[q.injectionDecoratorConflict=0]="injectionDecoratorConflict",q[q.missingInjectionDecorator=1]="missingInjectionDecorator",q[q.planning=2]="planning",q[q.resolution=3]="resolution",q[q.unknown=4]="unknown"})(w0||(w0={})),function(q){q[q.unknown=32]="unknown"}(Oq||(Oq={})),function(q){q[q.multipleInjection=0]="multipleInjection",q[q.singleInjection=1]="singleInjection",q[q.unmanaged=2]="unmanaged"}(j1||(j1={}));var Kw=m$(function(q,J){return{kind:q,name:void 0,optional:!1,tags:new Map,value:J}},function(q,J,Z){return l$(q),{...q,kind:J,value:Z}});function A$(q,J){return(Z)=>{let Q=Z.properties.get(J);return Z.properties.set(J,q(Q)),Z}}var S1;function jw(q,J,Z,Q){if(z0.isErrorOfKind(Q,w0.injectionDecoratorConflict)){let $=function(W,Y,z){if(z===void 0){if(Y===void 0)throw new z0(w0.unknown,"Unexpected undefined property and index values");return{kind:S1.property,property:Y,targetClass:W.constructor}}return typeof z=="number"?{index:z,kind:S1.parameter,targetClass:W}:{kind:S1.method,method:Y,targetClass:W}}(q,J,Z);throw new z0(w0.injectionDecoratorConflict,`Unexpected injection error.
33
+ `)}`)})(q,J)}function Iw(){return 0}function Lw(q){return(J)=>{J!==void 0&&J.kind===Oq.unknown&&w1(q,d$,Iw,(Z)=>Z-1)}}function c$(q,J){return(...Z)=>(Q)=>{if(Q===void 0)return q(...Z);if(Q.kind===j1.unmanaged)throw new w0(X0.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found");return J(Q,...Z)}}function p$(q){if(q.kind!==Oq.unknown&&q.isFromTypescriptParamType!==!0)throw new w0(X0.injectionDecoratorConflict,"Unexpected injection found. Multiple @inject, @multiInject or @unmanaged decorators found")}(function(q){q[q.injectionDecoratorConflict=0]="injectionDecoratorConflict",q[q.missingInjectionDecorator=1]="missingInjectionDecorator",q[q.planning=2]="planning",q[q.resolution=3]="resolution",q[q.unknown=4]="unknown"})(X0||(X0={})),function(q){q[q.unknown=32]="unknown"}(Oq||(Oq={})),function(q){q[q.multipleInjection=0]="multipleInjection",q[q.singleInjection=1]="singleInjection",q[q.unmanaged=2]="unmanaged"}(j1||(j1={}));var Aw=c$(function(q,J){return{kind:q,name:void 0,optional:!1,tags:new Map,value:J}},function(q,J,Z){return p$(q),{...q,kind:J,value:Z}});function E$(q,J){return(Z)=>{let Q=Z.properties.get(J);return Z.properties.set(J,q(Q)),Z}}var S1;function Rw(q,J,Z,Q){if(w0.isErrorOfKind(Q,X0.injectionDecoratorConflict)){let $=function(W,Y,z){if(z===void 0){if(Y===void 0)throw new w0(X0.unknown,"Unexpected undefined property and index values");return{kind:S1.property,property:Y,targetClass:W.constructor}}return typeof z=="number"?{index:z,kind:S1.parameter,targetClass:W}:{kind:S1.method,method:Y,targetClass:W}}(q,J,Z);throw new w0(X0.injectionDecoratorConflict,`Unexpected injection error.
34
34
 
35
35
  Cause:
36
36
 
@@ -38,27 +38,27 @@ ${Q.message}
38
38
 
39
39
  Details
40
40
 
41
- ${function(W){switch(W.kind){case S1.method:return`[class: "${W.targetClass.name}", method: "${W.method.toString()}"]`;case S1.parameter:return`[class: "${W.targetClass.name}", index: "${W.index.toString()}"]`;case S1.property:return`[class: "${W.targetClass.name}", property: "${W.property.toString()}"]`}}($)}`,{cause:Q})}throw Q}function Iw(q,J){return(Z,Q,$)=>{try{$===void 0?function(W,Y){let z=Q5(W,Y);return(X,w)=>{z1(X.constructor,Rq,Pq,A$(z(X),w))}}(q,J)(Z,Q):typeof $=="number"?function(W,Y){let z=Q5(W,Y);return(X,w,F)=>{if(!function(_,G){return typeof _=="function"&&G===void 0}(X,w))throw new z0(w0.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.
42
- Found @inject decorator at method "${w?.toString()??""}" at class "${X.constructor.name}"`);z1(X,Rq,Pq,function(_,G){return(B)=>{let A=B.constructorArguments[G];return B.constructorArguments[G]=_(A),B}}(z(X),F))}}(q,J)(Z,Q,$):function(W,Y){let z=Q5(W,Y);return(X,w,F)=>{if(!function(_){return _.set!==void 0}(F))throw new z0(w0.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.
43
- Found @inject decorator at method "${w.toString()}" at class "${X.constructor.name}"`);z1(X.constructor,Rq,Pq,A$(z(X),w))}}(q,J)(Z,Q,$)}catch(W){jw(Z,Q,$,W)}}}function Q5(q,J){return(Z)=>{let Q=J(Z);return($)=>(Q($),q($))}}function j(q){return Iw(Kw(j1.singleInjection,q),Uw)}(function(q){q[q.method=0]="method",q[q.parameter=1]="parameter",q[q.property=2]="property"})(S1||(S1={}));var R$="@inversifyjs/core/classIsInjectableFlagReflectKey",Lw=[Array,BigInt,Boolean,Function,Number,Object,String];function Aw(q){let J=K1(q,"design:paramtypes");J!==void 0&&z1(q,Rq,Pq,function(Z){return(Q)=>(Z.forEach(($,W)=>{var Y;Q.constructorArguments[W]!==void 0||(Y=$,Lw.includes(Y))||(Q.constructorArguments[W]=function(z){return{isFromTypescriptParamType:!0,kind:j1.singleInjection,name:void 0,optional:!1,tags:new Map,value:z}}($))}),Q)}(J))}function R(q){return(J)=>{(function(Z){if(K1(Z,R$)!==void 0)throw new z0(w0.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${Z.name}"`);F6(Z,R$,!0)})(J),Aw(J),q!==void 0&&z1(J,Rq,Pq,(Z)=>({...Z,scope:q}))}}function P$(){return{kind:j1.unmanaged}}var oK=m$(P$,function(q){if(l$(q),function(J){return J.name!==void 0||J.optional||J.tags.size>0}(q))throw new z0(w0.injectionDecoratorConflict,"Unexpected injection found. Found @unmanaged injection with additional @named, @optional, @tagged or @targetName injections");return P$()});var qq;(function(q){q[q.multipleInjection=0]="multipleInjection",q[q.singleInjection=1]="singleInjection"})(qq||(qq={}));class Cq{#q;constructor(q){this.#q=q}get name(){return this.#q.elem.name}get serviceIdentifier(){return this.#q.elem.serviceIdentifier}get tags(){return this.#q.elem.tags}getAncestor(){if(this.#q.previous!==void 0)return new Cq(this.#q.previous)}}class W5{last;constructor(q){this.last=q}concat(q){return new W5({elem:q,previous:this.last})}[Symbol.iterator](){let q=this.last;return{next:()=>{if(q===void 0)return{done:!0,value:void 0};let J=q.elem;return q=q.previous,{done:!1,value:J}}}}}function k8(q,J,Z){let Q=Z?.customServiceIdentifier??J.serviceIdentifier,$=[...q.getBindings(Q)??[]].filter((W)=>W.isSatisfiedBy(J));if($.length===0&&q.autobindOptions!==void 0&&typeof Q=="function"){let W=function(Y,z){let X=N6(z),w=X.scope??Y.scope;return{cache:{isRight:!1,value:void 0},id:I1(),implementationType:z,isSatisfiedBy:()=>!0,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:w,serviceIdentifier:z,type:F0.Instance}}(q.autobindOptions,Q);q.setBinding(W),$.push(W)}return $}function Jq(q){return q.redirections!==void 0}function d$(q,J,Z,Q){let $,W;Jq(Z)?($=Z.binding.targetServiceIdentifier,W=Z.binding.serviceIdentifier):($=Z.serviceIdentifier,W=Z.parent?.binding.serviceIdentifier),Array.isArray(q)?function(Y,z,X,w,F){if(Y.length!==0){let _=`Ambiguous bindings found for service: "${f0(X)}".
41
+ ${function(W){switch(W.kind){case S1.method:return`[class: "${W.targetClass.name}", method: "${W.method.toString()}"]`;case S1.parameter:return`[class: "${W.targetClass.name}", index: "${W.index.toString()}"]`;case S1.property:return`[class: "${W.targetClass.name}", property: "${W.property.toString()}"]`}}($)}`,{cause:Q})}throw Q}function Pw(q,J){return(Z,Q,$)=>{try{$===void 0?function(W,Y){let z=W5(W,Y);return(X,w)=>{w1(X.constructor,Rq,Pq,E$(z(X),w))}}(q,J)(Z,Q):typeof $=="number"?function(W,Y){let z=W5(W,Y);return(X,w,F)=>{if(!function(_,G){return typeof _=="function"&&G===void 0}(X,w))throw new w0(X0.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.
42
+ Found @inject decorator at method "${w?.toString()??""}" at class "${X.constructor.name}"`);w1(X,Rq,Pq,function(_,G){return(B)=>{let R=B.constructorArguments[G];return B.constructorArguments[G]=_(R),B}}(z(X),F))}}(q,J)(Z,Q,$):function(W,Y){let z=W5(W,Y);return(X,w,F)=>{if(!function(_){return _.set!==void 0}(F))throw new w0(X0.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.
43
+ Found @inject decorator at method "${w.toString()}" at class "${X.constructor.name}"`);w1(X.constructor,Rq,Pq,E$(z(X),w))}}(q,J)(Z,Q,$)}catch(W){Rw(Z,Q,$,W)}}}function W5(q,J){return(Z)=>{let Q=J(Z);return($)=>(Q($),q($))}}function U(q){return Pw(Aw(j1.singleInjection,q),Lw)}(function(q){q[q.method=0]="method",q[q.parameter=1]="parameter",q[q.property=2]="property"})(S1||(S1={}));var x$="@inversifyjs/core/classIsInjectableFlagReflectKey",Ew=[Array,BigInt,Boolean,Function,Number,Object,String];function xw(q){let J=K1(q,"design:paramtypes");J!==void 0&&w1(q,Rq,Pq,function(Z){return(Q)=>(Z.forEach(($,W)=>{var Y;Q.constructorArguments[W]!==void 0||(Y=$,Ew.includes(Y))||(Q.constructorArguments[W]=function(z){return{isFromTypescriptParamType:!0,kind:j1.singleInjection,name:void 0,optional:!1,tags:new Map,value:z}}($))}),Q)}(J))}function I(q){return(J)=>{(function(Z){if(K1(Z,x$)!==void 0)throw new w0(X0.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${Z.name}"`);F6(Z,x$,!0)})(J),xw(J),q!==void 0&&w1(J,Rq,Pq,(Z)=>({...Z,scope:q}))}}function k$(){return{kind:j1.unmanaged}}var Yj=c$(k$,function(q){if(p$(q),function(J){return J.name!==void 0||J.optional||J.tags.size>0}(q))throw new w0(X0.injectionDecoratorConflict,"Unexpected injection found. Found @unmanaged injection with additional @named, @optional, @tagged or @targetName injections");return k$()});var qq;(function(q){q[q.multipleInjection=0]="multipleInjection",q[q.singleInjection=1]="singleInjection"})(qq||(qq={}));class Cq{#q;constructor(q){this.#q=q}get name(){return this.#q.elem.name}get serviceIdentifier(){return this.#q.elem.serviceIdentifier}get tags(){return this.#q.elem.tags}getAncestor(){if(this.#q.previous!==void 0)return new Cq(this.#q.previous)}}class z5{last;constructor(q){this.last=q}concat(q){return new z5({elem:q,previous:this.last})}[Symbol.iterator](){let q=this.last;return{next:()=>{if(q===void 0)return{done:!0,value:void 0};let J=q.elem;return q=q.previous,{done:!1,value:J}}}}}function k8(q,J,Z){let Q=Z?.customServiceIdentifier??J.serviceIdentifier,$=[...q.getBindings(Q)??[]].filter((W)=>W.isSatisfiedBy(J));if($.length===0&&q.autobindOptions!==void 0&&typeof Q=="function"){let W=function(Y,z){let X=N6(z),w=X.scope??Y.scope;return{cache:{isRight:!1,value:void 0},id:I1(),implementationType:z,isSatisfiedBy:()=>!0,moduleId:void 0,onActivation:void 0,onDeactivation:void 0,scope:w,serviceIdentifier:z,type:_0.Instance}}(q.autobindOptions,Q);q.setBinding(W),$.push(W)}return $}function Jq(q){return q.redirections!==void 0}function s$(q,J,Z,Q){let $,W;Jq(Z)?($=Z.binding.targetServiceIdentifier,W=Z.binding.serviceIdentifier):($=Z.serviceIdentifier,W=Z.parent?.binding.serviceIdentifier),Array.isArray(q)?function(Y,z,X,w,F){if(Y.length!==0){let _=`Ambiguous bindings found for service: "${S0(X)}".
44
44
 
45
45
  Registered bindings:
46
46
 
47
- ${Y.map((G)=>function(B){switch(B.type){case F0.Instance:return`[ type: "${B.type}", serviceIdentifier: "${f0(B.serviceIdentifier)}", scope: "${B.scope}", implementationType: "${B.implementationType.name}" ]`;case F0.ServiceRedirection:return`[ type: "${B.type}", serviceIdentifier: "${f0(B.serviceIdentifier)}", redirection: "${f0(B.targetServiceIdentifier)}" ]`;default:return`[ type: "${B.type}", serviceIdentifier: "${f0(B.serviceIdentifier)}", scope: "${B.scope}" ]`}}(G.binding)).join(`
47
+ ${Y.map((G)=>function(B){switch(B.type){case _0.Instance:return`[ type: "${B.type}", serviceIdentifier: "${S0(B.serviceIdentifier)}", scope: "${B.scope}", implementationType: "${B.implementationType.name}" ]`;case _0.ServiceRedirection:return`[ type: "${B.type}", serviceIdentifier: "${S0(B.serviceIdentifier)}", redirection: "${S0(B.targetServiceIdentifier)}" ]`;default:return`[ type: "${B.type}", serviceIdentifier: "${S0(B.serviceIdentifier)}", scope: "${B.scope}" ]`}}(G.binding)).join(`
48
48
  `)}
49
49
 
50
- Trying to resolve bindings for "${c$(X,w)}".
50
+ Trying to resolve bindings for "${n$(X,w)}".
51
51
 
52
- ${p$(F)}`;throw new z0(w0.planning,_)}z||E$(X,w,F)}(q,J,$,W,Q):function(Y,z,X,w,F){if(Y!==void 0||z)return;E$(X,w,F)}(q,J,$,W,Q)}function E$(q,J,Z){let Q=`No bindings found for service: "${f0(q)}".
52
+ ${i$(F)}`;throw new w0(X0.planning,_)}z||O$(X,w,F)}(q,J,$,W,Q):function(Y,z,X,w,F){if(Y!==void 0||z)return;O$(X,w,F)}(q,J,$,W,Q)}function O$(q,J,Z){let Q=`No bindings found for service: "${S0(q)}".
53
53
 
54
- Trying to resolve bindings for "${c$(q,J)}".
54
+ Trying to resolve bindings for "${n$(q,J)}".
55
55
 
56
- ${p$(Z)}`;throw new z0(w0.planning,Q)}function c$(q,J){return J===void 0?`${f0(q)} (Root service)`:f0(J)}function p$(q){let J=q.tags.size===0?"":`
56
+ ${i$(Z)}`;throw new w0(X0.planning,Q)}function n$(q,J){return J===void 0?`${S0(q)} (Root service)`:S0(J)}function i$(q){let J=q.tags.size===0?"":`
57
57
  - tags:
58
58
  - ${[...q.tags.keys()].map((Z)=>Z.toString()).join(`
59
59
  - `)}`;return`Binding constraints:
60
- - service identifier: ${f0(q.serviceIdentifier)}
61
- - name: ${q.name?.toString()??"-"}${J}`}function s$(q,J,Z){if(q.redirections.length!==1)d$(q.redirections,J,q,Z);else{let[Q]=q.redirections;Jq(Q)&&s$(Q,J,Z)}}function Y5(q,J,Z){if(Array.isArray(q.bindings)&&q.bindings.length===1){let[Q]=q.bindings;Jq(Q)&&s$(Q,J,Z)}else d$(q.bindings,J,q,Z)}function Rw(q,J){if(function(Z){return Z instanceof Error&&(Z instanceof RangeError&&/stack space|call stack|too much recursion/i.test(Z.message)||Z.name==="InternalError"&&/too much recursion/.test(Z.message))}(J)){let Z=function(Q){let $=[...Q];if($.length===0)return"(No dependency trace)";return $.map(f0).join(" -> ")}(function(Q){let $=new Set;for(let W of Q.servicesBranch){if($.has(W))return[...$,W];$.add(W)}return[...$]}(q));throw new z0(w0.planning,`Circular dependency found: ${Z}`,{cause:J})}throw J}function n$(q){try{let J=new Map;q.rootConstraints.tag!==void 0&&J.set(q.rootConstraints.tag.key,q.rootConstraints.tag.value);let Z=new W5({elem:{name:q.rootConstraints.name,serviceIdentifier:q.rootConstraints.serviceIdentifier,tags:J},previous:void 0}),Q=new Cq(Z.last),$=k8(q,Q),W=[],Y={bindings:W,parent:void 0,serviceIdentifier:q.rootConstraints.serviceIdentifier};if(W.push(...O8(q,Z,$,Y)),!q.rootConstraints.isMultiple){Y5(Y,q.rootConstraints.isOptional??!1,Q);let[z]=W;Y.bindings=z}return{tree:{root:Y}}}catch(J){Rw(q,J)}}function Pw(q,J,Z,Q){let $={binding:J,classMetadata:q.getClassMetadata(J.implementationType),constructorParams:[],parent:Q,propertyParams:new Map};return i$({autobindOptions:q.autobindOptions,getBindings:q.getBindings,getClassMetadata:q.getClassMetadata,node:$,servicesBranch:q.servicesBranch,setBinding:q.setBinding},Z)}function x$(q,J,Z){if(Z.kind===j1.unmanaged)return;let Q=Aq.is(Z.value)?Z.value.unwrap():Z.value,$=J.concat({name:Z.name,serviceIdentifier:Q,tags:Z.tags}),W=new Cq($.last),Y=k8(q,W),z=[],X={bindings:z,parent:q.node,serviceIdentifier:Q};if(z.push(...O8(q,$,Y,X)),Z.kind===j1.singleInjection){Y5(X,Z.optional,W);let[w]=z;X.bindings=w}return X}function Ew(q,J,Z){let Q=Aq.is(Z.value)?Z.value.unwrap():Z.value,$=J.concat({name:Z.name,serviceIdentifier:Q,tags:Z.tags}),W=new Cq($.last),Y=k8(q,W),z=[],X={bindings:z,parent:q.node,serviceIdentifier:Q};if(z.push(...O8(q,$,Y,X)),Z.kind===qq.singleInjection){Y5(X,Z.optional,W);let[w]=z;X.bindings=w}return X}function xw(q,J,Z,Q){let $={binding:J,params:[],parent:Q};return i$({autobindOptions:q.autobindOptions,getBindings:q.getBindings,getClassMetadata:q.getClassMetadata,node:$,servicesBranch:q.servicesBranch,setBinding:q.setBinding},Z)}function O8(q,J,Z,Q){let $=Jq(Q)?Q.binding.targetServiceIdentifier:Q.serviceIdentifier;q.servicesBranch.push($);let W=[];for(let Y of Z)switch(Y.type){case F0.Instance:W.push(Pw(q,Y,J,Q));break;case F0.ResolvedValue:W.push(xw(q,Y,J,Q));break;case F0.ServiceRedirection:{let z=kw(q,J,Y,Q);W.push(z);break}default:W.push({binding:Y,parent:Q})}return q.servicesBranch.pop(),W}function kw(q,J,Z,Q){let $={binding:Z,parent:Q,redirections:[]},W=k8(q,new Cq(J.last),{customServiceIdentifier:Z.targetServiceIdentifier});return $.redirections.push(...O8(q,J,W,$)),$}function i$(q,J){return q.node.binding.type===F0.Instance?function(Z,Q,$){let W=Q.classMetadata;for(let[Y,z]of W.constructorArguments.entries())Q.constructorParams[Y]=x$(Z,$,z);for(let[Y,z]of W.properties){let X=x$(Z,$,z);X!==void 0&&Q.propertyParams.set(Y,X)}return Z.node}(q,q.node,J):function(Z,Q,$){let W=Q.binding.metadata;for(let[Y,z]of W.arguments.entries())Q.params[Y]=Ew(Z,$,z);return Z.node}(q,q.node,J)}var e1;(function(q){q[q.singleMandatory=0]="singleMandatory",q[q.singleOptional=1]="singleOptional",q[q.multipleMandatory=2]="multipleMandatory",q[q.multipleOptional=3]="multipleOptional",q[q.length=4]="length"})(e1||(e1={}));class z5{#q;#J;#$;#Z;#Y;constructor(){this.#q=this.#z(),this.#J=this.#z(),this.#Z=this.#z(),this.#$=this.#z(),this.#Y=[]}clearCache(){for(let q of this.#w())q.clear();for(let q of this.#Y)q.clearCache()}get(q){return q.name===void 0?q.tag===void 0?this.#Q(this.#q,q).get(q.serviceIdentifier):this.#Q(this.#$,q).get(q.serviceIdentifier)?.get(q.tag.key)?.get(q.tag.value):q.tag===void 0?this.#Q(this.#J,q).get(q.serviceIdentifier)?.get(q.name):this.#Q(this.#Z,q).get(q.serviceIdentifier)?.get(q.name)?.get(q.tag.key)?.get(q.tag.value)}set(q,J){q.name===void 0?q.tag===void 0?this.#Q(this.#q,q).set(q.serviceIdentifier,J):this.#W(this.#W(this.#Q(this.#$,q),q.serviceIdentifier),q.tag.key).set(q.tag.value,J):q.tag===void 0?this.#W(this.#Q(this.#J,q),q.serviceIdentifier).set(q.name,J):this.#W(this.#W(this.#W(this.#Q(this.#Z,q),q.serviceIdentifier),q.name),q.tag.key).set(q.tag.value,J)}subscribe(q){this.#Y.push(q)}#z(){let q=Array(e1.length);for(let J=0;J<q.length;++J)q[J]=new Map;return q}#W(q,J){let Z=q.get(J);return Z===void 0&&(Z=new Map,q.set(J,Z)),Z}#Q(q,J){return q[this.#X(J)]}#w(){return[...this.#q,...this.#J,...this.#Z,...this.#$]}#X(q){return q.isMultiple?q.optional===!0?e1.multipleOptional:e1.multipleMandatory:q.optional===!0?e1.singleOptional:e1.singleMandatory}}function a$(q,J){return U0(J)?(q.cache={isRight:!0,value:J},J.then((Z)=>k$(q,Z))):k$(q,J)}function k$(q,J){return q.cache={isRight:!0,value:J},J}function Ow(q,J,Z){let Q=q.getActivations(J);return Q===void 0?Z:U0(Z)?O$(q,Z,Q[Symbol.iterator]()):function($,W,Y){let z=W,X=Y.next();for(;X.done!==!0;){let w=X.value($.context,z);if(U0(w))return O$($,w,Y);z=w,X=Y.next()}return z}(q,Z,Q[Symbol.iterator]())}async function O$(q,J,Z){let Q=await J,$=Z.next();for(;$.done!==!0;)Q=await $.value(q.context,Q),$=Z.next();return Q}function x8(q,J,Z){let Q=Z;if(J.onActivation!==void 0){let $=J.onActivation;Q=U0(Q)?Q.then((W)=>$(q.context,W)):$(q.context,Q)}return Ow(q,J.serviceIdentifier,Q)}function w5(q){return(J,Z)=>{if(Z.cache.isRight)return Z.cache.value;return a$(Z,x8(J,Z,q(J,Z)))}}var Cw=w5(function(q,J){return J.value});function bw(q){return q}function X5(q,J){return(Z,Q)=>{let $=q(Q);switch($.scope){case s0.Singleton:if($.cache.isRight)return $.cache.value;return a$($,x8(Z,$,J(Z,Q)));case s0.Request:{if(Z.requestScopeCache.has($.id))return Z.requestScopeCache.get($.id);let W=x8(Z,$,J(Z,Q));return Z.requestScopeCache.set($.id,W),W}case s0.Transient:return x8(Z,$,J(Z,Q))}}}var Tw=((q)=>X5(bw,q))(function(q,J){return J.value(q.context)}),Mw=w5(function(q,J){return J.factory(q.context)});function C$(q,J,Z){let Q=function($,W,Y){if(Y===void 0)return;if(!(Y in $))throw new z0(w0.resolution,`Expecting a "${Y.toString()}" property when resolving "${W.implementationType.name}" class @postConstruct decorated method, none found.`);if(typeof $[Y]!="function")throw new z0(w0.resolution,`Expecting a "${Y.toString()}" method when resolving "${W.implementationType.name}" class @postConstruct decorated method, a non function property was found instead.`);{let z;try{z=$[Y]()}catch(X){throw new z0(w0.resolution,`Unexpected error found when calling "${Y.toString()}" @postConstruct decorated method on class "${W.implementationType.name}"`,{cause:X})}if(U0(z))return async function(X,w,F){try{await F}catch(_){throw new z0(w0.resolution,`Unexpected error found when calling "${w.toString()}" @postConstruct decorated method on class "${X.implementationType.name}"`,{cause:_})}}(W,Y,z)}}(q,J,Z);return U0(Q)?Q.then(()=>q):q}function b$(q){return(J,Z,Q)=>{let $=new Q.binding.implementationType(...J),W=q(Z,$,Q);return U0(W)?W.then(()=>C$($,Q.binding,Q.classMetadata.lifecycle.postConstructMethodName)):C$($,Q.binding,Q.classMetadata.lifecycle.postConstructMethodName)}}var fw=w5(function(q,J){return J.provider(q.context)});function Sw(q){return q.binding}function hw(q){return q.binding}var T$=function(q){return(J,Z,Q)=>{let $=[];for(let[W,Y]of Q.propertyParams){let z=Q.classMetadata.properties.get(W);if(z===void 0)throw new z0(w0.resolution,`Expecting metadata at property "${W.toString()}", none found`);z.kind!==j1.unmanaged&&Y.bindings!==void 0&&(Z[W]=q(J,Y),U0(Z[W])&&$.push((async()=>{Z[W]=await Z[W]})()))}if($.length>0)return Promise.all($).then(()=>{})}}(C8),M$=function(q){return function J(Z,Q){let $=[];for(let W of Q.redirections)Jq(W)?$.push(...J(Z,W)):$.push(q(Z,W));return $}}($5),vw=function(q,J,Z){return(Q,$)=>{let W=q(Q,$);return U0(W)?J(W,Q,$):Z(W,Q,$)}}(function(q){return(J,Z)=>{let Q=[];for(let $ of Z.constructorParams)$===void 0?Q.push(void 0):Q.push(q(J,$));return Q.some(U0)?Promise.all(Q):Q}}(C8),function(q){return async(J,Z,Q)=>{let $=await J;return q($,Z,Q)}}(b$(T$)),b$(T$)),yw=function(q){return(J,Z)=>{let Q=q(J,Z);return U0(Q)?Q.then(($)=>Z.binding.factory(...$)):Z.binding.factory(...Q)}}(function(q){return(J,Z)=>{let Q=[];for(let $ of Z.params)Q.push(q(J,$));return Q.some(U0)?Promise.all(Q):Q}}(C8)),uw=((q)=>X5(Sw,q))(vw),gw=((q)=>X5(hw,q))(yw);function o$(q){return C8(q,q.planResult.tree.root)}function $5(q,J){switch(J.binding.type){case F0.ConstantValue:return Cw(q,J.binding);case F0.DynamicValue:return Tw(q,J.binding);case F0.Factory:return Mw(q,J.binding);case F0.Instance:return uw(q,J);case F0.Provider:return fw(q,J.binding);case F0.ResolvedValue:return gw(q,J)}}function C8(q,J){if(J.bindings!==void 0)return Array.isArray(J.bindings)?function(Z,Q){let $=[];for(let W of Q)Jq(W)?$.push(...M$(Z,W)):$.push($5(Z,W));if($.some(U0))return Promise.all($);return $}(q,J.bindings):function(Z,Q){if(Jq(Q)){let $=M$(Z,Q);if($.length===1)return $[0];throw new z0(w0.resolution,"Unexpected multiple resolved values on single injection")}return $5(Z,Q)}(q,J.bindings)}function mw(q){return q.scope!==void 0}function f$(q,J){if(q.lifecycle.preDestroyMethodName!==void 0&&typeof J[q.lifecycle.preDestroyMethodName]=="function")return J[q.lifecycle.preDestroyMethodName]()}function S$(q,J,Z){let Q=q.getDeactivations(J);if(Q!==void 0)return U0(Z)?h$(Z,Q[Symbol.iterator]()):function($,W){let Y=W.next();for(;Y.done!==!0;){let z=Y.value($);if(U0(z))return h$($,W);Y=W.next()}}(Z,Q[Symbol.iterator]())}async function h$(q,J){let Z=await q,Q=J.next();for(;Q.done!==!0;)await Q.value(Z),Q=J.next()}function lw(q,J){let Z=function(Q,$){if($.type===F0.Instance){let W=Q.getClassMetadata($.implementationType),Y=$.cache.value;return U0(Y)?Y.then((z)=>f$(W,z)):f$(W,Y)}}(q,J);return Z===void 0?v$(q,J):Z.then(()=>v$(q,J))}function v$(q,J){let Z=J.cache;return U0(Z.value)?Z.value.then((Q)=>y$(q,J,Q)):y$(q,J,Z.value)}function y$(q,J,Z){let Q;if(J.onDeactivation!==void 0)Q=(0,J.onDeactivation)(Z);return Q===void 0?S$(q,J.serviceIdentifier,Z):Q.then(()=>S$(q,J.serviceIdentifier,Z))}function b8(q,J){if(J===void 0)return;let Z=function($){let W=[];for(let Y of $)mw(Y)&&Y.scope===s0.Singleton&&Y.cache.isRight&&W.push(Y);return W}(J),Q=[];for(let $ of Z){let W=lw(q,$);W!==void 0&&Q.push(W)}return Q.length>0?Promise.all(Q).then(()=>{}):void 0}function r$(q,J){let Z=q.getBindingsFromModule(J);return b8(q,Z)}function F5(q,J){let Z=q.getBindings(J);return b8(q,Z)}var _5="@inversifyjs/container/bindingId";class X0{#q;#J;constructor(q){this.#q=function(){let J=K1(Object,_5)??0;return J===Number.MAX_SAFE_INTEGER?F6(Object,_5,Number.MIN_SAFE_INTEGER):z1(Object,_5,()=>J,(Z)=>Z+1),J}(),this.#J=q}get id(){return this.#q}load(q){return this.#J(q)}}var e$=Symbol.for("@inversifyjs/container/bindingIdentifier");function t$(q){return typeof q=="object"&&q!==null&&q[e$]===!0}class h1{static always=(q)=>!0}function N5(q){return{[e$]:!0,id:q.id}}function D6(q){return(J)=>{for(let Z=J.getAncestor();Z!==void 0;Z=Z.getAncestor())if(q(Z))return!0;return!1}}function V6(q){return(J)=>J.name===q}function T8(q){return(J)=>J.serviceIdentifier===q}function B6(q,J){return(Z)=>Z.tags.has(q)&&Z.tags.get(q)===J}function dw(q){return q.name===void 0&&q.tags.size===0}function M8(q){let J=D6(q);return(Z)=>!J(Z)}function f8(q){return(J)=>{let Z=J.getAncestor();return Z===void 0||!q(Z)}}function S8(q){return(J)=>{let Z=J.getAncestor();return Z!==void 0&&q(Z)}}class qW{#q;constructor(q){this.#q=q}getIdentifier(){return N5(this.#q)}inRequestScope(){return this.#q.scope=s0.Request,new u1(this.#q)}inSingletonScope(){return this.#q.scope=s0.Singleton,new u1(this.#q)}inTransientScope(){return this.#q.scope=s0.Transient,new u1(this.#q)}}class G5{#q;#J;#$;#Z;constructor(q,J,Z,Q){this.#q=q,this.#J=J,this.#$=Z,this.#Z=Q}to(q){let J=N6(q),Z={cache:{isRight:!1,value:void 0},id:I1(),implementationType:q,isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:J.scope??this.#$,serviceIdentifier:this.#Z,type:F0.Instance};return this.#q(Z),new h8(Z)}toSelf(){if(typeof this.#Z!="function")throw Error('"toSelf" function can only be applied when a newable function is used as service identifier');return this.to(this.#Z)}toConstantValue(q){let J={cache:{isRight:!1,value:void 0},id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:s0.Singleton,serviceIdentifier:this.#Z,type:F0.ConstantValue,value:q};return this.#q(J),new u1(J)}toDynamicValue(q){let J={cache:{isRight:!1,value:void 0},id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:this.#$,serviceIdentifier:this.#Z,type:F0.DynamicValue,value:q};return this.#q(J),new h8(J)}toResolvedValue(q,J){let Z={cache:{isRight:!1,value:void 0},factory:q,id:I1(),isSatisfiedBy:h1.always,metadata:this.#Y(J),moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:this.#$,serviceIdentifier:this.#Z,type:F0.ResolvedValue};return this.#q(Z),new h8(Z)}toFactory(q){let J={cache:{isRight:!1,value:void 0},factory:q,id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:s0.Singleton,serviceIdentifier:this.#Z,type:F0.Factory};return this.#q(J),new u1(J)}toProvider(q){let J={cache:{isRight:!1,value:void 0},id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,provider:q,scope:s0.Singleton,serviceIdentifier:this.#Z,type:F0.Provider};return this.#q(J),new u1(J)}toService(q){let J={id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,serviceIdentifier:this.#Z,targetServiceIdentifier:q,type:F0.ServiceRedirection};this.#q(J)}#Y(q){return{arguments:(q??[]).map((J)=>function(Z){return typeof Z=="object"&&!Aq.is(Z)}(J)?{kind:J.isMultiple===!0?qq.multipleInjection:qq.singleInjection,name:J.name,optional:J.optional??!1,tags:new Map((J.tags??[]).map((Z)=>[Z.key,Z.value])),value:J.serviceIdentifier}:{kind:qq.singleInjection,name:void 0,optional:!1,tags:new Map,value:J})}}}class V5{#q;constructor(q){this.#q=q}getIdentifier(){return N5(this.#q)}onActivation(q){return this.#q.onActivation=q,new v8(this.#q)}onDeactivation(q){return this.#q.onDeactivation=q,new v8(this.#q)}}class v8{#q;constructor(q){this.#q=q}getIdentifier(){return N5(this.#q)}when(q){return this.#q.isSatisfiedBy=q,new V5(this.#q)}whenAnyAncestor(q){return this.when(D6(q))}whenAnyAncestorIs(q){return this.when(D6(T8(q)))}whenAnyAncestorNamed(q){return this.when(function(J){return D6(V6(J))}(q))}whenAnyAncestorTagged(q,J){return this.when(function(Z,Q){return D6(B6(Z,Q))}(q,J))}whenDefault(){return this.when(dw)}whenNamed(q){return this.when(V6(q))}whenNoParent(q){return this.when(f8(q))}whenNoParentIs(q){return this.when(f8(T8(q)))}whenNoParentNamed(q){return this.when(function(J){return f8(V6(J))}(q))}whenNoParentTagged(q,J){return this.when(function(Z,Q){return f8(B6(Z,Q))}(q,J))}whenParent(q){return this.when(S8(q))}whenParentIs(q){return this.when(S8(T8(q)))}whenParentNamed(q){return this.when(function(J){return S8(V6(J))}(q))}whenParentTagged(q,J){return this.when(function(Z,Q){return S8(B6(Z,Q))}(q,J))}whenTagged(q,J){return this.when(B6(q,J))}whenNoAncestor(q){return this.when(M8(q))}whenNoAncestorIs(q){return this.when(M8(T8(q)))}whenNoAncestorNamed(q){return this.when(function(J){return M8(V6(J))}(q))}whenNoAncestorTagged(q,J){return this.when(function(Z,Q){return M8(B6(Z,Q))}(q,J))}}class u1 extends v8{#q;constructor(q){super(q),this.#q=new V5(q)}onActivation(q){return this.#q.onActivation(q)}onDeactivation(q){return this.#q.onDeactivation(q)}}class h8 extends u1{#q;constructor(q){super(q),this.#q=new qW(q)}inRequestScope(){return this.#q.inRequestScope()}inSingletonScope(){return this.#q.inSingletonScope()}inTransientScope(){return this.#q.inTransientScope()}}var H5=Symbol.for("@inversifyjs/container/InversifyContainerError");class v1 extends Error{[H5];kind;constructor(q,J,Z){super(J,Z),this[H5]=!0,this.kind=q}static is(q){return typeof q=="object"&&q!==null&&q[H5]===!0}static isErrorOfKind(q,J){return v1.is(q)&&q.kind===J}}var y1;(function(q){q[q.invalidOperation=0]="invalidOperation"})(y1||(y1={}));var cw=s0.Transient;class y8{#q;#J;#$;#Z;#Y;#z;#W;#Q;#w;#X;#G;constructor(q){this.#$=this.#A(),this.#Y=(J)=>this.#q.get(J),this.#Q=new z5,this.#w=this.#N(),q?.parent===void 0?(this.#q=Eq.build(void 0),this.#J=xq.build(void 0),this.#Z=kq.build(void 0)):(this.#q=Eq.build(q.parent.#q),this.#J=xq.build(q.parent.#J),this.#Z=kq.build(q.parent.#Z),q.parent.#Q.subscribe(this.#Q)),this.#z=this.#J.get.bind(this.#J),this.#X=this.#H.bind(this),this.#W={autobind:q?.autobind??!1,defaultScope:q?.defaultScope??cw},this.#G=[]}bind(q){return new G5((J)=>{this.#H(J)},void 0,this.#W.defaultScope,q)}get(q,J){let Z=this.#F(!1,q,J),Q=this.#_(Z);if(U0(Q))throw new v1(y1.invalidOperation,`Unexpected asyncronous service when resolving service "${f0(q)}"`);return Q}getAll(q,J){let Z=this.#F(!0,q,J),Q=this.#_(Z);if(U0(Q))throw new v1(y1.invalidOperation,`Unexpected asyncronous service when resolving service "${f0(q)}"`);return Q}async getAllAsync(q,J){let Z=this.#F(!0,q,J);return this.#_(Z)}async getAsync(q,J){let Z=this.#F(!1,q,J);return this.#_(Z)}isBound(q,J){let Z=this.#J.get(q);return this.#V(q,Z,J)}isCurrentBound(q,J){let Z=this.#J.getNonParentBindings(q);return this.#V(q,Z,J)}async load(...q){await Promise.all(this.#B(...q))}loadSync(...q){let J=this.#B(...q);for(let Z of J)if(Z!==void 0)throw new v1(y1.invalidOperation,"Unexpected asyncronous module load. Consider using Container.load() instead.")}onActivation(q,J){this.#q.add(J,{serviceId:q})}onDeactivation(q,J){this.#Z.add(J,{serviceId:q})}restore(){let q=this.#G.pop();if(q===void 0)throw new v1(y1.invalidOperation,"No snapshot available to restore");this.#q=q.activationService,this.#J=q.bindingService,this.#Z=q.deactivationService,this.#x()}async rebind(q){return await this.unbind(q),this.bind(q)}rebindSync(q){return this.unbindSync(q),this.bind(q)}snapshot(){this.#G.push({activationService:this.#q.clone(),bindingService:this.#J.clone(),deactivationService:this.#Z.clone()})}async unbind(q){await this.#U(q)}async unbindAll(){let q=[...this.#J.getNonParentBoundServices()];await Promise.all(q.map(async(J)=>F5(this.#$,J)));for(let J of q)this.#q.removeAllByServiceId(J),this.#J.removeAllByServiceId(J),this.#Z.removeAllByServiceId(J);this.#Q.clearCache()}unbindSync(q){this.#U(q)!==void 0&&this.#k(q)}async unload(...q){await Promise.all(this.#D(...q)),this.#j(q)}unloadSync(...q){let J=this.#D(...q);for(let Z of J)if(Z!==void 0)throw new v1(y1.invalidOperation,"Unexpected asyncronous module unload. Consider using Container.unload() instead.");this.#j(q)}#L(q){return{bind:(J)=>new G5((Z)=>{this.#H(Z)},q,this.#W.defaultScope,J),isBound:this.isBound.bind(this),onActivation:(J,Z)=>{this.#q.add(Z,{moduleId:q,serviceId:J})},onDeactivation:(J,Z)=>{this.#Z.add(Z,{moduleId:q,serviceId:J})},rebind:this.rebind.bind(this),rebindSync:this.rebindSync.bind(this),unbind:this.unbind.bind(this),unbindSync:this.unbindSync.bind(this)}}#A(){return{getBindings:(q)=>this.#J.get(q),getBindingsFromModule:(q)=>this.#J.getByModuleId(q),getClassMetadata:N6,getDeactivations:(q)=>this.#Z.get(q)}}#R(q,J,Z){return{isMultiple:q,name:Z?.name,optional:Z?.optional,serviceIdentifier:J,tag:Z?.tag}}#P(q,J,Z){let Q={autobindOptions:Z?.autobind??this.#W.autobind?{scope:this.#W.defaultScope}:void 0,getBindings:this.#z,getClassMetadata:N6,rootConstraints:{isMultiple:J,serviceIdentifier:q},servicesBranch:[],setBinding:this.#X};return this.#E(Q,Z),Q}#F(q,J,Z){let Q=this.#R(q,J,Z),$=this.#Q.get(Q);if($!==void 0)return $;let W=n$(this.#P(J,q,Z));return this.#Q.set(Q,W),W}#N(){return{get:this.get.bind(this),getAll:this.getAll.bind(this),getAllAsync:this.getAllAsync.bind(this),getAsync:this.getAsync.bind(this)}}#_(q){return o$({context:this.#w,getActivations:this.#Y,planResult:q,requestScopeCache:new Map})}#E(q,J){J!==void 0&&(J.name!==void 0&&(q.rootConstraints.name=J.name),J.optional===!0&&(q.rootConstraints.isOptional=!0),J.tag!==void 0&&(q.rootConstraints.tag={key:J.tag.key,value:J.tag.value}))}#V(q,J,Z){if(J===void 0)return!1;let Q={getAncestor:()=>{},name:Z?.name,serviceIdentifier:q,tags:new Map};Z?.tag!==void 0&&Q.tags.set(Z.tag.key,Z.tag.value);for(let $ of J)if($.isSatisfiedBy(Q))return!0;return!1}#B(...q){return q.map((J)=>J.load(this.#L(J.id)))}#D(...q){return q.map((J)=>r$(this.#$,J.id))}#x(){this.#Q.clearCache(),this.#Y=(q)=>this.#q.get(q),this.#z=this.#J.get.bind(this.#J),this.#w=this.#N(),this.#X=this.#H.bind(this)}#H(q){this.#J.set(q),this.#Q.clearCache()}#k(q){let J;if(t$(q)){let Q=this.#J.getById(q.id),$=(Z=Q,function(W){if(W===void 0)return;let Y=W.next();return Y.done!==!0?Y.value:void 0}(Z?.[Symbol.iterator]()))?.serviceIdentifier;J=$===void 0?"Unexpected asyncronous deactivation when unbinding binding identifier. Consider using Container.unbind() instead.":`Unexpected asyncronous deactivation when unbinding "${f0($)}" binding. Consider using Container.unbind() instead.`}else J=`Unexpected asyncronous deactivation when unbinding "${f0(q)}" service. Consider using Container.unbind() instead.`;var Z;throw new v1(y1.invalidOperation,J)}#U(q){return t$(q)?this.#O(q):this.#C(q)}#O(q){let J=this.#J.getById(q.id),Z=b8(this.#$,J);if(Z!==void 0)return Z.then(()=>{this.#K(q)});this.#K(q)}#K(q){this.#J.removeById(q.id),this.#Q.clearCache()}#j(q){for(let J of q)this.#q.removeAllByModuleId(J.id),this.#J.removeAllByModuleId(J.id),this.#Z.removeAllByModuleId(J.id);this.#Q.clearCache()}#C(q){let J=F5(this.#$,q);if(J!==void 0)return J.then(()=>{this.#I(q)});this.#I(q)}#I(q){this.#q.removeAllByServiceId(q),this.#J.removeAllByServiceId(q),this.#Z.removeAllByServiceId(q),this.#Q.clearCache()}}var B5=k1(_q(),1);class u8{constructor(q,J,Z,Q,$){this.deviceModel=q,this.serviceUuid=J,this.writeUuid=Z,this.writeCmdUuid=Q,this.notifyUuid=$}}class L1{id;productName;usbProductId;bootloaderUsbProductId;usbOnly;memorySize;getBlockSize;masks;bluetoothSpec;constructor(q){this.id=q.id,this.productName=q.productName,this.usbProductId=q.usbProductId,this.bootloaderUsbProductId=q.bootloaderUsbProductId,this.usbOnly=q.usbOnly,this.memorySize=q.memorySize,this.getBlockSize=q.getBlockSize,this.masks=q.masks,this.bluetoothSpec=q.bluetoothSpec}}var{defineProperty:JW,getOwnPropertyDescriptor:pw}=Object,sw=(q,J,Z)=>(J in q)?JW(q,J,{enumerable:!0,configurable:!0,writable:!0,value:Z}):q[J]=Z,nw=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?pw(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&JW(J,Z,$),$},iw=(q,J,Z)=>sw(q,typeof J!="symbol"?J+"":J,Z),w1=class{getAllDeviceModels(){return Object.values(w1.deviceModelByIds)}getDeviceModel(q){return w1.deviceModelByIds[q.id]}filterDeviceModels(q){return this.getAllDeviceModels().filter((J)=>Object.entries(q).every(([Z,Q])=>J[Z]===Q))}getBluetoothServicesInfos(){return Object.values(w1.deviceModelByIds).reduce((q,J)=>{let{bluetoothSpec:Z}=J;return Z?{...q,...Z.reduce((Q,$)=>({...Q,[$.serviceUuid]:new u8(J,$.serviceUuid,$.writeUuid,$.writeCmdUuid,$.notifyUuid)}),{})}:q},{})}getBluetoothServices(){return Object.values(w1.deviceModelByIds).map((q)=>(q.bluetoothSpec||[]).map((J)=>J.serviceUuid)).flat().filter((q)=>!!q)}};iw(w1,"deviceModelByIds",{[o.NANO_S]:new L1({id:o.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:327680,getBlockSize:(q)=>B5.default.lt(B5.default.coerce(q.firmwareVersion)??"","2.0.0")?4096:2048,masks:[823132160]}),[o.NANO_SP]:new L1({id:o.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1569792,getBlockSize:()=>512,masks:[856686592]}),[o.NANO_X]:new L1({id:o.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2097152,getBlockSize:()=>4096,masks:[855638016],bluetoothSpec:[{serviceUuid:"13d63400-2c97-0004-0000-4c6564676572",notifyUuid:"13d63400-2c97-0004-0001-4c6564676572",writeUuid:"13d63400-2c97-0004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-0004-0003-4c6564676572"}]}),[o.STAX]:new L1({id:o.STAX,productName:"Ledger Stax",usbProductId:96,bootloaderUsbProductId:6,usbOnly:!1,memorySize:1569792,getBlockSize:()=>512,masks:[857735168],bluetoothSpec:[{serviceUuid:"13d63400-2c97-6004-0000-4c6564676572",notifyUuid:"13d63400-2c97-6004-0001-4c6564676572",writeUuid:"13d63400-2c97-6004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-6004-0003-4c6564676572"}]}),[o.FLEX]:new L1({id:o.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1569792,getBlockSize:()=>512,masks:[858783744],bluetoothSpec:[{serviceUuid:"13d63400-2c97-3004-0000-4c6564676572",notifyUuid:"13d63400-2c97-3004-0001-4c6564676572",writeUuid:"13d63400-2c97-3004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-3004-0003-4c6564676572"}]}),[o.APEX]:new L1({id:o.APEX,productName:"Ledger Nano Gen5",usbProductId:128,bootloaderUsbProductId:8,usbOnly:!1,memorySize:1569792,getBlockSize:()=>512,masks:[859832320],bluetoothSpec:[{serviceUuid:"13d63400-2c97-8004-0000-4c6564676572",notifyUuid:"13d63400-2c97-8004-0001-4c6564676572",writeUuid:"13d63400-2c97-8004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-8004-0003-4c6564676572"},{serviceUuid:"13d63400-2c97-9004-0000-4c6564676572",notifyUuid:"13d63400-2c97-9004-0001-4c6564676572",writeUuid:"13d63400-2c97-9004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-9004-0003-4c6564676572"}]})}),w1=nw([R()],w1);class bq{statusCode;data;constructor({statusCode:q,data:J}){this.statusCode=q,this.data=J}}var ZW=5,A1=1,U6=2,g1=2,K6=2;class QW extends a{makeStateMachine(q){let{getOsVersion:J,getDeviceVersion:Z,getFirmwareVersion:Q,genuineCheck:$,getDeviceSessionState:W,setDeviceSessionState:Y}=this.extractDependencies(q),z=this.input.unlockTimeout??t,X=new M0({input:{unlockTimeout:z}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{goToDashboard:X,getOsVersion:l(J),getDeviceVersion:l(Z),getFirmwareVersion:l(Q),genuineCheck:O0($)},guards:{hasError:(w)=>w.context._internalState.error!==null},actions:{assignErrorFromEvent:N({_internalState:(w)=>({...w.context._internalState,error:w.event.error})})}}).createMachine({id:"GenuineCheckDeviceAction",initial:"DeviceReady",context:(w)=>({input:{unlockTimeout:w.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None},_internalState:{error:null,result:{isGenuine:!1},getOsVersionResponse:null,deviceVersion:null,firmwareVersion:null}}),states:{DeviceReady:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:()=>w.context._internalState,Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(w)=>{},onDone:{target:"GetOsVersionCheck",actions:N({_internalState:(w)=>{if(n(w.event.output)){let F=W(),_=w.event.output.data.secureElementFlags.isSecureConnectionAllowed;return F.sessionStateType!==d.Connected&&Y({...F,isSecureConnectionAllowed:_}),{...w.context._internalState,getOsVersionResponse:w.event.output.data}}return{...w.context._internalState,error:w.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetDeviceVersion"}]},GetDeviceVersion:{invoke:{id:"getDeviceVersion",src:"getDeviceVersion",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse}),onDone:{target:"GetDeviceVersionCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,deviceVersion:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetFirmwareVersion"}]},GetFirmwareVersion:{invoke:{id:"getFirmwareVersion",src:"getFirmwareVersion",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,deviceVersion:w.context._internalState.deviceVersion}),onDone:{target:"GetFirmwareVersionCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,firmwareVersion:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetFirmwareVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GenuineCheck"}]},GenuineCheck:{invoke:{id:"genuineCheck",src:"genuineCheck",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,finalFirmware:w.context._internalState.firmwareVersion}),onSnapshot:{actions:N({intermediateValue:(w)=>{switch(w.event.snapshot.context?.type){case M.DeviceId:return{...w.context.intermediateValue,deviceId:w.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...w.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:return{...w.context.intermediateValue,requiredUserInteraction:k.None};default:return{...w.context.intermediateValue}}},_internalState:(w)=>w.event.snapshot.context?.type===M.Error?{...w.context._internalState,error:w.event.snapshot.context.error.mapDAErrors()}:w.event.snapshot.context?.type===M.Result?{...w.context._internalState,result:{isGenuine:eQ(w.event.snapshot.context.payload)}}:w.context._internalState})},onDone:{target:"GenuineCheckCheck"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GenuineCheckCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(w)=>w.context._internalState.error?K(w.context._internalState.error):I(w.context._internalState.result)})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new T0),getDeviceVersion:({input:J})=>{let{deviceInfo:Z}=J;return q.getManagerApiService().getDeviceVersion(Z)},getFirmwareVersion:({input:J})=>{let{deviceInfo:Z,deviceVersion:Q}=J;return q.getManagerApiService().getFirmwareVersion(Z,Q)},genuineCheck:({input:J})=>{let{deviceInfo:Z,finalFirmware:Q}=J,$=q.getSecureChannelService().genuineCheck(Z,Q);return new d0(q,{connection:$}).run()},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}class Tq extends a{makeStateMachine(q){let{getOsVersion:J,getDeviceVersion:Z,getFirmwareVersion:Q,listInstalledApps:$,getDeviceSessionState:W,setDeviceSessionState:Y}=this.extractDependencies(q),z=this.input.unlockTimeout??t,X=new M0({input:{unlockTimeout:z}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{goToDashboard:X,getOsVersion:l(J),getDeviceVersion:l(Z),getFirmwareVersion:l(Q),listInstalledApps:O0($)},guards:{hasError:(w)=>w.context._internalState.error!==null},actions:{assignErrorFromEvent:N({_internalState:(w)=>({...w.context._internalState,error:w.event.error})})}}).createMachine({id:"ListInstalledAppsDeviceAction",initial:"DeviceReady",context:(w)=>({input:{unlockTimeout:w.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None},_internalState:{error:null,getOsVersionResponse:null,deviceVersion:null,firmwareVersion:null,result:{installedApps:[]}}}),states:{DeviceReady:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:()=>w.context._internalState,Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(w)=>{},onDone:{target:"GetOsVersionCheck",actions:N({_internalState:(w)=>{if(n(w.event.output)){let F=W(),_=w.event.output.data.secureElementFlags.isSecureConnectionAllowed;return F.sessionStateType!==d.Connected&&Y({...F,isSecureConnectionAllowed:_}),{...w.context._internalState,getOsVersionResponse:w.event.output.data}}return{...w.context._internalState,error:w.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetDeviceVersion"}]},GetDeviceVersion:{invoke:{id:"getDeviceVersion",src:"getDeviceVersion",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse}),onDone:{target:"GetDeviceVersionCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,deviceVersion:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetFirmwareVersion"}]},GetFirmwareVersion:{invoke:{id:"getFirmwareVersion",src:"getFirmwareVersion",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,deviceVersion:w.context._internalState.deviceVersion}),onDone:{target:"GetFirmwareVersionCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,firmwareVersion:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetFirmwareVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"ListInstalledApps"}]},ListInstalledApps:{invoke:{id:"listInstalledApps",src:"listInstalledApps",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,finalFirmware:w.context._internalState.firmwareVersion}),onSnapshot:{actions:N({intermediateValue:(w)=>{switch(w.event.snapshot.context?.type){case M.DeviceId:return{...w.context.intermediateValue,deviceId:w.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...w.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:return{...w.context.intermediateValue,requiredUserInteraction:k.None};default:return{...w.context.intermediateValue}}},_internalState:(w)=>{if(w.event.snapshot.context?.type===M.Error)return{...w.context._internalState,error:w.event.snapshot.context.error.mapDAErrors()};if(w.event.snapshot.context?.type===M.Result){if(I8(w.event.snapshot.context.payload))return{...w.context._internalState,result:{installedApps:w.event.snapshot.context.payload}};throw Error(`Invalid result ${JSON.stringify(w.event.snapshot.context.payload)}`)}return{...w.context._internalState}}})},onDone:{target:"Success"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListInstalledAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(w)=>w.context._internalState.error?K(w.context._internalState.error):I(w.context._internalState.result)})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new T0),getDeviceVersion:({input:J})=>{let{deviceInfo:Z}=J;return q.getManagerApiService().getDeviceVersion(Z)},getFirmwareVersion:({input:J})=>{let{deviceInfo:Z,deviceVersion:Q}=J;return q.getManagerApiService().getFirmwareVersion(Z,Q)},listInstalledApps:({input:J})=>{let{deviceInfo:Z,finalFirmware:Q}=J,$=q.getSecureChannelService().listInstalledApps(Z,Q);return new d0(q,{connection:$}).run()},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}class $W extends a{makeStateMachine(q){let{getOsVersion:J,getAppList:Z,installApp:Q,getDeviceSessionState:$,setDeviceSessionState:W}=this.extractDependencies(q),Y=this.input.unlockTimeout??t,z=new Tq({input:{unlockTimeout:Y}}).makeStateMachine(q),X=new M0({input:{unlockTimeout:Y}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{listInstalledApps:z,goToDashboard:X,getOsVersion:l(J),getAppList:l(Z),installApp:O0(Q)},guards:{hasError:(w)=>w.context._internalState.error!==null,appInstalled:(w)=>w.context._internalState.installedApps.some((F)=>F.name===w.context.input.appName),appNotFound:(w)=>w.context._internalState.appList.findIndex(({versionName:F})=>F===w.context.input.appName)===-1,depAppNotInstalled:(w)=>{let F=w.context._internalState.appList.find(({versionName:_})=>_===w.context.input.appName);return F?.parentName?w.context._internalState.installedApps.findIndex(({name:_})=>_===F.parentName)===-1:!1}},actions:{assignErrorFromEvent:N({_internalState:(w)=>({...w.context._internalState,error:w.event.error})}),assignAppNotFound:N({_internalState:(w)=>({...w.context._internalState,error:new q0("App to install not found in manager API")})}),assignDepAppNotInstalled:N({_internalState:(w)=>({...w.context._internalState,error:new q0("Dep app is not installed on the device")})}),cleanupDeviceState:()=>{let w=$();w.sessionStateType!==d.Connected&&W({...w,installedApps:[],appsUpdates:void 0})}}}).createMachine({id:"InstallAppDeviceAction",initial:"DeviceReady",context:(w)=>({input:{unlockTimeout:w.input.unlockTimeout,appName:w.input.appName},intermediateValue:{requiredUserInteraction:k.None,progress:0},_internalState:{error:null,installedApps:[],getOsVersionResponse:null,appList:[]}}),states:{DeviceReady:{always:{target:"ListInstalledApps"}},ListInstalledApps:{value:"ListInstalledApps",invoke:{id:"listInstalledApps",src:"listInstalledApps",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"ListInstalledAppsCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:({installedApps:F})=>({...w.context._internalState,installedApps:F}),Left:(F)=>({...w.context._internalState,error:F})})})}}},ListInstalledAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"appInstalled"},{target:"GoToDashboard"}]},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:()=>w.context._internalState,Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(w)=>{},onDone:{target:"GetOsVersionCheck",actions:N({_internalState:(w)=>{if(n(w.event.output)){let F=$(),_=w.event.output.data.secureElementFlags.isSecureConnectionAllowed;return F.sessionStateType!==d.Connected&&W({...F,isSecureConnectionAllowed:_}),{...w.context._internalState,getOsVersionResponse:w.event.output.data}}return{...w.context._internalState,error:w.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetAppList"}]},GetAppList:{invoke:{id:"getAppList",src:"getAppList",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse}),onDone:{target:"GetAppListCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,appList:F}),Left:(F)=>({...w.context._internalState,error:F})})})}}},GetAppListCheck:{always:[{target:"Error",guard:"hasError"},{target:"Error",guard:"appNotFound",actions:"assignAppNotFound"},{target:"Error",guard:"depAppNotInstalled",actions:"assignDepAppNotInstalled"},{target:"InstallApp"}]},InstallApp:{invoke:{id:"installApp",src:"installApp",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,app:w.context._internalState.appList.find(({versionName:F})=>F===w.context.input.appName)}),onSnapshot:{actions:N({intermediateValue:(w)=>w.event.snapshot.context?.type===M.DeviceId?{...w.context.intermediateValue,deviceId:w.event.snapshot.context.payload.deviceId}:w.event.snapshot.context?.type===M.Progress?{...w.context.intermediateValue,progress:w.event.snapshot.context.payload.progress}:{...w.context.intermediateValue},_internalState:(w)=>w.event.snapshot.context?.type===M.Error?{...w.context._internalState,error:w.event.snapshot.context.error.mapInstallDAErrors()}:w.context._internalState})},onDone:{target:"ListInstalledApps",actions:"cleanupDeviceState"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final",description:"App installed successfully"},Error:{type:"final"}},output:({context:w})=>w._internalState.error?K(w._internalState.error):I(void 0)})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new T0),getAppList:({input:J})=>{let{deviceInfo:Z}=J;return q.getManagerApiService().getAppList(Z)},installApp:({input:J})=>{let{deviceInfo:Z,app:Q}=J,$=q.getSecureChannelService().installApp(Z,Q);return new d0(q,{connection:$}).run()},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}class WW extends a{makeStateMachine(q){let{getOsVersion:J,getAppsByHash:Z,uninstallApp:Q,getDeviceSessionState:$,setDeviceSessionState:W}=this.extractDependencies(q),Y=this.input.unlockTimeout??t,z=new M0({input:{unlockTimeout:Y}}).makeStateMachine(q),X=new Tq({input:{unlockTimeout:Y}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{listInstalledApps:X,goToDashboard:z,getOsVersion:l(J),getAppsByHash:l(Z),uninstallApp:O0(Q)},guards:{hasError:(w)=>w.context._internalState.error!==null,appNotInstalled:(w)=>!w.context._internalState.installedApps.some((F)=>F.name===w.context.input.appName),appNotFound:(w)=>w.context._internalState.appList.findIndex((F)=>F?.versionName===w.context.input.appName)===-1,isDepAppOfOther:(w)=>w.context._internalState.appList.some((F)=>F?.parentName===w.context.input.appName)},actions:{assignErrorFromEvent:N({_internalState:(w)=>({...w.context._internalState,error:w.event.error})}),assignAppNotFound:N({_internalState:(w)=>({...w.context._internalState,error:new q0("App to uninstall not found in manager API")})}),assignIsDepAppOfOther:N({_internalState:(w)=>({...w.context._internalState,error:new q0("App to uninstall is a dependency of another installed app")})}),cleanupDeviceState:()=>{let w=$();w.sessionStateType!==d.Connected&&W({...w,installedApps:[],appsUpdates:void 0})}}}).createMachine({id:"UninstallAppDeviceAction",initial:"DeviceReady",context:(w)=>({input:{unlockTimeout:w.input.unlockTimeout,appName:w.input.appName},intermediateValue:{requiredUserInteraction:k.None},_internalState:{error:null,installedApps:[],appList:[],getOsVersionResponse:null}}),states:{DeviceReady:{always:{target:"ListInstalledApps"}},ListInstalledApps:{invoke:{id:"listInstalledApps",src:"listInstalledApps",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"ListInstalledAppsCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:({installedApps:F})=>({...w.context._internalState,installedApps:F,hasCheckedInstalledApps:!0}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListInstalledAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"appNotInstalled"},{target:"GetAppsByHash"}]},GetAppsByHash:{invoke:{id:"getAppsByHash",src:"getAppsByHash",input:(w)=>w.context._internalState.installedApps,onDone:{target:"GetAppsByHashCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,appList:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetAppsByHashCheck:{always:[{target:"Error",guard:"hasError"},{target:"Error",guard:"appNotFound",actions:"assignAppNotFound"},{target:"Error",guard:"isDepAppOfOther",actions:"assignIsDepAppOfOther"},{target:"GoToDashboard"}]},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:()=>w.context._internalState,Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(w)=>{},onDone:{target:"GetOsVersionCheck",actions:N({_internalState:(w)=>{if(n(w.event.output)){let F=$(),_=w.event.output.data.secureElementFlags.isSecureConnectionAllowed;return F.sessionStateType!==d.Connected&&W({...F,isSecureConnectionAllowed:_}),{...w.context._internalState,getOsVersionResponse:w.event.output.data}}return{...w.context._internalState,error:w.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"UninstallApp"}]},UninstallApp:{invoke:{id:"uninstallApp",src:"uninstallApp",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,app:w.context._internalState.appList.find((F)=>F?.versionName===w.context.input.appName)}),onSnapshot:{actions:N({intermediateValue:(w)=>{switch(w.event.snapshot.context?.type){case M.DeviceId:return{...w.context.intermediateValue,deviceId:w.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...w.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:return{...w.context.intermediateValue,requiredUserInteraction:k.None};default:return{...w.context.intermediateValue}}},_internalState:(w)=>w.event.snapshot.context?.type===M.Error?{...w.context._internalState,error:w.event.snapshot.context.error.mapDAErrors()}:w.context._internalState})},onDone:{target:"ListInstalledApps",actions:"cleanupDeviceState"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final",description:"App uninstalled successfully"},Error:{type:"final"}},output:({context:w})=>w._internalState.error?K(w._internalState.error):I(void 0)})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new T0),getAppsByHash:({input:J})=>{let Z=J.map((Q)=>Q.hash);return q.getManagerApiService().getAppsByHash(Z)},uninstallApp:({input:J})=>{let{deviceInfo:Z,app:Q}=J,$=q.getSecureChannelService().uninstallApp(Z,Q);return new d0(q,{connection:$}).run()},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}var aw=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),D5={randomUUID:aw};var U5,ow=new Uint8Array(16);function K5(){if(!U5){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");U5=crypto.getRandomValues.bind(crypto)}return U5(ow)}var C0=[];for(let q=0;q<256;++q)C0.push((q+256).toString(16).slice(1));function YW(q,J=0){return(C0[q[J+0]]+C0[q[J+1]]+C0[q[J+2]]+C0[q[J+3]]+"-"+C0[q[J+4]]+C0[q[J+5]]+"-"+C0[q[J+6]]+C0[q[J+7]]+"-"+C0[q[J+8]]+C0[q[J+9]]+"-"+C0[q[J+10]]+C0[q[J+11]]+C0[q[J+12]]+C0[q[J+13]]+C0[q[J+14]]+C0[q[J+15]]).toLowerCase()}function rw(q,J,Z){if(D5.randomUUID&&!J&&!q)return D5.randomUUID();q=q||{};let Q=q.random||(q.rng||K5)();if(Q[6]=Q[6]&15|64,Q[8]=Q[8]&63|128,J){Z=Z||0;for(let $=0;$<16;++$)J[Z+$]=Q[$];return J}return YW(Q)}var R1=rw;var Z1={getLastBytesFrom(q,J){return q.slice(-J)},getFirstBytesFrom(q,J){return q.slice(0,J)},bytesToNumber(q){return q.reduce((J,Z,Q)=>J+Z*Math.pow(256,q.length-1-Q),0)},numberToByteArray(q,J){return new Uint8Array(J).map((Z,Q)=>q>>8*(J-1-Q)&255)}};var j5=2,g8=800;class m8{_tag="FramerOverflowError";originalError;constructor(){this.originalError=Error("Frame header length is greater than frame size")}}class I5{_tag="FramerApduError";originalError;constructor(){this.originalError=Error("Frame offset is greater than apdu length")}}class l8{_tag="ReceiverApduError";originalError;constructor(q){this.originalError=Error(q??"Unable to parse apdu")}}class d8{_tag="DeviceSessionNotFound";originalError;constructor(q){this.originalError=q??Error("Device session not found")}}class j6{_header;_data;constructor({header:q,data:J}){this._header=q,this._data=J}toString(){return JSON.stringify({header:this._header.toString(),data:B0(this._data)},null,2)}getRawData(){let q=this._header.getRawData(),J=new Uint8Array(q.length+this._data.length);return J.set(q,0),J.set(this._data,q.length),J}getHeader(){return this._header}getData(){return this._data}}class I6{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:q,dataSize:J,index:Z,headTag:Q,length:$,channel:W}){this._uuid=q,this._dataLength=J,this._index=Z,this._headTag=Q,this._length=$,this._channel=W}getDataLength(){return this._dataLength.map((q)=>Z1.bytesToNumber(q))}setDataSize(q){return this._dataLength=q,this}getLength(){return this._length}toString(){return JSON.stringify({uuid:this._uuid.toString(),dataSize:this._dataLength.extract()?.toString(),index:this._index.toString(),headTag:this._headTag.toString(),length:this._length.toString(),channel:this._channel.extract()?.toString()})}getRawData(){return new Uint8Array([...this._channel.caseOf({Just:(q)=>[...q],Nothing:()=>[]}),...this._headTag,...this._index,...this._dataLength.caseOf({Just:(q)=>[...q],Nothing:()=>[]})])}}var y={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var{defineProperty:tw,getOwnPropertyDescriptor:ew}=Object,qX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?ew(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&tw(J,Z,$),$},JX=(q,J)=>(Z,Q)=>J(Z,Q,q),Mq=class{_channel;_logger;_pendingFrames;constructor({channel:q=J0.zero()},J){this._channel=q,this._logger=J("ApduReceiverService"),this._pendingFrames=[]}handleFrame(q){return this.getFrameFromBytes(q).map((J)=>{if(this._pendingFrames.push(J),!this._pendingFrames[0])return p;let Z=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(Z)})}getCompleteFrame(q){return q.chain((J)=>{if(!this.isComplete(J))return this._logger.debug("frame is not complete, waiting for more"),p;let Z=Z1.getFirstBytesFrom(this.concatFrames(this._pendingFrames),J),Q=Z1.getFirstBytesFrom(Z,Z.length-j5),$=Z1.getLastBytesFrom(Z,j5);return this._pendingFrames=[],I0(new bq({data:Q,statusCode:$}))})}getFrameFromBytes(q){let J=this._channel.caseOf({Just:()=>U6,Nothing:()=>0}),Z=q.slice(J,J+A1),Q=q.slice(J+A1,J+A1+g1),$=Q.reduce((_,G)=>_+G,0)===0;if(!$&&this._pendingFrames.length===0)return K(new l8);let W=J+A1+g1,Y=$?K6:0;if(q.length<J+A1+g1+Y)return K(new l8("Unable to parse header from apdu"));let z=$?I0(q.slice(W,W+Y)):p,X=W+Y,w=q.slice(X),F=new j6({header:new I6({uuid:R1(),channel:this._channel,dataSize:z,headTag:Z,index:Q,length:J+A1+g1+Y}),data:w});return I(F)}isComplete(q){return this._pendingFrames.reduce((J,Z)=>J+Z.getData().length,0)>=q}concatFrames(q){return q.reduce((J,Z)=>Uint8Array.from([...J,...Z.getData()]),new Uint8Array(0))}};Mq=qX([R(),JX(1,j(y.LoggerPublisherServiceFactory))],Mq);var ZX=(q={},J)=>new Mq({channel:J0.of(new Uint8Array([18,52])),...q},J);var{defineProperty:QX,getOwnPropertyDescriptor:$X}=Object,WX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?$X(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&QX(J,Z,$),$},YX=(q,J)=>(Z,Q)=>J(Z,Q,q),fq=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:q,channel:J=J0.zero(),padding:Z=!1},Q){this._frameSize=q,this._channel=J,this._padding=Z,this._logger=Q("DefaultApduSenderService")}getFrames(q){let J=[],Z=0,Q=this.getFrameAtIndex(q,Z);for(;Q.isRight();)J.push(Q.extract()),Z+=1,Q=this.getFrameAtIndex(q,Z).mapLeft(($)=>($ instanceof m8||this._logger.error("Error while parsing frame",{data:{error:$}}),$));return J}getFrameAtIndex(q,J){let Z=this.getFrameHeaderFrom(J,q.length),Q=J===0?0:J*this._frameSize-this.getHeaderSizeSumFrom(J);if(Q>=q.length)return K(new m8);if(Z.getLength()>this._frameSize)return K(new I5);let $=this._frameSize-Z.getLength(),W=q.slice(Q,Q+this._frameSize-Z.getLength()),Y=this._padding?new Uint8Array($).fill(0):new Uint8Array(W.length<$?W.length:$);Y.set(W,0);let z=new j6({header:Z,data:Y});return I(z)}getFrameHeaderFrom(q,J){let Z=new I6({uuid:R1(),channel:this._channel.map((Q)=>Z1.getLastBytesFrom(Q,U6)),headTag:new Uint8Array([ZW]),index:Z1.numberToByteArray(q,g1),length:this.getFrameHeaderSizeFromIndex(q),dataSize:J0.zero()});return q===0&&Z.setDataSize(J0.of(Z1.numberToByteArray(J,K6))),Z}getHeaderSizeSumFrom(q){let J=this.getFrameHeaderSizeFromIndex(0),Z=1;for(;Z<q;)J+=this.getFrameHeaderSizeFromIndex(Z),Z+=1;return J}getFrameHeaderSizeFromIndex(q){return this._channel.caseOf({Just:()=>U6,Nothing:()=>0})+g1+A1+(q===0?K6:0)}};fq=WX([R(),YX(1,j(y.LoggerPublisherServiceFactory))],fq);var zX=(q={},J)=>new fq({frameSize:64,channel:J0.of(new Uint8Array([18,52])),padding:!0,...q},J);var L6={SendCommandUseCase:Symbol.for("SendCommandUseCase")};var c0={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService"),GetDmkVersionUseCase:Symbol.for("GetDmkVersionUseCase")};var u={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService"),GetDeviceSessionStateUseCase:Symbol.for("GetDeviceSessionStateUseCase"),DisableDeviceSessionRefresherUseCase:Symbol.for("DisableDeviceSessionRefresherUseCase"),CloseSessionsUseCase:Symbol.for("CloseSessionsUseCase"),UnsafeBypassIntentQueueUseCase:Symbol.for("UnsafeBypassIntentQueueUseCase")};var r={StartDiscoveringUseCase:Symbol.for("StartDiscoveringUseCase"),StopDiscoveringUseCase:Symbol.for("StopDiscoveringUseCase"),ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase"),GetConnectedDeviceUseCase:Symbol.for("GetConnectedDeviceUseCase"),ListenToAvailableDevicesUseCase:Symbol.for("ListenToAvailableDevicesUseCase"),ListenToConnectedDeviceUseCase:Symbol.for("ListenToConnectedDeviceUseCase"),ListConnectedDevicesUseCase:Symbol.for("ListConnectedDevicesUseCase"),ReconnectUseCase:Symbol.for("ReconnectUseCase")};var x0={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig"),SetProviderUseCase:Symbol.for("SetProviderUseCase")};var A6={SendApduUseCase:Symbol.for("SendApduUseCase")};var K0={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var{defineProperty:wX,getOwnPropertyDescriptor:XX}=Object,FX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?XX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&wX(J,Z,$),$},zW=(q,J)=>(Z,Q)=>J(Z,Q,q),c8=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("SendCommandUseCase")}async execute({sessionId:q,command:J,abortTimeout:Z}){return this._sessionService.getDeviceSessionById(q).caseOf({Right:async(Q)=>await Q.sendCommand(J,Z),Left:(Q)=>{throw this._logger.error("Error getting session",{data:{error:Q}}),Q}})}};c8=FX([R(),zW(0,j(u.DeviceSessionService)),zW(1,j(y.LoggerPublisherServiceFactory))],c8);var{defineProperty:_X,getOwnPropertyDescriptor:HX}=Object,GX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?HX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&_X(J,Z,$),$},W0=class{execute=vi.fn(()=>"stub")};W0=GX([R()],W0);var wW=({stub:q=!1}={})=>new X0(({bind:J,rebindSync:Z})=>{J(L6.SendCommandUseCase).to(c8),q&&Z(L6.SendCommandUseCase).to(W0)});var{defineProperty:NX,getOwnPropertyDescriptor:VX}=Object,BX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?VX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&NX(J,Z,$),$},XW=(q,J)=>(Z,Q)=>J(Z,Q,q),p8=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("ExecuteDeviceActionUseCase")}execute({sessionId:q,deviceAction:J}){return this._sessionService.getDeviceSessionById(q).caseOf({Right:(Z)=>Z.executeDeviceAction(J),Left:(Z)=>{throw this._logger.error("Error getting session",{data:{error:Z}}),Z}})}};p8=BX([R(),XW(0,j(u.DeviceSessionService)),XW(1,j(y.LoggerPublisherServiceFactory))],p8);var R6={ExecuteDeviceActionUseCase:Symbol.for("ExecuteDeviceActionUseCase")};var FW=({stub:q=!1}={})=>new X0(({bind:J,rebindSync:Z})=>{J(R6.ExecuteDeviceActionUseCase).to(p8),q&&Z(R6.ExecuteDeviceActionUseCase).to(W0)});function _W(q){return typeof q=="object"&&q!==null&&"version"in q&&"name"in q&&typeof q.version=="string"&&typeof q.name=="string"}class s8{constructor(q){this.err=q,this.originalError=q}_tag="ApiCallError";originalError}class L5{constructor(q){this.err=q,this.originalError=q}_tag="ParseResponseError";originalError}class P6{constructor(q){this.err=q,this.originalError=q}_tag="JSONParseError";originalError}class A5{constructor(q){this.err=q,this.originalError=q}_tag="ReadFileError";originalError}var R5={dependencies:{"@noble/hashes":"^1.8.0","@sentry/minimal":"catalog:",inversify:"catalog:","isomorphic-ws":"catalog:","purify-ts":"catalog:","reflect-metadata":"catalog:",semver:"catalog:",uuid:"catalog:",ws:"catalog:",xstate:"catalog:"},devDependencies:{"@ledgerhq/eslint-config-dsdk":"workspace:^","@ledgerhq/ldmk-tool":"workspace:^","@ledgerhq/prettier-config-dsdk":"workspace:^","@ledgerhq/tsconfig-dsdk":"workspace:^","@ledgerhq/vitest-config-dmk":"workspace:^","@statelyai/inspect":"catalog:","@types/semver":"catalog:","@types/uuid":"catalog:","@types/ws":"catalog:",rxjs:"catalog:","ts-node":"catalog:"},exports:{".":{import:"./lib/esm/index.js",require:"./lib/cjs/index.js",types:"./lib/types/index.d.ts"}},files:["./lib","package.json"],license:"Apache-2.0",name:"@ledgerhq/device-management-kit",peerDependencies:{rxjs:"catalog:"},private:!1,repository:{type:"git",url:"https://github.com/LedgerHQ/device-sdk-ts.git"},scripts:{build:"pnpm ldmk-tool build --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",dev:'concurrently "pnpm watch:builds" "pnpm watch:types"',lint:"eslint","lint:fix":"pnpm lint --fix","module:create":"pnpm hygen core-module with-prompt",postpack:"find . -name '*.tgz' -exec cp {} ../../dist/ \\; ",prebuild:"rimraf lib",prettier:"prettier . --check","prettier:fix":"prettier . --write",test:"vitest run","test:coverage":"vitest run --coverage","test:watch":"vitest",typecheck:"tsc --noEmit","watch:builds":"pnpm ldmk-tool watch --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json","watch:types":'concurrently "tsc --watch -p tsconfig.prod.json" "tsc-alias --watch -p tsconfig.prod.json"'},version:"1.9.1"};var{defineProperty:UX,getOwnPropertyDescriptor:KX}=Object,jX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?KX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&UX(J,Z,$),$},IX={name:R5.name,version:R5.version},LX=()=>JSON.stringify(IX),n8=class{getConfig(){return L0.encase(()=>LX()).mapLeft((q)=>new A5(q)).chain((q)=>L0.encase(()=>{let J=JSON.parse(q);if(_W(J))return J;throw Error("Invalid config file")}).mapLeft((J)=>new P6(J)))}};n8=jX([R()],n8);var{defineProperty:AX,getOwnPropertyDescriptor:RX}=Object,PX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?RX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&AX(J,Z,$),$},i8=class{getConfig(){return L0.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};i8=PX([R()],i8);var{defineProperty:EX,getOwnPropertyDescriptor:xX}=Object,kX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?xX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&EX(J,Z,$),$},a8=class{async getConfig(){let q=await this._callApi();if(q.isLeft())return K(new s8(q.extract()));if(!q.extract().ok)return K(new s8(Error("response not ok")));let J=await q.extract().json();return J.isLeft()?K(new P6):J.chain((Z)=>this._parseResponse(Z)).map((Z)=>Z)}_parseResponse(q){let{name:J,version:Z}=q;return!J||!Z?K(new L5):L0.of({name:J,version:Z})}_callApi(){return new Promise((q)=>{q(L0.of({ok:!0,json:async()=>new Promise((J)=>{J(L0.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};a8=kX([R()],a8);var{defineProperty:OX,getOwnPropertyDescriptor:CX}=Object,bX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?CX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&OX(J,Z,$),$},o8=class{async getConfig(){return new Promise((q)=>q(L0.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};o8=bX([R()],o8);var{defineProperty:TX,getOwnPropertyDescriptor:MX}=Object,fX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?MX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&TX(J,Z,$),$},P5=(q,J)=>(Z,Q)=>J(Z,Q,q),r8=class{_local;_remote;_logger;constructor(q,J,Z){this._local=q,this._remote=J,this._logger=Z("config")}async getDmkConfig(){let q=this._local.getConfig().ifLeft((J)=>{this._logger.error("Local config not available",{data:{error:J}})});if(q.isRight()){let J=q.extract();return this._logger.info("Local config available",{data:{config:J}}),J}return this._remote.getConfig().then((J)=>J.mapLeft((Z)=>(this._logger.error("Local config available",{data:{error:Z}}),{name:"DeadDmk",version:"0.0.0-dead.1"})).extract())}};r8=fX([R(),P5(0,j(c0.LocalConfigDataSource)),P5(1,j(c0.RemoteConfigDataSource)),P5(2,j(y.LoggerPublisherServiceFactory))],r8);var{defineProperty:SX,getOwnPropertyDescriptor:hX}=Object,vX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?hX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&SX(J,Z,$),$},yX=(q,J)=>(Z,Q)=>J(Z,Q,q),t8=class{_configService;constructor(q){this._configService=q}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};t8=vX([R(),yX(0,j(c0.ConfigService))],t8);var HW=({stub:q})=>new X0(({bind:J,rebindSync:Z})=>{J(c0.LocalConfigDataSource).to(n8),J(c0.RemoteConfigDataSource).to(a8),J(c0.GetDmkVersionUseCase).to(t8),J(c0.ConfigService).to(r8),q&&(Z(c0.LocalConfigDataSource).to(i8),Z(c0.RemoteConfigDataSource).to(o8))});var e8={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var GW=({stub:q})=>new X0(({bind:J})=>{J(e8.DeviceModelDataSource).to(w1)});var{defineProperty:uX,getOwnPropertyDescriptor:gX}=Object,mX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?gX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&uX(J,Z,$),$},NW=(q,J)=>(Z,Q)=>J(Z,Q,q),q9=class{constructor(q,J){this._sessionService=q,this._logger=J("DisableDeviceSessionRefresherUseCase")}_logger;execute({sessionId:q,blockerId:J}){return this._sessionService.getDeviceSessionById(q).caseOf({Left:(Z)=>{throw this._logger.error("Error getting device session",{data:{error:Z}}),Z},Right:(Z)=>Z.disableRefresher(J)})}};q9=mX([R(),NW(0,j(u.DeviceSessionService)),NW(1,j(y.LoggerPublisherServiceFactory))],q9);import{ReplaySubject as sX}from"rxjs";var{defineProperty:lX,getOwnPropertyDescriptor:dX}=Object,cX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?dX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&lX(J,Z,$),$},pX=(q,J)=>(Z,Q)=>J(Z,Q,q),J9=class{_sessions;_sessionsSubject;_logger;constructor(q){this._sessions=[],this._sessionsSubject=new sX,this._logger=q("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(q){return this._sessions.find((J)=>J.id===q.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:q}}),this):(this._sessions.push(q),this._sessionsSubject.next(q),this._logger.info("DeviceSession added",{data:{sessionId:q.id}}),this)}removeDeviceSession(q){let J=this._sessions.find((Z)=>Z.id===q);return J?(J.close(),this._sessions=this._sessions.filter((Z)=>Z.id!==q),this._logger.info("DeviceSession removed",{data:{sessionId:q}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:q}}),this)}getDeviceSessionById(q){return J0.fromNullable(this._sessions.find((J)=>J.id===q)).toEither(new d8)}getDeviceSessionsByDeviceId(q){return J0.fromPredicate(({length:J})=>J>0,this._sessions.filter((J)=>J.connectedDevice.id===q)).toEither(new d8)}getDeviceSessions(){return this._sessions}};J9=cX([R(),pX(0,j(y.LoggerPublisherServiceFactory))],J9);var{defineProperty:nX,getOwnPropertyDescriptor:iX}=Object,aX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?iX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&nX(J,Z,$),$},VW=(q,J)=>(Z,Q)=>J(Z,Q,q),Z9=class{_sessionService;_transportService;constructor(q,J){this._sessionService=q,this._transportService=J}execute(){let q=this._sessionService.getDeviceSessions();for(let J of q)this._transportService.closeConnection(J.connectedDevice),this._sessionService.removeDeviceSession(J.id)}};Z9=aX([R(),VW(0,j(u.DeviceSessionService)),VW(1,j(K0.TransportService))],Z9);var{defineProperty:oX,getOwnPropertyDescriptor:rX}=Object,tX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?rX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&oX(J,Z,$),$},BW=(q,J)=>(Z,Q)=>J(Z,Q,q),Q9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("GetDeviceSessionStateUseCase")}execute({sessionId:q}){return this._sessionService.getDeviceSessionById(q).caseOf({Left:(J)=>{throw this._logger.error("Error getting session device",{data:{error:J}}),J},Right:(J)=>J.state})}};Q9=tX([R(),BW(0,j(u.DeviceSessionService)),BW(1,j(y.LoggerPublisherServiceFactory))],Q9);var{defineProperty:eX,getOwnPropertyDescriptor:qF}=Object,JF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?qF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&eX(J,Z,$),$},DW=(q,J)=>(Z,Q)=>J(Z,Q,q),$9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("UnsafeBypassIntentQueueUseCase")}execute({sessionId:q,bypass:J}){this._sessionService.getDeviceSessionById(q).caseOf({Left:(Z)=>{throw this._logger.error("Error getting session",{data:{error:Z}}),Z},Right:(Z)=>{this._logger.warn(`UNSAFE: ${J?"Enabling":"Disabling"} intent queue bypass for session ${q}`),Z._unsafeBypassIntentQueue(J)}})}};$9=JF([R(),DW(0,j(u.DeviceSessionService)),DW(1,j(y.LoggerPublisherServiceFactory))],$9);var UW=({stub:q}={stub:!1})=>new X0(({bind:J,rebindSync:Z})=>{J(u.ApduSenderServiceFactory).toFactory((Q)=>{let $=Q.get(y.LoggerPublisherServiceFactory);return(W)=>new fq(W,$)}),J(u.ApduReceiverServiceFactory).toFactory((Q)=>{let $=Q.get(y.LoggerPublisherServiceFactory);return(W={})=>new Mq(W,$)}),J(u.DeviceSessionService).to(J9).inSingletonScope(),J(u.GetDeviceSessionStateUseCase).to(Q9),J(u.CloseSessionsUseCase).to(Z9),J(u.DisableDeviceSessionRefresherUseCase).to(q9),J(u.UnsafeBypassIntentQueueUseCase).to($9),q&&(Z(u.GetDeviceSessionStateUseCase).to(W0),Z(u.DisableDeviceSessionRefresherUseCase).to(W0),Z(u.UnsafeBypassIntentQueueUseCase).to(W0))});import{BehaviorSubject as HF,from as PW,lastValueFrom as EW,timeout as xW}from"rxjs";function KW(q){return`[will send APDU] ~...> ${B0(q,!1)}`}function ZF(q){return`[exchange] => ${B0(q,!1)}`}function jW(q){return`[exchange] <= ${B0(q.data,!1)}${B0(q.statusCode,!1)}`}var QF="apdu-exchange";function IW(q,J,Z){let Q=B0(J,!1),$=`${B0(Z.data,!1)}${B0(Z.statusCode,!1)}`;return{message:jW(Z),data:{type:QF,sessionId:q,apdu:Q,response:$}}}var E6=1000,W9=1000,LW={isRefresherDisabled:!1,pollingInterval:1000};import{finalize as WF,Subject as YF}from"rxjs";import{Subject as $F}from"rxjs";var Z0=((q)=>(q.NEW_STATE="NEW_STATE",q.REFRESH_NEEDED="REFRESH_NEEDED",q.COMMAND_SUCCEEDED="COMMAND_SUCCEEDED",q.DEVICE_STATE_UPDATE_BUSY="DEVICE_STATE_UPDATE_BUSY",q.DEVICE_STATE_UPDATE_LOCKED="DEVICE_STATE_UPDATE_LOCKED",q.DEVICE_STATE_UPDATE_CONNECTED="DEVICE_STATE_UPDATE_CONNECTED",q.DEVICE_STATE_UPDATE_UNKNOWN="DEVICE_STATE_UPDATE_UNKNOWN",q))(Z0||{});class E5{_eventEmitter=new $F;listen(){return this._eventEmitter.asObservable()}dispatch(q){this._eventEmitter.next(q)}}class x5{constructor(q,J){this.loggerModuleFactory=q,this.sessionEventDispatcher=J,this._logger=this.loggerModuleFactory("IntentQueueService")}_logger;_queue=[];_isProcessing=!1;_currentSubscription=null;enqueue(q){this._logger.debug("Enqueueing intent",{data:{type:q.type}});let J=new YF,Z={intent:q,subject:J,isCancelled:!1};this._queue.push(Z);let Q=()=>{this._logger.debug("Cancelling intent",{data:{type:q.type}}),Z.isCancelled=!0,this._queue[0]===Z&&this._currentSubscription?(this._currentSubscription.unsubscribe(),this._currentSubscription=null,J.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue()):(!this._isProcessing||this._queue[0]!==Z)&&J.complete()};return this._isProcessing||this._processQueue(),{observable:J.asObservable().pipe(WF(()=>{this._logger.debug("Intent observable finalized",{data:{type:q.type}})})),cancel:Q}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:Z0.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:Z0.DEVICE_STATE_UPDATE_BUSY}),this._isProcessing=!0;let q=this._queue[0];if(q.isCancelled){this._logger.debug("Skipping cancelled intent",{data:{type:q.intent.type}}),q.subject.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue();return}this._logger.debug("Processing intent",{data:{type:q.intent.type}}),this._currentSubscription=q.intent.execute().subscribe({next:(J)=>{q.isCancelled||q.subject.next(J)},error:(J)=>{q.isCancelled||q.subject.error(J),this._onIntentComplete()},complete:()=>{q.isCancelled||q.subject.complete(),this._onIntentComplete()}})}_onIntentComplete(){this._logger.debug("Intent completed"),this._currentSubscription=null,this._queue.shift(),this._isProcessing=!1,this._processQueue()}}class k5{constructor(q,J){this._refresher=J,this._logger=q("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(q){let J=`${q}-${R1()}`;this.addRefresherBlocker(J),this._logger.debug("Refresher disabled",{data:{blockerId:J,blockers:Array.from(this._refresherBlockers)}});let Z=!1;return()=>{Z||(Z=!0,this.removeRefresherBlocker(J),this._logger.debug("Refresher re-enabled",{data:{blockerId:J,blockers:Array.from(this._refresherBlockers)}}))}}addRefresherBlocker(q){let J=this._refresherBlockers.size;this._refresherBlockers.add(q),J===0&&this._refresher.stop()}removeRefresherBlocker(q){let J=this._refresherBlockers.size;this._refresherBlockers.delete(q),J>0&&this._refresherBlockers.size===0&&this._refresher.start()}}class O5{constructor(q,J,Z,Q){this.connectedDevice=J,this._sessionEventDispatcher=Z,this._sendCommandFunction=Q,this._logger=q("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async($)=>await this.mapEventAction($))}_sendCommandFunction;_subscription;_logger;async ping(){try{return await this.mapDevicePingAction(this.connectedDevice.deviceModel.id)}catch(q){return this._logger.error("Error while pinging device",{data:{error:q}}),null}}mapEventAction=async(q)=>{switch(q.eventName){case Z0.REFRESH_NEEDED:return await this.ping();default:return null}};async mapDevicePingAction(q){switch(q){case o.NANO_S:{let J=async()=>{let $=await this._sendCommandFunction(new i0,g8);return this._sendCommandFunction(new T0,g8),$},Z=new Promise(($)=>{setTimeout(()=>$(null),E6*2+100)}),Q=await Promise.race([J(),Z]);return Q?this._sessionEventDispatcher.dispatch({eventName:Z0.COMMAND_SUCCEEDED,eventData:Q}):this._sessionEventDispatcher.dispatch({eventName:Z0.DEVICE_STATE_UPDATE_LOCKED}),Q}default:{let J=await this._sendCommandFunction(new i0,g8);return this._sessionEventDispatcher.dispatch({eventName:Z0.COMMAND_SUCCEEDED,eventData:J}),J}}}unsubscribe(){this._subscription.unsubscribe()}}import{distinctUntilChanged as zF,filter as AW,map as wF,startWith as XF,tap as RW,timer as FF,withLatestFrom as _F}from"rxjs";class C5{constructor(q,J,Z,Q){this._sessionEventDispatcher=Z,this._refresherOptions=J,this._logger=q("device-session-refresher"),this._connectedDeviceID=Q.deviceModel.id}_refresherSubscription;_refresherOptions;_logger;_connectedDeviceID;startRefresher(){if(this._refresherOptions.isRefresherDisabled||this._refresherSubscription)return;let q=this.getValidPollingInterval(this._refresherOptions,this._logger),J=this._sessionEventDispatcher.listen().pipe(AW((Z)=>Z.eventName===Z0.DEVICE_STATE_UPDATE_BUSY||Z.eventName===Z0.NEW_STATE),wF((Z)=>Z.eventName===Z0.DEVICE_STATE_UPDATE_BUSY),XF(!1),zF());this._refresherSubscription=FF(0,q).pipe(_F(J),RW(([Z,Q])=>{Q&&this._logger.debug("Refresh skipped: device is busy")}),AW(([Z,Q])=>!Q),RW(()=>this._sessionEventDispatcher.dispatch({eventName:Z0.REFRESH_NEEDED}))).subscribe(),this._logger.info("Refresher started.")}stopRefresher(){this._refresherSubscription&&(this._refresherSubscription.unsubscribe(),this._refresherSubscription=void 0,this._logger.info("Refresher stopped."))}restartRefresher(){this.stopRefresher(),this.startRefresher(),this._logger.info("Refresher restarted.")}getValidPollingInterval=(q,J)=>{let{pollingInterval:Z}=q;switch(this._connectedDeviceID){case o.NANO_S:{let Q=E6*2;return Z!==void 0&&Z<Q?(J.warn(`Polling interval of ${Z} is too low, setting to minimum as ${Q}`),Q):Z??Q}default:return Z!==void 0&&Z<W9?(J.warn(`Polling interval of ${Z} is too low, setting to minimum as ${W9}`),W9):Z??E6}}}class b5{constructor(q,J,Z,Q,$){this._sessionEventDispatcher=J,this._connectedDevice=Z,this._deviceState=Q,this.setDeviceSessionState=$,this._subscription=this._sessionEventDispatcher.listen().subscribe((W)=>this.mapEventAction(W)),this._logger=q("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=u0.BUSY;_updateDeviceState(q){let J=this._parseDeviceStatus(q);if(J){let{sessionStateType:Z,deviceStatus:Q,currentApp:$}=J,W=this._deviceState.getValue();W.sessionStateType===d.Connected?this.setDeviceSessionState({sessionStateType:Z,deviceStatus:Q,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:$,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...W,sessionStateType:Z,deviceStatus:Q,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:$})}}mapEventAction=(q)=>{let{eventName:J}=q;switch(J){case Z0.COMMAND_SUCCEEDED:return this._updateDeviceState(q.eventData);case Z0.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:u0.BUSY});case Z0.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=u0.LOCKED;return;case Z0.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=u0.CONNECTED;return;case Z0.NEW_STATE:{let Z=this._pendingDeviceStatus;return this._pendingDeviceStatus=u0.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Z})}case Z0.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:u0.BUSY});case Z0.REFRESH_NEEDED:return;default:throw Error(`Unhandled context type ${J}`)}};_parseDeviceStatus(q){return n(q)?{sessionStateType:d.ReadyWithoutSecureChannel,deviceStatus:u0.CONNECTED,currentApp:{name:q.data.name,version:q.data.version}}:(this._logger.debug("Error while parsing APDU response",{data:{parsedResponse:q}}),null)}unsubscribe(){this._subscription.unsubscribe()}}class x6{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new E5;_bypassIntentQueue=!1;constructor({connectedDevice:q,id:J=R1()},Z,Q,$,W,Y=(z)=>new x5(Z,z)){this._id=J,this._connectedDevice=q,this._loggerModuleFactory=Z,this._logger=Z("device-session"),this._managerApiService=Q,this._intentQueueService=Y(this._sessionEventDispatcher),this._secureChannelService=$,this._refresherOptions={...LW,...W},this._deviceState=new HF({sessionStateType:d.Connected,deviceStatus:u0.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new O5(Z,q,this._sessionEventDispatcher,(z,X)=>this.sendCommand(z,X)),this._deviceSessionRefresher=new C5(Z,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new b5(Z,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,(z)=>this.setDeviceSessionState(z)),this._refresherService=new k5(Z,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{this._refresherOptions.isRefresherDisabled?await this._pinger.ping():this._deviceSessionRefresher.startRefresher()}catch(q){throw this._logger.error("Error while initialising session",{data:{error:q}}),q}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(q){this._deviceState.next(q)}sendApdu(q,J={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._bypassIntentQueue?this._unsafeInternalSendApdu(q,J):this._internalSendApdu(q,J)}_internalSendApdu(q,J){let Z=J.abortTimeout,Q=Date.now(),{observable:$,cancel:W}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>PW((async()=>{let z=Date.now()-Q;return await this._unsafeInternalSendApdu(q,{isPolling:J.isPolling,triggersDisconnection:J.triggersDisconnection,abortTimeout:Z?Z-z:void 0})})())}),Y=Z?$.pipe(xW({each:Z,with:()=>{throw W(),new TJ}})):$;return EW(Y)}async _unsafeInternalSendApdu(q,J={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(KW(q)),(await this._connectedDevice.sendApdu(q,J.triggersDisconnection,J.abortTimeout)).ifRight((Z)=>{let{message:Q,data:$}=IW(this._id,q,Z);this._logger.debug(Q,{data:$}),m.isLockedDeviceResponse(Z)?this._sessionEventDispatcher.dispatch({eventName:Z0.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:Z0.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:Z0.DEVICE_STATE_UPDATE_UNKNOWN})})}sendCommand(q,J){return this._logger.debug(`[sendCommand] ${q.name}`),this._bypassIntentQueue?this._unsafeInternalSendCommand(q,J):this._internalSendCommand(q,J)}_internalSendCommand(q,J){let Z=Date.now(),{observable:Q,cancel:$}=this._intentQueueService.enqueue({type:"send-command",execute:()=>PW((async()=>{let Y=Date.now()-Z;return await this._unsafeInternalSendCommand(q,J?J-Y:void 0)})())}),W=J?Q.pipe(xW({each:J,with:()=>{throw $(),new MJ}})):Q;return EW(W)}async _unsafeInternalSendCommand(q,J){let Z=q.getApdu();return(await this._unsafeInternalSendApdu(Z.getRawApdu(),{isPolling:!1,triggersDisconnection:q.triggersDisconnection??!1,abortTimeout:J})).caseOf({Left:(Q)=>{throw this._logger.error("[sendCommand] error",{data:{err:Q}}),Q},Right:(Q)=>{let $=q.parseResponse(Q,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:$}}),$}})}executeDeviceAction(q){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(q):this._internalExecuteDeviceAction(q)}_internalExecuteDeviceAction(q){let J,{observable:Z,cancel:Q}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{let{observable:$,cancel:W}=this._unsafeInternalExecuteDeviceAction(q);return J=W,$}});return{observable:Z,cancel:()=>{J?.(),Q()}}}_unsafeInternalExecuteDeviceAction(q){let{observable:J,cancel:Z}=q._execute({sendApdu:async(Q)=>this._unsafeInternalSendApdu(Q),sendCommand:async(Q)=>this._unsafeInternalSendCommand(Q),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:(Q)=>(this.setDeviceSessionState(Q),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:J,cancel:Z}}close(){this._updateDeviceStatus(u0.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher(),this._pinger.unsubscribe()}disableRefresher(q){return this._refresherService.disableRefresher(q)}_unsafeBypassIntentQueue(q){this._bypassIntentQueue=q}_updateDeviceStatus(q){let J=this._deviceState.getValue();this._deviceState.next({...J,deviceStatus:q})}}var X1={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")};var{defineProperty:GF,getOwnPropertyDescriptor:NF}=Object,VF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?NF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&GF(J,Z,$),$},k6=(q,J)=>(Z,Q)=>J(Z,Q,q),Y9=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(q,J,Z,Q,$){this._sessionService=J,this._transportService=q,this._loggerFactory=Z,this._logger=Z("ConnectUseCase"),this._managerApi=Q,this._secureChannel=$}handleDeviceDisconnect(q){this._sessionService.getDeviceSessionsByDeviceId(q).ifRight((J)=>{J.forEach((Z)=>{this._sessionService.removeDeviceSession(Z.id),this._logger.info("Session removed",{data:{deviceId:q,sessionId:Z.id}})})})}async execute({device:q,sessionRefresherOptions:J}){let Z=this._transportService.getTransport(q.transport),Q="sessionId"in q?q.sessionId:void 0;return S.liftEither(Z.toEither(new o1(Error("Unknown transport")))).chain(async($)=>$.connect({deviceId:q.id,onDisconnect:(W)=>this.handleDeviceDisconnect(W)})).ifLeft(($)=>{this._logger.error("Error connecting to device")}).map(async($)=>{let W=new x6({connectedDevice:$,id:Q},this._loggerFactory,this._managerApi,this._secureChannel,J);return this._sessionService.addDeviceSession(W),await W.initialiseSession(),W.id}).caseOf({Left:($)=>{throw $},Right:($)=>$})}};Y9=VF([R(),k6(0,j(K0.TransportService)),k6(1,j(u.DeviceSessionService)),k6(2,j(y.LoggerPublisherServiceFactory)),k6(3,j(x0.ManagerApiService)),k6(4,j(X1.SecureChannelService))],Y9);var{defineProperty:BF,getOwnPropertyDescriptor:DF}=Object,UF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?DF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&BF(J,Z,$),$},T5=(q,J)=>(Z,Q)=>J(Z,Q,q),z9=class{_transportService;_sessionService;_logger;constructor(q,J,Z){this._sessionService=J,this._transportService=q,this._logger=Z("DisconnectUseCase")}async execute({sessionId:q}){return this._logger.debug("Disconnecting from device",{data:{test:this._sessionService.getDeviceSessions().map((J)=>J.id)}}),S(async({liftEither:J})=>{let Z=await J(this._sessionService.getDeviceSessionById(q).ifLeft((W)=>{this._logger.error("Device session not found",{data:{sessionId:q,error:W}})})),Q=Z.connectedDevice.transport,$=await J(this._transportService.getTransport(Q).toEither(new o1(Error("Unknown transport"))));Z.close(),this._sessionService.removeDeviceSession(q),await $.disconnect({connectedDevice:Z.connectedDevice})}).caseOf({Left:(J)=>{throw this._logger.error("Error disconnecting from device",{data:{error:J}}),J},Right:()=>{}})}};z9=UF([R(),T5(0,j(K0.TransportService)),T5(1,j(u.DeviceSessionService)),T5(2,j(y.LoggerPublisherServiceFactory))],z9);class m1{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:q,deviceModel:{id:J,productName:Z},type:Q,transport:$,name:W},sessionId:Y}){this.id=q,this.sessionId=Y,this.modelId=J,this.name=W??Z,this.type=Q,this.transport=$}}var{defineProperty:KF,getOwnPropertyDescriptor:jF}=Object,IF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?jF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&KF(J,Z,$),$},kW=(q,J)=>(Z,Q)=>J(Z,Q,q),w9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("GetConnectedDeviceUseCase")}execute({sessionId:q}){return this._sessionService.getDeviceSessionById(q).caseOf({Right:(J)=>new m1({sessionId:J.id,transportConnectedDevice:J.connectedDevice}),Left:(J)=>{throw this._logger.error("Error getting session",{data:{error:J}}),J}})}};w9=IF([R(),kW(0,j(u.DeviceSessionService)),kW(1,j(y.LoggerPublisherServiceFactory))],w9);var{defineProperty:LF,getOwnPropertyDescriptor:AF}=Object,RF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?AF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&LF(J,Z,$),$},OW=(q,J)=>(Z,Q)=>J(Z,Q,q),X9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("ListConnectedDeviceUseCase")}execute(){return this._logger.info("Listing connected devices"),this._sessionService.getDeviceSessions().map((q)=>new m1({transportConnectedDevice:q.connectedDevice,sessionId:q.id}))}};X9=RF([R(),OW(0,j(u.DeviceSessionService)),OW(1,j(y.LoggerPublisherServiceFactory))],X9);import{from as kF,map as M5,merge as OF,of as CF,scan as bF}from"rxjs";var{defineProperty:PF,getOwnPropertyDescriptor:EF}=Object,xF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?EF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&PF(J,Z,$),$},CW=(q,J)=>(Z,Q)=>J(Z,Q,q),F9=class{_transports;_transportService;_logger;constructor(q,J){this._transports=q.getAllTransports(),this._transportService=q,this._logger=J("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(q){let J=new Hq({id:q.id,model:q.deviceModel.id,name:q.deviceModel.productName});return{id:q.id,deviceModel:J,transport:q.transport,name:q.name||J.name,rssi:q.rssi}}execute({transport:q}={}){if(this._logger.info("Listening to available devices"),this._transports.length===0)return this._logger.warn("No transports available"),kF([[]]);if(!q){this._logger.info("Discovering all available transports");let J=this._transports.map((Z,Q)=>Z.listenToAvailableDevices().pipe(M5(($)=>({index:Q,arr:$}))));return OF(...J).pipe(bF((Z,{index:Q,arr:$})=>(Z[Q]=$,Z),{}),M5((Z)=>Object.values(Z).flat().map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))}return this._logger.info(`Discovering devices on transport ${q}`),this._transportService.getTransport(q).caseOf({Nothing:()=>(this._logger.error(`Transport ${q} not found`),CF([])),Just:(J)=>J.listenToAvailableDevices().pipe(M5((Z)=>Z.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};F9=xF([R(),CW(0,j(K0.TransportService)),CW(1,j(y.LoggerPublisherServiceFactory))],F9);import{map as SF}from"rxjs";var{defineProperty:TF,getOwnPropertyDescriptor:MF}=Object,fF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?MF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&TF(J,Z,$),$},bW=(q,J)=>(Z,Q)=>J(Z,Q,q),_9=class{constructor(q,J){this._sessionService=q,this._logger=J("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(SF((q)=>new m1({transportConnectedDevice:q.connectedDevice,sessionId:q.id})))}};_9=fF([R(),bW(0,j(u.DeviceSessionService)),bW(1,j(y.LoggerPublisherServiceFactory))],_9);var{defineProperty:hF,getOwnPropertyDescriptor:vF}=Object,yF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?vF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&hF(J,Z,$),$},f5=(q,J)=>(Z,Q)=>J(Z,Q,q),H9=class{constructor(q,J,Z){this.connectUseCase=q,this.disconnectUseCase=J,this._logger=Z("ReconnectUseCase")}_logger;async execute({device:q,sessionRefresherOptions:J}){return this._logger.debug("Reconnecting device session",{data:{deviceId:q.id,transport:q.transport}}),await this.disconnectUseCase.execute({sessionId:q.sessionId}),this.connectUseCase.execute({device:q,sessionRefresherOptions:J})}};H9=yF([R(),f5(0,j(r.ConnectUseCase)),f5(1,j(r.DisconnectUseCase)),f5(2,j(y.LoggerPublisherServiceFactory))],H9);import{map as TW,mergeMap as dF,of as cF}from"rxjs";var{defineProperty:uF,getOwnPropertyDescriptor:gF}=Object,mF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?gF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&uF(J,Z,$),$},lF=(q,J)=>(Z,Q)=>J(Z,Q,q),G9=class{constructor(q){this._transportService=q}mapDiscoveredDevice(q){let J=new Hq({id:q.id,model:q.deviceModel.id,name:q.deviceModel.productName});return{id:q.id,deviceModel:J,transport:q.transport,name:q.name||J.name,rssi:q.rssi}}execute({transport:q}={}){if(!q){let J=this._transportService.getAllTransports();return cF(...J).pipe(dF((Z)=>Z.startDiscovering().pipe(TW((Q)=>this.mapDiscoveredDevice(Q)))))}return this._transportService.getTransport(q).caseOf({Just:(J)=>J.startDiscovering().pipe(TW((Z)=>this.mapDiscoveredDevice(Z))),Nothing:()=>{throw new o1(Error("Unknown transport"))}})}};G9=mF([R(),lF(0,j(K0.TransportService))],G9);var{defineProperty:pF,getOwnPropertyDescriptor:sF}=Object,nF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?sF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&pF(J,Z,$),$},MW=(q,J)=>(Z,Q)=>J(Z,Q,q),N9=class{constructor(q,J){this.transportService=q,this._logger=J("StopDiscoveringUseCase")}_logger;async execute(){this._logger.debug("Stopping discovering devices");for(let q of this.transportService.getAllTransports())await q.stopDiscovering()}};N9=nF([R(),MW(0,j(K0.TransportService)),MW(1,j(y.LoggerPublisherServiceFactory))],N9);var fW=({stub:q=!1})=>new X0(({bind:J,rebindSync:Z})=>{J(r.ConnectUseCase).to(Y9),J(r.DisconnectUseCase).to(z9),J(r.ReconnectUseCase).to(H9),J(r.StartDiscoveringUseCase).to(G9),J(r.StopDiscoveringUseCase).to(N9),J(r.GetConnectedDeviceUseCase).to(w9),J(r.ListenToAvailableDevicesUseCase).to(F9),J(r.ListenToConnectedDeviceUseCase).to(_9),J(r.ListConnectedDevicesUseCase).to(X9),q&&(Z(r.ConnectUseCase).to(W0),Z(r.DisconnectUseCase).to(W0),Z(r.StartDiscoveringUseCase).to(W0),Z(r.StopDiscoveringUseCase).to(W0),Z(r.GetConnectedDeviceUseCase).to(W0),Z(r.ListenToAvailableDevicesUseCase).to(W0),Z(r.ListenToConnectedDeviceUseCase).to(W0),Z(r.ListConnectedDevicesUseCase).to(W0))});var j0=((q)=>(q[q.Fatal=0]="Fatal",q[q.Error=1]="Error",q[q.Warning=2]="Warning",q[q.Info=3]="Info",q[q.Debug=4]="Debug",q))(j0||{});class V9{format(q){return Array.isArray(q)?q.map((J)=>`[${J}]`).join(" "):`[${q}]`}}function S5(q,J){if(typeof q=="bigint")return q.toString();if(Array.isArray(q))return J.has(q)?"[Circular]":(J.add(q),q.map((Z)=>S5(Z,J)));if(q!==null&&typeof q=="object"){if(J.has(q))return"[Circular]";J.add(q);let Z={};for(let[Q,$]of Object.entries(q))Z[Q]=S5($,J);return Z}return q}function SW(q){let J=new WeakSet;J.add(q);let Z={};for(let[Q,$]of Object.entries(q))Z[Q]=S5($,J);return Z}var{defineProperty:iF,getOwnPropertyDescriptor:aF}=Object,oF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?aF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&iF(J,Z,$),$},B9=class{subscribers;tag;tagFormatter;constructor(q,J,Z=new V9){this.subscribers=q,this.tag=J,this.tagFormatter=Z}_log(q,J,Z){let Q=Z?.data?SW(Z.data):void 0,$=Z?.tag??this.tag,W=this.tagFormatter.format($);this.subscribers.forEach((Y)=>{let z={timestamp:Z?.timestamp??Date.now(),tag:W,data:Q};Y.log(q,J,z)})}info(q,J){this._log(j0.Info,q,J)}warn(q,J){this._log(j0.Warning,q,J)}debug(q,J){this._log(j0.Debug,q,J)}error(q,J){this._log(j0.Error,q,J)}};B9=oF([R()],B9);var hW=({subscribers:q}={subscribers:[]})=>new X0(({bind:J})=>{J(y.LoggerPublisherServiceFactory).toFactory((Z)=>(Q)=>new B9(q,Q))});class F1 extends Error{status;statusText;responseBody;isTimeout;cause;constructor(q){super(q.message),this.name="DmkNetworkClientError",this.status=q.status,this.statusText=q.statusText,this.responseBody=q.responseBody,this.isTimeout=q.isTimeout??!1,this.cause=q.cause}}var rF="application/json";function tF(q,J){if(!J)return q;let Z=q.endsWith("/")?q.slice(0,-1):q,Q=J.startsWith("/")?J:`/${J}`;return`${Z}${Q}`}function eF(q){let J=[];for(let[Z,Q]of Object.entries(q))Q!=null&&J.push(`${encodeURIComponent(Z)}=${encodeURIComponent(String(Q))}`);return J.join("&")}function P1(q){let{url:J,params:Z,baseUrl:Q}=q,$=/^[a-z][a-z0-9+.-]*:\/\//i.test(J)?J:Q?tF(Q,J):J,W=Z?eF(Z):"";if(W.length===0)return $;let Y=$.includes("?")?"&":"?";return`${$}${Y}${W}`}function q_(q,J){let Z=J.toLowerCase();return Object.keys(q).some((Q)=>Q.toLowerCase()===Z)}function J_(q){return!!(typeof q=="string"||q instanceof ArrayBuffer||ArrayBuffer.isView(q)||typeof Blob<"u"&&q instanceof Blob||typeof FormData<"u"&&q instanceof FormData||typeof URLSearchParams<"u"&&q instanceof URLSearchParams||typeof ReadableStream<"u"&&q instanceof ReadableStream)}function vW(q){let{method:J,body:Z,defaultHeaders:Q,perRequestHeaders:$}=q,W={...Q,...$};return Z===void 0||J==="GET"||J==="HEAD"?{body:void 0,headers:W}:J_(Z)?{body:Z,headers:W}:(q_(W,"content-type")||(W["Content-Type"]=rF),{body:JSON.stringify(Z),headers:W})}function yW(q){let{timeoutMs:J}=q;if(!J||J<=0)return{signal:void 0,cleanup:()=>{}};let Z=new AbortController,Q=setTimeout(()=>{Z.abort()},J);return{signal:Z.signal,cleanup:()=>clearTimeout(Q)}}async function uW(q,J){switch(J){case"void":return;case"text":return await q.text();case"blob":return await q.blob();case"arrayBuffer":return await q.arrayBuffer();case"json":default:{let Z=await q.text();if(Z.length===0)return;try{return JSON.parse(Z)}catch(Q){throw new F1({message:"Failed to parse JSON response body",status:q.status,statusText:q.statusText,responseBody:Z,cause:Q})}}}}async function gW(q){try{return await q.text()}catch{return}}function mW(q){let{cause:J,timeoutMs:Z}=q,Q=!!(Z&&Z>0);if(J instanceof Error&&(J.name==="AbortError"||J.name==="TimeoutError")){let $=J.name==="TimeoutError"||Q;return new F1({message:$?"Request timed out":"Request aborted",isTimeout:$,cause:J})}return new F1({message:J instanceof Error?J.message:"Network request failed",cause:J})}class D9{baseUrl;defaultHeaders;fetchImpl;constructor(q={}){this.baseUrl=q.baseUrl,this.defaultHeaders=q.headers??{},this.fetchImpl=q.fetch}getFetch(){return this.fetchImpl??globalThis.fetch.bind(globalThis)}get(q,J){return this.request({...J,method:"GET",url:q}).then((Z)=>Z.data)}post(q,J,Z){return this.request({...Z,method:"POST",url:q,body:J}).then((Q)=>Q.data)}put(q,J,Z){return this.request({...Z,method:"PUT",url:q,body:J}).then((Q)=>Q.data)}patch(q,J,Z){return this.request({...Z,method:"PATCH",url:q,body:J}).then((Q)=>Q.data)}delete(q,J){return this.request({...J,method:"DELETE",url:q}).then((Z)=>Z.data)}head(q,J){return this.request({...J,method:"HEAD",url:q,responseType:"void"}).then(()=>{})}async request(q){let J=P1({url:q.url,params:q.params,baseUrl:this.baseUrl}),{body:Z,headers:Q}=vW({method:q.method,body:q.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:q.headers}),{signal:$,cleanup:W}=yW({timeoutMs:q.timeoutMs}),Y=q.throwOnHttpError??!0,z=q.responseType??"json";try{let X;try{X=await this.getFetch()(J,{method:q.method,headers:Q,body:Z,signal:$})}catch(w){throw mW({cause:w,timeoutMs:q.timeoutMs})}if(!X.ok&&Y){let w=await gW(X);throw new F1({message:`HTTP error ${X.status} ${X.statusText}`.trim(),status:X.status,statusText:X.statusText,responseBody:w})}return{data:await uW(X,z),status:X.status,statusText:X.statusText,headers:X.headers,ok:X.ok}}finally{W()}}}var Sq=((q)=>(q.currency="currency",q.plugin="plugin",q.tool="tool",q.swap="swap",q))(Sq||{});var U9="https://manager.api.live.ledger.com/api",K9="https://device-mock-server.aws.ldg-ps-default.ldg-tech.com",hq=1,vq="0";class Zq{constructor(q){this.error=q,this.originalError=q}_tag="FetchError";originalError}var yq=((q)=>(q.currency="currency",q.plugin="plugin",q.tool="tool",q.swap="swap",q))(yq||{});var{defineProperty:Z_,getOwnPropertyDescriptor:Q_}=Object,$_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?Q_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&Z_(J,Z,$),$},W_=(q,J)=>(Z,Q)=>J(Z,Q,q),E1=(q)=>q instanceof F1&&q.cause!==void 0?new Zq(q.cause):new Zq(q),j9=class{http;_provider=hq;_firmwareDistributionSalt=vq;constructor({managerApiUrl:q,provider:J,firmwareDistributionSalt:Z}){this.http=new D9({baseUrl:q}),this._provider=J,this._firmwareDistributionSalt=Z}setProvider(q){this._provider===q||q<1||(this._provider=q)}getProvider(){return this._provider}getAppList(q){let{targetId:J,firmwareVersionName:Z}=q;return S(()=>this.http.get("/v2/apps/by-target",{params:{target_id:J,provider:this._provider,firmware_version_name:Z}})).chain((Q)=>this.mapApplicationDtoToApplication(Q)).mapLeft(E1)}getMcuList(){return S(()=>this.http.get("/mcu_versions")).chain((q)=>this.mapMcuDtoToMcu(q)).mapLeft(E1)}getDeviceVersion(q){let{targetId:J}=q;return S(()=>this.http.get("/get_device_version",{params:{target_id:J,provider:this._provider}})).chain((Z)=>this.mapDeviceVersionDto(Z)).mapLeft(E1)}getFirmwareVersion(q){let{deviceId:J,version:Z}=q;return S(()=>this.http.get("/get_firmware_version",{params:{device_version:J,version_name:Z,provider:this._provider}})).chain((Q)=>this.mapFinalFirmwareDto(Q)).mapLeft(E1)}getFirmwareVersionById(q){return S(()=>this.http.get(`/firmware_final_versions/${q}`)).chain((J)=>this.mapFinalFirmwareDto(J)).mapLeft(E1)}getOsuFirmwareVersion(q){let{deviceId:J,version:Z}=q;return S(()=>this.http.get("/get_osu_version",{params:{device_version:J,version_name:Z,provider:this._provider}})).chain((Q)=>this.mapOsuFirmwareDto(Q)).mapLeft(E1)}getLatestFirmwareVersion(q){let{currentFinalFirmwareId:J,deviceId:Z}=q;return S(()=>this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:J,device_version:Z,provider:this._provider,salt:this._firmwareDistributionSalt}})).chain((Q)=>this.mapLatestFirmwareDto(Q)).mapLeft(E1)}getAppsByHash(q){let{hashes:J}=q;return S(()=>this.http.post("/v2/apps/hash",J)).chain((Z)=>this.mapNullableApplicationDtoToApplication(Z)).mapLeft(E1)}getLanguagePackages(q){let{deviceId:J,currentFinalFirmwareId:Z}=q;return S(()=>this.http.get("/language-packages",{params:{device_version:J,current_se_firmware_final_version:Z}})).chain((Q)=>this.mapLanguagesDtoToLanguages(Q)).mapLeft(E1)}mapAppTypeDtoToAppType(q){if(q===null)return null;switch(q){case yq.currency:return Sq.currency;case yq.plugin:return Sq.plugin;case yq.tool:return Sq.tool;case yq.swap:return Sq.swap}}mapApplicationDtoToApplication(q){return S(()=>Promise.resolve(q.map((J)=>this.mapApplicationDto(J))))}mapNullableApplicationDtoToApplication(q){return S(()=>Promise.resolve(q.map((J)=>J===null?null:this.mapApplicationDto(J))))}mapApplicationDto(q){if(typeof q!="object"||typeof q.versionId!="number"||typeof q.versionName!="string"||q.versionDisplayName!==null&&typeof q.versionDisplayName!="string"||typeof q.version!="string"||q.currencyId!==null&&typeof q.currencyId!="string"||q.description!==null&&typeof q.description!="string"||q.applicationType!==null&&typeof q.applicationType!="string"||typeof q.dateModified!="string"||q.icon!==null&&typeof q.icon!="string"||q.authorName!==null&&typeof q.authorName!="string"||q.supportURL!==null&&typeof q.supportURL!="string"||q.contactURL!==null&&typeof q.contactURL!="string"||q.sourceURL!==null&&typeof q.sourceURL!="string"||q.compatibleWallets!==null&&typeof q.compatibleWallets!="string"||typeof q.hash!="string"||typeof q.perso!="string"||typeof q.firmware!="string"||typeof q.firmwareKey!="string"||typeof q.delete!="string"||typeof q.deleteKey!="string"||q.bytes!==null&&typeof q.bytes!="number"||q.warning!==null&&typeof q.warning!="string"||typeof q.isDevTools!="boolean"||q.category!==null&&typeof q.category!="number"||q.parent!==null&&typeof q.parent!="number"||q.parentName!==null&&typeof q.parentName!="string")throw Error(`Incomplete application: ${JSON.stringify(q)}`);let{applicationType:J,hash:Z,perso:Q,firmware:$,firmwareKey:W,delete:Y,deleteKey:z,...X}=q;return{...X,hash:Z,perso:Q,firmware:$,firmwareKey:W,delete:Y,deleteKey:z,applicationType:this.mapAppTypeDtoToAppType(J)}}mapMcuDtoToMcu(q){return S(()=>Promise.resolve(q.map((J)=>{if(typeof J!="object"||typeof J.id!="number"||typeof J.name!="string"||typeof J.from_bootloader_version!="string")throw Error(`Incomplete MCU version: ${JSON.stringify(J)}`);return{id:J.id,name:J.name,fromBootloaderVersion:J.from_bootloader_version,providers:J.providers}})))}mapDeviceVersionDto(q){return S(()=>{if(typeof q!="object"||typeof q.id!="number")throw Error(`Incomplete device version: ${JSON.stringify(q)}`);let J={id:q.id};return Promise.resolve(J)})}mapFinalFirmwareDto(q){return S(()=>{if(typeof q!="object"||typeof q.id!="number"||typeof q.version!="string"||typeof q.perso!="string"||q.firmware!==null&&typeof q.firmware!="string"||q.firmware_key!==null&&typeof q.firmware_key!="string"||q.hash!==null&&typeof q.hash!="string"||q.bytes!==null&&typeof q.bytes!="number"||!Array.isArray(q.mcu_versions))throw Error(`Incomplete final firmware: ${JSON.stringify(q)}`);let J={id:q.id,version:q.version,perso:q.perso,firmware:q.firmware,firmwareKey:q.firmware_key,hash:q.hash,bytes:q.bytes,mcuVersions:q.mcu_versions};return Promise.resolve(J)})}mapLatestFirmwareDto(q){return S(()=>{if(q.result==="null")return Promise.resolve(null);if(q.result!=="success"||!q.se_firmware_osu_version)throw Error(`Latest firmware could not be retrieved: ${q.result}`);let J=q.se_firmware_osu_version;return Promise.resolve(J)}).chain((J)=>J===null?S(()=>Promise.resolve(p)):this.mapOsuFirmwareDto(J).map((Z)=>I0(Z)))}mapOsuFirmwareDto(q){return S(()=>{if(typeof q!="object"||typeof q.id!="number"||q.notes!==null&&typeof q.notes!="string"||typeof q.perso!="string"||typeof q.firmware!="string"||typeof q.firmware_key!="string"||q.hash!==null&&typeof q.hash!="string"||typeof q.next_se_firmware_final_version!="number")throw Error(`Incomplete latest firmware: ${JSON.stringify(q)}`);let J={id:q.id,notes:q.notes,perso:q.perso,firmware:q.firmware,firmwareKey:q.firmware_key,hash:q.hash,nextFinalFirmware:q.next_se_firmware_final_version};return Promise.resolve(J)})}mapLanguagesDtoToLanguages(q){return S(()=>Promise.resolve(q.map((J)=>this.mapLanguageDto(J))))}mapLanguageDto(q){if(typeof q!="object"||typeof q.language!="string"||typeof q.languagePackageVersionId!="number"||typeof q.version!="string"||typeof q.language_package_id!="number"||typeof q.apdu_install_url!="string"||typeof q.apdu_uninstall_url!="string"||typeof q.bytes!="number"||typeof q.date_creation!="string"||typeof q.date_last_modified!="string")throw Error(`Incomplete language version: ${JSON.stringify(q)}`);return{language:q.language,languagePackageVersionId:q.languagePackageVersionId,version:q.version,languagePackageId:q.language_package_id,apduInstallUrl:q.apdu_install_url,apduUninstallUrl:q.apdu_uninstall_url,bytes:q.bytes,dateCreation:q.date_creation,dateLastModified:q.date_last_modified}}};j9=$_([R(),W_(0,j(x0.DmkConfig))],j9);var{defineProperty:Y_,getOwnPropertyDescriptor:z_}=Object,w_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?z_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&Y_(J,Z,$),$},X_=(q,J)=>(Z,Q)=>J(Z,Q,q),I9=class{constructor(q){this.dataSource=q}getAppList(q){let J={targetId:q.targetId.toString(),firmwareVersionName:q.seVersion};return this.dataSource.getAppList(J)}getDeviceVersion(q){let J={targetId:q.targetId.toString()};return this.dataSource.getDeviceVersion(J)}getFirmwareVersion(q,J){let Z={version:q.seVersion,deviceId:J.id};return this.dataSource.getFirmwareVersion(Z)}getOsuFirmwareVersion(q,J){let Z={version:q.seVersion,deviceId:J.id};return this.dataSource.getOsuFirmwareVersion(Z)}getLatestFirmwareVersion(q,J){let Z={currentFinalFirmwareId:q.id,deviceId:J.id};return this.dataSource.getLatestFirmwareVersion(Z)}getNextFirmwareVersion(q){return this.dataSource.getFirmwareVersionById(q.nextFinalFirmware)}getLanguagePackages(q,J){let Z={deviceId:q.id,currentFinalFirmwareId:J.id};return this.dataSource.getLanguagePackages(Z)}getMcuList(){return this.dataSource.getMcuList()}getAppsByHash(q){let J={hashes:q};return S(async({fromPromise:Z,throwE:Q})=>{if(J.hashes.length===0)return[];try{return await Z(this.dataSource.getAppsByHash(J))}catch($){return $ instanceof Zq?Q($):Q(new Zq($))}})}getProvider(){return this.dataSource.getProvider()}};I9=w_([R(),X_(0,j(x0.ManagerApiDataSource))],I9);var{defineProperty:F_,getOwnPropertyDescriptor:__}=Object,H_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?__(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&F_(J,Z,$),$},lW=(q,J)=>(Z,Q)=>J(Z,Q,q),L9=class{constructor(q,J){this.sessionService=q,this.managerApiDataSource=J}execute(q){for(let J of this.sessionService.getDeviceSessions()){let Z=J.getDeviceSessionState();Z.sessionStateType!==d.Connected&&J.setDeviceSessionState({...Z,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(q)}};L9=H_([R(),lW(0,j(u.DeviceSessionService)),lW(1,j(x0.ManagerApiDataSource))],L9);var dW=({stub:q,config:J})=>new X0(({bind:Z,rebindSync:Q})=>{Z(x0.DmkConfig).toConstantValue(J),Z(x0.ManagerApiDataSource).to(j9).inSingletonScope(),Z(x0.ManagerApiService).to(I9).inSingletonScope(),Z(x0.SetProviderUseCase).to(L9),q&&(Q(x0.ManagerApiDataSource).to(W0),Q(x0.ManagerApiService).to(W0),Q(x0.SetProviderUseCase).to(W0))});var{defineProperty:G_,getOwnPropertyDescriptor:N_}=Object,V_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?N_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&G_(J,Z,$),$},B_=(q,J)=>(Z,Q)=>J(Z,Q,q),A9=class{webSocketBaseUrl;constructor({webSocketUrl:q}){this.webSocketBaseUrl=q}genuineCheck(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:q});return this._connectWebSocket(J)}installApp(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/install",params:q});return this._connectWebSocket(J)}listInstalledApps(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:q});return this._connectWebSocket(J)}uninstallApp(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/install",params:q});return this._connectWebSocket(J)}updateFirmware(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/install",params:q});return this._connectWebSocket(J)}updateMcu(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:q});return this._connectWebSocket(J)}_connectWebSocket(q){try{return I(new L8(q))}catch(J){return K(new iJ(J))}}};A9=V_([R(),B_(0,j(X1.DmkConfig))],A9);var{defineProperty:D_,getOwnPropertyDescriptor:U_}=Object,K_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?U_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&D_(J,Z,$),$},j_=(q,J)=>(Z,Q)=>J(Z,Q,q),R9=class{constructor(q){this.dataSource=q}genuineCheck(q,J){let Z={targetId:q.targetId.toString(),perso:J.perso};return this.dataSource.genuineCheck(Z)}installApp(q,J){let{perso:Z,firmware:Q,firmwareKey:$,hash:W}=J,Y={targetId:q.targetId.toString(),perso:Z,firmware:Q,firmwareKey:$,hash:W};return this.dataSource.installApp(Y)}listInstalledApps(q,J){let Z={targetId:q.targetId.toString(),perso:J.perso};return this.dataSource.listInstalledApps(Z)}uninstallApp(q,J){let{perso:Z,delete:Q,deleteKey:$,hash:W}=J,Y={targetId:q.targetId.toString(),perso:Z,firmware:Q,firmwareKey:$,hash:W};return this.dataSource.uninstallApp(Y)}updateFirmware(q,J){let Z={targetId:q.targetId.toString(),perso:J.perso,firmware:J.firmware,firmwareKey:J.firmwareKey};return this.dataSource.updateFirmware(Z)}updateMcu(q,J){let Z={targetId:q.targetId.toString(),version:J.version};return this.dataSource.updateMcu(Z)}};R9=K_([R(),j_(0,j(X1.SecureChannelDataSource))],R9);var cW=({stub:q,config:J})=>new X0(({bind:Z})=>{Z(X1.DmkConfig).toConstantValue(J),Z(X1.SecureChannelDataSource).to(A9),Z(X1.SecureChannelService).to(R9)});var P9="wss://scriptrunner.api.live.ledger.com/update";var{defineProperty:I_,getOwnPropertyDescriptor:L_}=Object,A_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?L_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&I_(J,Z,$),$},pW=(q,J)=>(Z,Q)=>J(Z,Q,q),E9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("SendApduUseCase")}async execute({sessionId:q,apdu:J,abortTimeout:Z,triggersDisconnection:Q}){return this._sessionService.getDeviceSessionById(q).caseOf({Right:async($)=>(await $.sendApdu(J,{abortTimeout:Z,triggersDisconnection:Q})).caseOf({Right:(W)=>W,Left:(W)=>{throw this._logger.error("Error sending APDU",{data:{sessionId:q,apdu:J,error:W}}),W}}),Left:($)=>{throw this._logger.error("Error getting deviceSession",{data:{error:$}}),$}})}};E9=A_([R(),pW(0,j(u.DeviceSessionService)),pW(1,j(y.LoggerPublisherServiceFactory))],E9);var sW=({stub:q=!1})=>new X0(({bind:J,rebindSync:Z})=>{J(A6.SendApduUseCase).to(E9),q&&Z(A6.SendApduUseCase).to(W0)});var{defineProperty:R_,getOwnPropertyDescriptor:P_}=Object,E_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?P_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&R_(J,Z,$),$},uq=(q,J)=>(Z,Q)=>J(Z,Q,q),x9=class{constructor(q,J,Z,Q,$,W){if(this._config=J,this._loggerModuleFactory=Z,this._deviceModelDataSource=Q,this._apduSenderServiceFactory=$,this._apduReceiverServiceFactory=W,this._logger=Z("TransportService"),q.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new hJ("No transports provided, please check your configuration");for(let Y of q){let z=this.addTransport(Y);if(z.isLeft())throw z.extract()}}_transports=new Map;_logger;addTransport(q){let J=q({deviceModelDataSource:this._deviceModelDataSource,loggerServiceFactory:this._loggerModuleFactory,config:this._config,apduSenderServiceFactory:this._apduSenderServiceFactory,apduReceiverServiceFactory:this._apduReceiverServiceFactory});return this.addTransportInternal(J)}addTransportInternal(q){return this.getTransport(q.getIdentifier()).isJust()?(this._logger.warn(`Transport ${q.getIdentifier()} already exists, please check your configuration`),K(new fJ(`Transport ${q.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(q.getIdentifier(),q),I(void 0))}getTransport(q){return J0.fromNullable(this._transports.get(q))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(q){this.getTransport(q.transport).map((J)=>J.disconnect({connectedDevice:q}))}};x9=E_([R(),uq(0,j(K0.TransportsInput)),uq(1,j(K0.DmkConfig)),uq(2,j(y.LoggerPublisherServiceFactory)),uq(3,j(e8.DeviceModelDataSource)),uq(4,j(u.ApduSenderServiceFactory)),uq(5,j(u.ApduReceiverServiceFactory))],x9);var nW=({stub:q=!1,transports:J=[],config:Z}={})=>new X0(({bind:Q})=>{Q(K0.TransportsInput).toConstantValue(J),Q(K0.TransportService).to(x9).inSingletonScope(),Q(K0.DmkConfig).toConstantValue(Z)});var iW=({stub:q=!1,transports:J=[],loggers:Z=[],config:Q={mockUrl:K9,managerApiUrl:U9,webSocketUrl:P9,provider:hq,firmwareDistributionSalt:vq}})=>{let $=new y8;return $.loadSync(HW({stub:q}),GW({stub:q}),nW({stub:q,transports:J,config:Q}),dW({stub:q,config:Q}),cW({stub:q,config:Q}),fW({stub:q}),hW({subscribers:Z}),UW({stub:q}),sW({stub:q}),wW({stub:q}),FW({stub:q})),$};class k9{container;constructor({stub:q,transports:J,loggers:Z,config:Q}={}){this.container=iW({stub:q,transports:J,loggers:Z,config:Q})}getVersion(){return this.container.get(c0.GetDmkVersionUseCase).getDmkVersion()}startDiscovering(q){return this.container.get(r.StartDiscoveringUseCase).execute(q)}stopDiscovering(){return this.container.get(r.StopDiscoveringUseCase).execute()}listenToAvailableDevices(q){return this.container.get(r.ListenToAvailableDevicesUseCase).execute(q)}async reconnect(q){return this.container.get(r.ReconnectUseCase).execute(q)}connect(q){return this.container.get(r.ConnectUseCase).execute(q)}disconnect(q){return this.container.get(r.DisconnectUseCase).execute(q)}sendApdu(q){return this.container.get(A6.SendApduUseCase).execute(q)}sendCommand(q){return this.container.get(L6.SendCommandUseCase).execute(q)}executeDeviceAction(q){return this.container.get(R6.ExecuteDeviceActionUseCase).execute(q)}getConnectedDevice(q){return this.container.get(r.GetConnectedDeviceUseCase).execute(q)}getDeviceSessionState(q){return this.container.get(u.GetDeviceSessionStateUseCase).execute(q)}close(){return this.container.get(u.CloseSessionsUseCase).execute()}listConnectedDevices(){return this.container.get(r.ListConnectedDevicesUseCase).execute()}listenToConnectedDevice(){return this.container.get(r.ListenToConnectedDeviceUseCase).execute()}disableDeviceSessionRefresher(q){return this.container.get(u.DisableDeviceSessionRefresherUseCase).execute(q)}_unsafeBypassIntentQueue(q){return this.container.get(u.UnsafeBypassIntentQueueUseCase).execute(q)}setProvider(q){return this.container.get(x0.SetProviderUseCase).execute(q)}getProvider(){return this.container.get(x0.ManagerApiDataSource).getProvider()}isEnvironmentSupported(){return this.container.get(K0.TransportService).getAllTransports().some((q)=>q.isSupported())}getLoggerFactory(){return this.container.get(y.LoggerPublisherServiceFactory)}}class aW{stub=!1;loggers=[];transports=[];config={managerApiUrl:U9,mockUrl:K9,webSocketUrl:P9,provider:hq,firmwareDistributionSalt:vq};build(){return new k9({stub:this.stub,transports:this.transports,loggers:this.loggers,config:this.config})}setStub(q){return this.stub=q,this}addTransport(q){return this.transports.push(q),this}addLogger(q){return this.loggers.push(q),this}addConfig(q){return this.config={...this.config,...q},this}}class oW{maxLevel;constructor(q=j0.Debug){this.maxLevel=q}log(q,J,Z){let Q=Z.tag;switch(q){case j0.Info:{this.maxLevel>=j0.Info&&this.logWithData(Q,console.info,J,Z);break}case j0.Warning:{this.maxLevel>=j0.Warning&&this.logWithData(Q,console.warn,J,Z);break}case j0.Debug:{this.maxLevel>=j0.Debug&&this.logWithData(Q,console.debug,J,Z);break}case j0.Error:{this.maxLevel>=j0.Error&&this.logWithData(Q,console.error,J,Z);break}case j0.Fatal:{this.maxLevel>=j0.Fatal&&this.logWithData(Q,console.error,J,Z);break}default:this.logWithData(Q,console.log,J,Z)}}logWithData(q,J,Z,Q){Q.data?J(q,Z,Q.data):J(q,Z)}}function x_(){let q=[];return function(J,Z){if(Z instanceof Uint8Array){let Q=Array.from(Z).map(($)=>$.toString(16).padStart(2,"0"));return{hex:"0x"+Q.join(""),readableHex:Q.join(" "),value:Z.toString()}}if(Z instanceof x6){let{connectedDevice:{deviceModel:Q,type:$,id:W}}=Z;return{id:Z.id,connectedDevice:{deviceModel:Q,type:$,id:W}}}if(typeof Z!="object"||Z===null)return Z;for(;q.length>0&&q.at(-1)!==this;)q.pop();return q.includes(Z)?"[Circular]":(q.push(Z),Z)}}class rW{logs=[];log(q,J,Z){this.logs.push([q,J,Z])}formatLogsToJSON(){let q=this.logs.map(([J,Z,Q])=>{let{timestamp:$,...W}=Q;return{level:j0[J],message:Z,options:{...W,date:new Date(Q.timestamp)}}});return JSON.stringify(q,x_(),2)}exportLogsToJSON(){let q=this.formatLogsToJSON(),J=new Blob([q],{type:"application/json"}),Z=URL.createObjectURL(J),Q=document.createElement("a");Q.href=Z,Q.download=`ledger-device-management-kit-logs-${new Date().toISOString()}.json`,Q.click()}}var k_=1e4;class tW{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;previousSendApduPromise=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(q){this.deviceId=q.deviceId,this.deviceAdpuSender=q.deviceApduSender,this.timeoutDuration=q.timeoutDuration,this.machineActor=t0(O_({sendApduFn:(J,Z,Q)=>this.sendApduToDeviceConnection(J,Z,Q),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},tryToReconnect:()=>{q.tryToReconnect(this.timeoutDuration)},onTerminated:q.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(q,J,Z){this.deviceAdpuSender.sendApdu(q,J,Z).then((Q)=>{Q.caseOf({Left:($)=>{this.machineActor.send({type:"ApduSendingError",error:$})},Right:($)=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:$})}})}).catch((Q)=>{this.machineActor.send({type:"ApduSendingError",error:new zq(Q)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(q){this.deviceAdpuSender.setDependencies(q)}getDeviceId(){return this.deviceId}async sendApdu(q,J,Z){this.machineActor.getSnapshot().context.apduInProgress.isJust()&&await Promise.race([new Promise(($)=>setTimeout($,k_)),this.previousSendApduPromise]);let Q=new Promise(($)=>{this.machineActor.send({type:"SendApduCalled",apdu:q,triggersDisconnection:!!J,abortTimeout:Z,responseCallback:$})});return this.previousSendApduPromise=Q,Q.finally(()=>{this.previousSendApduPromise===Q&&(this.previousSendApduPromise=null)}),Q}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceConnected(){this.machineActor.send({type:"DeviceConnected"})}eventDeviceDisconnected(){this.machineActor.send({type:"DeviceDisconnected"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function O_({sendApduFn:q,startReconnectionTimeout:J,cancelReconnectionTimeout:Z,tryToReconnect:Q,onTerminated:$,closeConnection:W}){return i({types:{},actions:{startTimer:()=>{J()},cancelTimer:()=>{Z()},reconnectionTimeoutEvent:AJ({type:"ReconnectionTimedOut"}),sendApdu:({context:Y})=>{Y.apduInProgress.map(({apdu:z,abortTimeout:X})=>{q(z,!1,X)})},sendApduResponse:({context:Y},z)=>{Y.apduInProgress.map(({responseCallback:X})=>X(z.response))},sendGetAppAndVersion:()=>{q(new i0().getApdu().getRawApdu(),!1)},tryToReconnect:()=>{Q()},clearApduInProgress:N({apduInProgress:p}),clearApduResponse:N({apduResponse:p}),signalTermination:()=>{$()},closeConnection:()=>{W()}},guards:{isApduThatTriggersDisconnection:({context:Y,event:z})=>z.type!=="ApduResponseReceived"?!1:Y.apduInProgress.caseOf({Just:({triggersDisconnection:X,apdu:w})=>(X||m.isApduThatTriggersDisconnection(w))&&m.isSuccessResponse(z.apduResponse),Nothing:()=>!1}),isSendApduBusyError:({event:Y})=>Y.type!=="ApduResponseReceived"?!1:Y.apduResponse.statusCode[0]===102&&Y.apduResponse.statusCode[1]===1}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:p,apduResponse:p},states:{Connected:{on:{DeviceDisconnected:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:N({apduInProgress:({event:Y})=>J0.of({apdu:Y.apdu,triggersDisconnection:Y.triggersDisconnection,abortTimeout:Y.abortTimeout,responseCallback:Y.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:"isApduThatTriggersDisconnection",target:"WaitingForDisconnection",actions:[N({apduResponse:({event:Y})=>J0.of(Y.apduResponse)})]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:Y})=>({response:I(Y.apduResponse)})},{type:"clearApduInProgress"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:Y})=>({response:K(Y.error)})},"clearApduInProgress"]},DeviceDisconnected:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:K(new r1)}},"clearApduInProgress"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:K(new r1)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:Y})=>{Y.responseCallback(K(new W6))}}}},WaitingForDisconnection:{entry:["sendGetAppAndVersion"],exit:[{type:"sendApduResponse",params:({context:Y})=>({response:Y.apduResponse.caseOf({Just:(z)=>I(z),Nothing:()=>K(new zq)})})},{type:"clearApduInProgress"},{type:"clearApduResponse"}],on:{ApduResponseReceived:[{guard:"isSendApduBusyError",actions:["sendGetAppAndVersion"],target:"WaitingForDisconnection"},{target:"Connected"}],ApduSendingError:[{target:"WaitingForReconnection"}],SendApduCalled:{actions:({event:Y})=>{Y.responseCallback(K(new W6))}},DeviceDisconnected:{target:"WaitingForReconnection"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnection:{entry:["startTimer","tryToReconnect"],on:{DeviceConnected:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:N({apduInProgress:({event:Y})=>J0.of({apdu:Y.apdu,triggersDisconnection:Y.triggersDisconnection,abortTimeout:Y.abortTimeout,responseCallback:Y.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceConnected:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:K(new SJ)}},{type:"clearApduInProgress"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:K(new r1)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:Y})=>{Y.responseCallback(K(new W6))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}class O9{id;deviceModel;sendApdu;type;transport;name;constructor({id:q,deviceModel:J,type:Z,transport:Q,sendApdu:$,name:W}){this.id=q,this.deviceModel=J,this.sendApdu=$,this.type=Z,this.transport=Q,this.name=W}}function eW(q={}){return{id:o.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2097152,getBlockSize:()=>4096,masks:[855638016],bluetoothSpec:[{serviceUuid:"13d63400-2c97-0004-0000-4c6564676572",notifyUuid:"13d63400-2c97-0004-0001-4c6564676572",writeUuid:"13d63400-2c97-0004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-0004-0003-4c6564676572"}],...q}}var qY=({statusCode:q=Uint8Array.from([144,0]),data:J=Uint8Array.from([])}={})=>new bq({statusCode:q,data:J});function C_(q={}){let J=eW();return new O9({deviceModel:J,id:"42",type:"MOCK",transport:"USB",sendApdu:vi.fn(async()=>Promise.resolve(I(qY()))),...q})}var Q1=k1(_q(),1);class JY{isCompatible;version;modelId;appName;constructor(q,J,Z){this.modelId=q.deviceModelId,this.appName="currentApp"in q?q.currentApp.name:void 0;let Q=Z.resolve(q,J);this.isCompatible=Q.isCompatible,this.version=Q.version}withMinVersionInclusive(q){return Q1.gte(this.version,q)||(this.isCompatible=!1),this}withMinVersionExclusive(q){return Q1.gt(this.version,q)||(this.isCompatible=!1),this}withMinVersionInclusiveAcceptingPrerelease(q){let J=Q1.valid(Q1.coerce(this.version)),Z=Q1.valid(Q1.coerce(q));return(J===null||Z===null||!Q1.gte(J,Z))&&(this.isCompatible=!1),this}excludeDeviceModel(q){return this.modelId===q&&(this.isCompatible=!1),this}excludeDeviceModels(...q){for(let J of q)this.excludeDeviceModel(J);return this}excludeApp(q){return this.appName===q&&(this.isCompatible=!1),this}excludeApps(...q){for(let J of q)this.excludeApp(J);return this}check(){return this.isCompatible}}function ZY(q){return q.replace(/\s/g,"")}function QY(q){let J=ZY(q);return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(J)}function b_(){if(typeof window<"u"&&typeof window.atob=="function")return window.atob.bind(window);if(typeof atob=="function")return atob}function T_(){if(typeof window<"u"&&typeof window.btoa=="function")return window.btoa.bind(window);if(typeof btoa=="function")return btoa}function M_(q){let J=ZY(q);if(J.length===0)return new Uint8Array;if(!QY(J))return null;let Z=b_();if(Z){let Q=Z(J),$=new Uint8Array(Q.length);for(let W=0;W<Q.length;W++)$[W]=Q.charCodeAt(W);return $}if(typeof globalThis.Buffer<"u")return Uint8Array.from(globalThis.Buffer.from(J,"base64"));throw Error("No Base64 decoder available in this environment.")}function f_(q){let J=T_();if(J){let Z="";for(let Q=0;Q<q.length;Q++){let $=q[Q];if($===void 0)throw Error("Unexpected undefined byte in array.");Z+=String.fromCharCode($)}return J(Z)}if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(q).toString("base64");throw Error("No Base64 encoder available in this environment.")}export{O6 as Ma,C6 as Na,kY as Oa,_1 as Pa,B0 as Qa,mq as Ra,Wq as Sa,b6 as Ta,T6 as Ua,lq as Va,_0 as Wa,M6 as Xa,Y0 as Ya,H1 as Za,Yq as _a,f6 as $a,n0 as ab,x1 as bb,T as cb,n as db,m as eb,S0 as fb,zq as gb,bY as hb,TY as ib,h0 as jb,h9 as kb,S9 as lb,H0 as mb,wq as nb,v9 as ob,S6 as pb,i0 as qb,y9 as rb,h6 as sb,JZ as tb,ZZ as ub,_q as vb,o as wb,Hq as xb,E3 as yb,rq as zb,D0 as Ab,T0 as Bb,o6 as Cb,qJ as Db,r6 as Eb,r7 as Fb,t6 as Gb,u0 as Hb,d1 as Ib,k as Jb,J0 as Kb,I0 as Lb,p as Mb,L0 as Nb,K as Ob,I as Pb,r0 as Qb,ZQ as Rb,QQ as Sb,uN as Tb,b3 as Ub,lN as Vb,dN as Wb,cN as Xb,S as Yb,k0 as Zb,t3 as _b,l as $b,N as ac,i as bc,G8 as cc,B1 as dc,i1 as ec,T1 as fc,N8 as gc,D1 as hc,q0 as ic,V8 as jc,t as kc,cQ as lc,CJ as mc,a as nc,a1 as oc,U8 as pc,d as qc,Kq as rc,A0 as sc,u2 as tc,g2 as uc,m2 as vc,l2 as wc,d2 as xc,o1 as yc,c2 as zc,TJ as Ac,MJ as Bc,p2 as Cc,s2 as Dc,n2 as Ec,i2 as Fc,a2 as Gc,fJ as Hc,r1 as Ic,W6 as Jc,SJ as Kc,hJ as Lc,M1 as Mc,nQ as Nc,M0 as Oc,jq as Pc,j8 as Qc,z6 as Rc,M as Sc,w6 as Tc,mJ as Uc,Y$ as Vc,lJ as Wc,mD as Xc,lD as Yc,dD as Zc,cJ as _c,pJ as $c,w$ as ad,E0 as bd,d0 as cd,f1 as dd,Vw as ed,D$ as fd,P8 as gd,K$ as hd,I$ as id,L$ as jd,j as kd,R as ld,X0 as md,y8 as nd,u8 as od,L1 as pd,w1 as qd,bq as rd,ZW as sd,A1 as td,U6 as ud,g1 as vd,K6 as wd,QW as xd,Tq as yd,$W as zd,WW as Ad,R1 as Bd,Z1 as Cd,ZX as Dd,zX as Ed,ZF as Fd,jW as Gd,m1 as Hd,j0 as Id,V9 as Jd,F1 as Kd,D9 as Ld,k9 as Md,aW as Nd,oW as Od,rW as Pd,tW as Qd,O9 as Rd,C_ as Sd,JY as Td,QY as Ud,M_ as Vd,f_ as Wd};
60
+ - service identifier: ${S0(q.serviceIdentifier)}
61
+ - name: ${q.name?.toString()??"-"}${J}`}function a$(q,J,Z){if(q.redirections.length!==1)s$(q.redirections,J,q,Z);else{let[Q]=q.redirections;Jq(Q)&&a$(Q,J,Z)}}function w5(q,J,Z){if(Array.isArray(q.bindings)&&q.bindings.length===1){let[Q]=q.bindings;Jq(Q)&&a$(Q,J,Z)}else s$(q.bindings,J,q,Z)}function kw(q,J){if(function(Z){return Z instanceof Error&&(Z instanceof RangeError&&/stack space|call stack|too much recursion/i.test(Z.message)||Z.name==="InternalError"&&/too much recursion/.test(Z.message))}(J)){let Z=function(Q){let $=[...Q];if($.length===0)return"(No dependency trace)";return $.map(S0).join(" -> ")}(function(Q){let $=new Set;for(let W of Q.servicesBranch){if($.has(W))return[...$,W];$.add(W)}return[...$]}(q));throw new w0(X0.planning,`Circular dependency found: ${Z}`,{cause:J})}throw J}function o$(q){try{let J=new Map;q.rootConstraints.tag!==void 0&&J.set(q.rootConstraints.tag.key,q.rootConstraints.tag.value);let Z=new z5({elem:{name:q.rootConstraints.name,serviceIdentifier:q.rootConstraints.serviceIdentifier,tags:J},previous:void 0}),Q=new Cq(Z.last),$=k8(q,Q),W=[],Y={bindings:W,parent:void 0,serviceIdentifier:q.rootConstraints.serviceIdentifier};if(W.push(...O8(q,Z,$,Y)),!q.rootConstraints.isMultiple){w5(Y,q.rootConstraints.isOptional??!1,Q);let[z]=W;Y.bindings=z}return{tree:{root:Y}}}catch(J){kw(q,J)}}function Ow(q,J,Z,Q){let $={binding:J,classMetadata:q.getClassMetadata(J.implementationType),constructorParams:[],parent:Q,propertyParams:new Map};return r$({autobindOptions:q.autobindOptions,getBindings:q.getBindings,getClassMetadata:q.getClassMetadata,node:$,servicesBranch:q.servicesBranch,setBinding:q.setBinding},Z)}function C$(q,J,Z){if(Z.kind===j1.unmanaged)return;let Q=Aq.is(Z.value)?Z.value.unwrap():Z.value,$=J.concat({name:Z.name,serviceIdentifier:Q,tags:Z.tags}),W=new Cq($.last),Y=k8(q,W),z=[],X={bindings:z,parent:q.node,serviceIdentifier:Q};if(z.push(...O8(q,$,Y,X)),Z.kind===j1.singleInjection){w5(X,Z.optional,W);let[w]=z;X.bindings=w}return X}function Cw(q,J,Z){let Q=Aq.is(Z.value)?Z.value.unwrap():Z.value,$=J.concat({name:Z.name,serviceIdentifier:Q,tags:Z.tags}),W=new Cq($.last),Y=k8(q,W),z=[],X={bindings:z,parent:q.node,serviceIdentifier:Q};if(z.push(...O8(q,$,Y,X)),Z.kind===qq.singleInjection){w5(X,Z.optional,W);let[w]=z;X.bindings=w}return X}function bw(q,J,Z,Q){let $={binding:J,params:[],parent:Q};return r$({autobindOptions:q.autobindOptions,getBindings:q.getBindings,getClassMetadata:q.getClassMetadata,node:$,servicesBranch:q.servicesBranch,setBinding:q.setBinding},Z)}function O8(q,J,Z,Q){let $=Jq(Q)?Q.binding.targetServiceIdentifier:Q.serviceIdentifier;q.servicesBranch.push($);let W=[];for(let Y of Z)switch(Y.type){case _0.Instance:W.push(Ow(q,Y,J,Q));break;case _0.ResolvedValue:W.push(bw(q,Y,J,Q));break;case _0.ServiceRedirection:{let z=Tw(q,J,Y,Q);W.push(z);break}default:W.push({binding:Y,parent:Q})}return q.servicesBranch.pop(),W}function Tw(q,J,Z,Q){let $={binding:Z,parent:Q,redirections:[]},W=k8(q,new Cq(J.last),{customServiceIdentifier:Z.targetServiceIdentifier});return $.redirections.push(...O8(q,J,W,$)),$}function r$(q,J){return q.node.binding.type===_0.Instance?function(Z,Q,$){let W=Q.classMetadata;for(let[Y,z]of W.constructorArguments.entries())Q.constructorParams[Y]=C$(Z,$,z);for(let[Y,z]of W.properties){let X=C$(Z,$,z);X!==void 0&&Q.propertyParams.set(Y,X)}return Z.node}(q,q.node,J):function(Z,Q,$){let W=Q.binding.metadata;for(let[Y,z]of W.arguments.entries())Q.params[Y]=Cw(Z,$,z);return Z.node}(q,q.node,J)}var e1;(function(q){q[q.singleMandatory=0]="singleMandatory",q[q.singleOptional=1]="singleOptional",q[q.multipleMandatory=2]="multipleMandatory",q[q.multipleOptional=3]="multipleOptional",q[q.length=4]="length"})(e1||(e1={}));class X5{#q;#J;#$;#Z;#Y;constructor(){this.#q=this.#z(),this.#J=this.#z(),this.#Z=this.#z(),this.#$=this.#z(),this.#Y=[]}clearCache(){for(let q of this.#w())q.clear();for(let q of this.#Y)q.clearCache()}get(q){return q.name===void 0?q.tag===void 0?this.#Q(this.#q,q).get(q.serviceIdentifier):this.#Q(this.#$,q).get(q.serviceIdentifier)?.get(q.tag.key)?.get(q.tag.value):q.tag===void 0?this.#Q(this.#J,q).get(q.serviceIdentifier)?.get(q.name):this.#Q(this.#Z,q).get(q.serviceIdentifier)?.get(q.name)?.get(q.tag.key)?.get(q.tag.value)}set(q,J){q.name===void 0?q.tag===void 0?this.#Q(this.#q,q).set(q.serviceIdentifier,J):this.#W(this.#W(this.#Q(this.#$,q),q.serviceIdentifier),q.tag.key).set(q.tag.value,J):q.tag===void 0?this.#W(this.#Q(this.#J,q),q.serviceIdentifier).set(q.name,J):this.#W(this.#W(this.#W(this.#Q(this.#Z,q),q.serviceIdentifier),q.name),q.tag.key).set(q.tag.value,J)}subscribe(q){this.#Y.push(q)}#z(){let q=Array(e1.length);for(let J=0;J<q.length;++J)q[J]=new Map;return q}#W(q,J){let Z=q.get(J);return Z===void 0&&(Z=new Map,q.set(J,Z)),Z}#Q(q,J){return q[this.#X(J)]}#w(){return[...this.#q,...this.#J,...this.#Z,...this.#$]}#X(q){return q.isMultiple?q.optional===!0?e1.multipleOptional:e1.multipleMandatory:q.optional===!0?e1.singleOptional:e1.singleMandatory}}function t$(q,J){return K0(J)?(q.cache={isRight:!0,value:J},J.then((Z)=>b$(q,Z))):b$(q,J)}function b$(q,J){return q.cache={isRight:!0,value:J},J}function Mw(q,J,Z){let Q=q.getActivations(J);return Q===void 0?Z:K0(Z)?T$(q,Z,Q[Symbol.iterator]()):function($,W,Y){let z=W,X=Y.next();for(;X.done!==!0;){let w=X.value($.context,z);if(K0(w))return T$($,w,Y);z=w,X=Y.next()}return z}(q,Z,Q[Symbol.iterator]())}async function T$(q,J,Z){let Q=await J,$=Z.next();for(;$.done!==!0;)Q=await $.value(q.context,Q),$=Z.next();return Q}function x8(q,J,Z){let Q=Z;if(J.onActivation!==void 0){let $=J.onActivation;Q=K0(Q)?Q.then((W)=>$(q.context,W)):$(q.context,Q)}return Mw(q,J.serviceIdentifier,Q)}function F5(q){return(J,Z)=>{if(Z.cache.isRight)return Z.cache.value;return t$(Z,x8(J,Z,q(J,Z)))}}var fw=F5(function(q,J){return J.value});function Sw(q){return q}function _5(q,J){return(Z,Q)=>{let $=q(Q);switch($.scope){case n0.Singleton:if($.cache.isRight)return $.cache.value;return t$($,x8(Z,$,J(Z,Q)));case n0.Request:{if(Z.requestScopeCache.has($.id))return Z.requestScopeCache.get($.id);let W=x8(Z,$,J(Z,Q));return Z.requestScopeCache.set($.id,W),W}case n0.Transient:return x8(Z,$,J(Z,Q))}}}var hw=((q)=>_5(Sw,q))(function(q,J){return J.value(q.context)}),vw=F5(function(q,J){return J.factory(q.context)});function M$(q,J,Z){let Q=function($,W,Y){if(Y===void 0)return;if(!(Y in $))throw new w0(X0.resolution,`Expecting a "${Y.toString()}" property when resolving "${W.implementationType.name}" class @postConstruct decorated method, none found.`);if(typeof $[Y]!="function")throw new w0(X0.resolution,`Expecting a "${Y.toString()}" method when resolving "${W.implementationType.name}" class @postConstruct decorated method, a non function property was found instead.`);{let z;try{z=$[Y]()}catch(X){throw new w0(X0.resolution,`Unexpected error found when calling "${Y.toString()}" @postConstruct decorated method on class "${W.implementationType.name}"`,{cause:X})}if(K0(z))return async function(X,w,F){try{await F}catch(_){throw new w0(X0.resolution,`Unexpected error found when calling "${w.toString()}" @postConstruct decorated method on class "${X.implementationType.name}"`,{cause:_})}}(W,Y,z)}}(q,J,Z);return K0(Q)?Q.then(()=>q):q}function f$(q){return(J,Z,Q)=>{let $=new Q.binding.implementationType(...J),W=q(Z,$,Q);return K0(W)?W.then(()=>M$($,Q.binding,Q.classMetadata.lifecycle.postConstructMethodName)):M$($,Q.binding,Q.classMetadata.lifecycle.postConstructMethodName)}}var yw=F5(function(q,J){return J.provider(q.context)});function uw(q){return q.binding}function gw(q){return q.binding}var S$=function(q){return(J,Z,Q)=>{let $=[];for(let[W,Y]of Q.propertyParams){let z=Q.classMetadata.properties.get(W);if(z===void 0)throw new w0(X0.resolution,`Expecting metadata at property "${W.toString()}", none found`);z.kind!==j1.unmanaged&&Y.bindings!==void 0&&(Z[W]=q(J,Y),K0(Z[W])&&$.push((async()=>{Z[W]=await Z[W]})()))}if($.length>0)return Promise.all($).then(()=>{})}}(C8),h$=function(q){return function J(Z,Q){let $=[];for(let W of Q.redirections)Jq(W)?$.push(...J(Z,W)):$.push(q(Z,W));return $}}(Y5),mw=function(q,J,Z){return(Q,$)=>{let W=q(Q,$);return K0(W)?J(W,Q,$):Z(W,Q,$)}}(function(q){return(J,Z)=>{let Q=[];for(let $ of Z.constructorParams)$===void 0?Q.push(void 0):Q.push(q(J,$));return Q.some(K0)?Promise.all(Q):Q}}(C8),function(q){return async(J,Z,Q)=>{let $=await J;return q($,Z,Q)}}(f$(S$)),f$(S$)),lw=function(q){return(J,Z)=>{let Q=q(J,Z);return K0(Q)?Q.then(($)=>Z.binding.factory(...$)):Z.binding.factory(...Q)}}(function(q){return(J,Z)=>{let Q=[];for(let $ of Z.params)Q.push(q(J,$));return Q.some(K0)?Promise.all(Q):Q}}(C8)),dw=((q)=>_5(uw,q))(mw),cw=((q)=>_5(gw,q))(lw);function e$(q){return C8(q,q.planResult.tree.root)}function Y5(q,J){switch(J.binding.type){case _0.ConstantValue:return fw(q,J.binding);case _0.DynamicValue:return hw(q,J.binding);case _0.Factory:return vw(q,J.binding);case _0.Instance:return dw(q,J);case _0.Provider:return yw(q,J.binding);case _0.ResolvedValue:return cw(q,J)}}function C8(q,J){if(J.bindings!==void 0)return Array.isArray(J.bindings)?function(Z,Q){let $=[];for(let W of Q)Jq(W)?$.push(...h$(Z,W)):$.push(Y5(Z,W));if($.some(K0))return Promise.all($);return $}(q,J.bindings):function(Z,Q){if(Jq(Q)){let $=h$(Z,Q);if($.length===1)return $[0];throw new w0(X0.resolution,"Unexpected multiple resolved values on single injection")}return Y5(Z,Q)}(q,J.bindings)}function pw(q){return q.scope!==void 0}function v$(q,J){if(q.lifecycle.preDestroyMethodName!==void 0&&typeof J[q.lifecycle.preDestroyMethodName]=="function")return J[q.lifecycle.preDestroyMethodName]()}function y$(q,J,Z){let Q=q.getDeactivations(J);if(Q!==void 0)return K0(Z)?u$(Z,Q[Symbol.iterator]()):function($,W){let Y=W.next();for(;Y.done!==!0;){let z=Y.value($);if(K0(z))return u$($,W);Y=W.next()}}(Z,Q[Symbol.iterator]())}async function u$(q,J){let Z=await q,Q=J.next();for(;Q.done!==!0;)await Q.value(Z),Q=J.next()}function sw(q,J){let Z=function(Q,$){if($.type===_0.Instance){let W=Q.getClassMetadata($.implementationType),Y=$.cache.value;return K0(Y)?Y.then((z)=>v$(W,z)):v$(W,Y)}}(q,J);return Z===void 0?g$(q,J):Z.then(()=>g$(q,J))}function g$(q,J){let Z=J.cache;return K0(Z.value)?Z.value.then((Q)=>m$(q,J,Q)):m$(q,J,Z.value)}function m$(q,J,Z){let Q;if(J.onDeactivation!==void 0)Q=(0,J.onDeactivation)(Z);return Q===void 0?y$(q,J.serviceIdentifier,Z):Q.then(()=>y$(q,J.serviceIdentifier,Z))}function b8(q,J){if(J===void 0)return;let Z=function($){let W=[];for(let Y of $)pw(Y)&&Y.scope===n0.Singleton&&Y.cache.isRight&&W.push(Y);return W}(J),Q=[];for(let $ of Z){let W=sw(q,$);W!==void 0&&Q.push(W)}return Q.length>0?Promise.all(Q).then(()=>{}):void 0}function qW(q,J){let Z=q.getBindingsFromModule(J);return b8(q,Z)}function H5(q,J){let Z=q.getBindings(J);return b8(q,Z)}var G5="@inversifyjs/container/bindingId";class F0{#q;#J;constructor(q){this.#q=function(){let J=K1(Object,G5)??0;return J===Number.MAX_SAFE_INTEGER?F6(Object,G5,Number.MIN_SAFE_INTEGER):w1(Object,G5,()=>J,(Z)=>Z+1),J}(),this.#J=q}get id(){return this.#q}load(q){return this.#J(q)}}var ZW=Symbol.for("@inversifyjs/container/bindingIdentifier");function JW(q){return typeof q=="object"&&q!==null&&q[ZW]===!0}class h1{static always=(q)=>!0}function B5(q){return{[ZW]:!0,id:q.id}}function D6(q){return(J)=>{for(let Z=J.getAncestor();Z!==void 0;Z=Z.getAncestor())if(q(Z))return!0;return!1}}function V6(q){return(J)=>J.name===q}function T8(q){return(J)=>J.serviceIdentifier===q}function B6(q,J){return(Z)=>Z.tags.has(q)&&Z.tags.get(q)===J}function nw(q){return q.name===void 0&&q.tags.size===0}function M8(q){let J=D6(q);return(Z)=>!J(Z)}function f8(q){return(J)=>{let Z=J.getAncestor();return Z===void 0||!q(Z)}}function S8(q){return(J)=>{let Z=J.getAncestor();return Z!==void 0&&q(Z)}}class QW{#q;constructor(q){this.#q=q}getIdentifier(){return B5(this.#q)}inRequestScope(){return this.#q.scope=n0.Request,new u1(this.#q)}inSingletonScope(){return this.#q.scope=n0.Singleton,new u1(this.#q)}inTransientScope(){return this.#q.scope=n0.Transient,new u1(this.#q)}}class V5{#q;#J;#$;#Z;constructor(q,J,Z,Q){this.#q=q,this.#J=J,this.#$=Z,this.#Z=Q}to(q){let J=N6(q),Z={cache:{isRight:!1,value:void 0},id:I1(),implementationType:q,isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:J.scope??this.#$,serviceIdentifier:this.#Z,type:_0.Instance};return this.#q(Z),new h8(Z)}toSelf(){if(typeof this.#Z!="function")throw Error('"toSelf" function can only be applied when a newable function is used as service identifier');return this.to(this.#Z)}toConstantValue(q){let J={cache:{isRight:!1,value:void 0},id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:n0.Singleton,serviceIdentifier:this.#Z,type:_0.ConstantValue,value:q};return this.#q(J),new u1(J)}toDynamicValue(q){let J={cache:{isRight:!1,value:void 0},id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:this.#$,serviceIdentifier:this.#Z,type:_0.DynamicValue,value:q};return this.#q(J),new h8(J)}toResolvedValue(q,J){let Z={cache:{isRight:!1,value:void 0},factory:q,id:I1(),isSatisfiedBy:h1.always,metadata:this.#Y(J),moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:this.#$,serviceIdentifier:this.#Z,type:_0.ResolvedValue};return this.#q(Z),new h8(Z)}toFactory(q){let J={cache:{isRight:!1,value:void 0},factory:q,id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,scope:n0.Singleton,serviceIdentifier:this.#Z,type:_0.Factory};return this.#q(J),new u1(J)}toProvider(q){let J={cache:{isRight:!1,value:void 0},id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,onActivation:void 0,onDeactivation:void 0,provider:q,scope:n0.Singleton,serviceIdentifier:this.#Z,type:_0.Provider};return this.#q(J),new u1(J)}toService(q){let J={id:I1(),isSatisfiedBy:h1.always,moduleId:this.#J,serviceIdentifier:this.#Z,targetServiceIdentifier:q,type:_0.ServiceRedirection};this.#q(J)}#Y(q){return{arguments:(q??[]).map((J)=>function(Z){return typeof Z=="object"&&!Aq.is(Z)}(J)?{kind:J.isMultiple===!0?qq.multipleInjection:qq.singleInjection,name:J.name,optional:J.optional??!1,tags:new Map((J.tags??[]).map((Z)=>[Z.key,Z.value])),value:J.serviceIdentifier}:{kind:qq.singleInjection,name:void 0,optional:!1,tags:new Map,value:J})}}}class D5{#q;constructor(q){this.#q=q}getIdentifier(){return B5(this.#q)}onActivation(q){return this.#q.onActivation=q,new v8(this.#q)}onDeactivation(q){return this.#q.onDeactivation=q,new v8(this.#q)}}class v8{#q;constructor(q){this.#q=q}getIdentifier(){return B5(this.#q)}when(q){return this.#q.isSatisfiedBy=q,new D5(this.#q)}whenAnyAncestor(q){return this.when(D6(q))}whenAnyAncestorIs(q){return this.when(D6(T8(q)))}whenAnyAncestorNamed(q){return this.when(function(J){return D6(V6(J))}(q))}whenAnyAncestorTagged(q,J){return this.when(function(Z,Q){return D6(B6(Z,Q))}(q,J))}whenDefault(){return this.when(nw)}whenNamed(q){return this.when(V6(q))}whenNoParent(q){return this.when(f8(q))}whenNoParentIs(q){return this.when(f8(T8(q)))}whenNoParentNamed(q){return this.when(function(J){return f8(V6(J))}(q))}whenNoParentTagged(q,J){return this.when(function(Z,Q){return f8(B6(Z,Q))}(q,J))}whenParent(q){return this.when(S8(q))}whenParentIs(q){return this.when(S8(T8(q)))}whenParentNamed(q){return this.when(function(J){return S8(V6(J))}(q))}whenParentTagged(q,J){return this.when(function(Z,Q){return S8(B6(Z,Q))}(q,J))}whenTagged(q,J){return this.when(B6(q,J))}whenNoAncestor(q){return this.when(M8(q))}whenNoAncestorIs(q){return this.when(M8(T8(q)))}whenNoAncestorNamed(q){return this.when(function(J){return M8(V6(J))}(q))}whenNoAncestorTagged(q,J){return this.when(function(Z,Q){return M8(B6(Z,Q))}(q,J))}}class u1 extends v8{#q;constructor(q){super(q),this.#q=new D5(q)}onActivation(q){return this.#q.onActivation(q)}onDeactivation(q){return this.#q.onDeactivation(q)}}class h8 extends u1{#q;constructor(q){super(q),this.#q=new QW(q)}inRequestScope(){return this.#q.inRequestScope()}inSingletonScope(){return this.#q.inSingletonScope()}inTransientScope(){return this.#q.inTransientScope()}}var N5=Symbol.for("@inversifyjs/container/InversifyContainerError");class v1 extends Error{[N5];kind;constructor(q,J,Z){super(J,Z),this[N5]=!0,this.kind=q}static is(q){return typeof q=="object"&&q!==null&&q[N5]===!0}static isErrorOfKind(q,J){return v1.is(q)&&q.kind===J}}var y1;(function(q){q[q.invalidOperation=0]="invalidOperation"})(y1||(y1={}));var iw=n0.Transient;class y8{#q;#J;#$;#Z;#Y;#z;#W;#Q;#w;#X;#G;constructor(q){this.#$=this.#A(),this.#Y=(J)=>this.#q.get(J),this.#Q=new X5,this.#w=this.#N(),q?.parent===void 0?(this.#q=Eq.build(void 0),this.#J=xq.build(void 0),this.#Z=kq.build(void 0)):(this.#q=Eq.build(q.parent.#q),this.#J=xq.build(q.parent.#J),this.#Z=kq.build(q.parent.#Z),q.parent.#Q.subscribe(this.#Q)),this.#z=this.#J.get.bind(this.#J),this.#X=this.#H.bind(this),this.#W={autobind:q?.autobind??!1,defaultScope:q?.defaultScope??iw},this.#G=[]}bind(q){return new V5((J)=>{this.#H(J)},void 0,this.#W.defaultScope,q)}get(q,J){let Z=this.#F(!1,q,J),Q=this.#_(Z);if(K0(Q))throw new v1(y1.invalidOperation,`Unexpected asyncronous service when resolving service "${S0(q)}"`);return Q}getAll(q,J){let Z=this.#F(!0,q,J),Q=this.#_(Z);if(K0(Q))throw new v1(y1.invalidOperation,`Unexpected asyncronous service when resolving service "${S0(q)}"`);return Q}async getAllAsync(q,J){let Z=this.#F(!0,q,J);return this.#_(Z)}async getAsync(q,J){let Z=this.#F(!1,q,J);return this.#_(Z)}isBound(q,J){let Z=this.#J.get(q);return this.#V(q,Z,J)}isCurrentBound(q,J){let Z=this.#J.getNonParentBindings(q);return this.#V(q,Z,J)}async load(...q){await Promise.all(this.#B(...q))}loadSync(...q){let J=this.#B(...q);for(let Z of J)if(Z!==void 0)throw new v1(y1.invalidOperation,"Unexpected asyncronous module load. Consider using Container.load() instead.")}onActivation(q,J){this.#q.add(J,{serviceId:q})}onDeactivation(q,J){this.#Z.add(J,{serviceId:q})}restore(){let q=this.#G.pop();if(q===void 0)throw new v1(y1.invalidOperation,"No snapshot available to restore");this.#q=q.activationService,this.#J=q.bindingService,this.#Z=q.deactivationService,this.#x()}async rebind(q){return await this.unbind(q),this.bind(q)}rebindSync(q){return this.unbindSync(q),this.bind(q)}snapshot(){this.#G.push({activationService:this.#q.clone(),bindingService:this.#J.clone(),deactivationService:this.#Z.clone()})}async unbind(q){await this.#U(q)}async unbindAll(){let q=[...this.#J.getNonParentBoundServices()];await Promise.all(q.map(async(J)=>H5(this.#$,J)));for(let J of q)this.#q.removeAllByServiceId(J),this.#J.removeAllByServiceId(J),this.#Z.removeAllByServiceId(J);this.#Q.clearCache()}unbindSync(q){this.#U(q)!==void 0&&this.#k(q)}async unload(...q){await Promise.all(this.#D(...q)),this.#j(q)}unloadSync(...q){let J=this.#D(...q);for(let Z of J)if(Z!==void 0)throw new v1(y1.invalidOperation,"Unexpected asyncronous module unload. Consider using Container.unload() instead.");this.#j(q)}#L(q){return{bind:(J)=>new V5((Z)=>{this.#H(Z)},q,this.#W.defaultScope,J),isBound:this.isBound.bind(this),onActivation:(J,Z)=>{this.#q.add(Z,{moduleId:q,serviceId:J})},onDeactivation:(J,Z)=>{this.#Z.add(Z,{moduleId:q,serviceId:J})},rebind:this.rebind.bind(this),rebindSync:this.rebindSync.bind(this),unbind:this.unbind.bind(this),unbindSync:this.unbindSync.bind(this)}}#A(){return{getBindings:(q)=>this.#J.get(q),getBindingsFromModule:(q)=>this.#J.getByModuleId(q),getClassMetadata:N6,getDeactivations:(q)=>this.#Z.get(q)}}#R(q,J,Z){return{isMultiple:q,name:Z?.name,optional:Z?.optional,serviceIdentifier:J,tag:Z?.tag}}#P(q,J,Z){let Q={autobindOptions:Z?.autobind??this.#W.autobind?{scope:this.#W.defaultScope}:void 0,getBindings:this.#z,getClassMetadata:N6,rootConstraints:{isMultiple:J,serviceIdentifier:q},servicesBranch:[],setBinding:this.#X};return this.#E(Q,Z),Q}#F(q,J,Z){let Q=this.#R(q,J,Z),$=this.#Q.get(Q);if($!==void 0)return $;let W=o$(this.#P(J,q,Z));return this.#Q.set(Q,W),W}#N(){return{get:this.get.bind(this),getAll:this.getAll.bind(this),getAllAsync:this.getAllAsync.bind(this),getAsync:this.getAsync.bind(this)}}#_(q){return e$({context:this.#w,getActivations:this.#Y,planResult:q,requestScopeCache:new Map})}#E(q,J){J!==void 0&&(J.name!==void 0&&(q.rootConstraints.name=J.name),J.optional===!0&&(q.rootConstraints.isOptional=!0),J.tag!==void 0&&(q.rootConstraints.tag={key:J.tag.key,value:J.tag.value}))}#V(q,J,Z){if(J===void 0)return!1;let Q={getAncestor:()=>{},name:Z?.name,serviceIdentifier:q,tags:new Map};Z?.tag!==void 0&&Q.tags.set(Z.tag.key,Z.tag.value);for(let $ of J)if($.isSatisfiedBy(Q))return!0;return!1}#B(...q){return q.map((J)=>J.load(this.#L(J.id)))}#D(...q){return q.map((J)=>qW(this.#$,J.id))}#x(){this.#Q.clearCache(),this.#Y=(q)=>this.#q.get(q),this.#z=this.#J.get.bind(this.#J),this.#w=this.#N(),this.#X=this.#H.bind(this)}#H(q){this.#J.set(q),this.#Q.clearCache()}#k(q){let J;if(JW(q)){let Q=this.#J.getById(q.id),$=(Z=Q,function(W){if(W===void 0)return;let Y=W.next();return Y.done!==!0?Y.value:void 0}(Z?.[Symbol.iterator]()))?.serviceIdentifier;J=$===void 0?"Unexpected asyncronous deactivation when unbinding binding identifier. Consider using Container.unbind() instead.":`Unexpected asyncronous deactivation when unbinding "${S0($)}" binding. Consider using Container.unbind() instead.`}else J=`Unexpected asyncronous deactivation when unbinding "${S0(q)}" service. Consider using Container.unbind() instead.`;var Z;throw new v1(y1.invalidOperation,J)}#U(q){return JW(q)?this.#O(q):this.#C(q)}#O(q){let J=this.#J.getById(q.id),Z=b8(this.#$,J);if(Z!==void 0)return Z.then(()=>{this.#K(q)});this.#K(q)}#K(q){this.#J.removeById(q.id),this.#Q.clearCache()}#j(q){for(let J of q)this.#q.removeAllByModuleId(J.id),this.#J.removeAllByModuleId(J.id),this.#Z.removeAllByModuleId(J.id);this.#Q.clearCache()}#C(q){let J=H5(this.#$,q);if(J!==void 0)return J.then(()=>{this.#I(q)});this.#I(q)}#I(q){this.#q.removeAllByServiceId(q),this.#J.removeAllByServiceId(q),this.#Z.removeAllByServiceId(q),this.#Q.clearCache()}}var U5=k1(_q(),1);class u8{constructor(q,J,Z,Q,$){this.deviceModel=q,this.serviceUuid=J,this.writeUuid=Z,this.writeCmdUuid=Q,this.notifyUuid=$}}class L1{id;productName;usbProductId;bootloaderUsbProductId;usbOnly;memorySize;getBlockSize;masks;bluetoothSpec;constructor(q){this.id=q.id,this.productName=q.productName,this.usbProductId=q.usbProductId,this.bootloaderUsbProductId=q.bootloaderUsbProductId,this.usbOnly=q.usbOnly,this.memorySize=q.memorySize,this.getBlockSize=q.getBlockSize,this.masks=q.masks,this.bluetoothSpec=q.bluetoothSpec}}var{defineProperty:$W,getOwnPropertyDescriptor:aw}=Object,ow=(q,J,Z)=>(J in q)?$W(q,J,{enumerable:!0,configurable:!0,writable:!0,value:Z}):q[J]=Z,rw=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?aw(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&$W(J,Z,$),$},tw=(q,J,Z)=>ow(q,typeof J!="symbol"?J+"":J,Z),X1=class{getAllDeviceModels(){return Object.values(X1.deviceModelByIds)}getDeviceModel(q){return X1.deviceModelByIds[q.id]}filterDeviceModels(q){return this.getAllDeviceModels().filter((J)=>Object.entries(q).every(([Z,Q])=>J[Z]===Q))}getBluetoothServicesInfos(){return Object.values(X1.deviceModelByIds).reduce((q,J)=>{let{bluetoothSpec:Z}=J;return Z?{...q,...Z.reduce((Q,$)=>({...Q,[$.serviceUuid]:new u8(J,$.serviceUuid,$.writeUuid,$.writeCmdUuid,$.notifyUuid)}),{})}:q},{})}getBluetoothServices(){return Object.values(X1.deviceModelByIds).map((q)=>(q.bluetoothSpec||[]).map((J)=>J.serviceUuid)).flat().filter((q)=>!!q)}};tw(X1,"deviceModelByIds",{[o.NANO_S]:new L1({id:o.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:327680,getBlockSize:(q)=>U5.default.lt(U5.default.coerce(q.firmwareVersion)??"","2.0.0")?4096:2048,masks:[823132160]}),[o.NANO_SP]:new L1({id:o.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1569792,getBlockSize:()=>512,masks:[856686592]}),[o.NANO_X]:new L1({id:o.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2097152,getBlockSize:()=>4096,masks:[855638016],bluetoothSpec:[{serviceUuid:"13d63400-2c97-0004-0000-4c6564676572",notifyUuid:"13d63400-2c97-0004-0001-4c6564676572",writeUuid:"13d63400-2c97-0004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-0004-0003-4c6564676572"}]}),[o.STAX]:new L1({id:o.STAX,productName:"Ledger Stax",usbProductId:96,bootloaderUsbProductId:6,usbOnly:!1,memorySize:1569792,getBlockSize:()=>512,masks:[857735168],bluetoothSpec:[{serviceUuid:"13d63400-2c97-6004-0000-4c6564676572",notifyUuid:"13d63400-2c97-6004-0001-4c6564676572",writeUuid:"13d63400-2c97-6004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-6004-0003-4c6564676572"}]}),[o.FLEX]:new L1({id:o.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1569792,getBlockSize:()=>512,masks:[858783744],bluetoothSpec:[{serviceUuid:"13d63400-2c97-3004-0000-4c6564676572",notifyUuid:"13d63400-2c97-3004-0001-4c6564676572",writeUuid:"13d63400-2c97-3004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-3004-0003-4c6564676572"}]}),[o.APEX]:new L1({id:o.APEX,productName:"Ledger Nano Gen5",usbProductId:128,bootloaderUsbProductId:8,usbOnly:!1,memorySize:1569792,getBlockSize:()=>512,masks:[859832320],bluetoothSpec:[{serviceUuid:"13d63400-2c97-8004-0000-4c6564676572",notifyUuid:"13d63400-2c97-8004-0001-4c6564676572",writeUuid:"13d63400-2c97-8004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-8004-0003-4c6564676572"},{serviceUuid:"13d63400-2c97-9004-0000-4c6564676572",notifyUuid:"13d63400-2c97-9004-0001-4c6564676572",writeUuid:"13d63400-2c97-9004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-9004-0003-4c6564676572"}]})}),X1=rw([I()],X1);class bq{statusCode;data;constructor({statusCode:q,data:J}){this.statusCode=q,this.data=J}}var WW=5,A1=1,U6=2,g1=2,K6=2;class YW extends a{makeStateMachine(q){let{getOsVersion:J,getDeviceVersion:Z,getFirmwareVersion:Q,genuineCheck:$,getDeviceSessionState:W,setDeviceSessionState:Y}=this.extractDependencies(q),z=this.input.unlockTimeout??t,X=new f0({input:{unlockTimeout:z}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{goToDashboard:X,getOsVersion:d(J),getDeviceVersion:d(Z),getFirmwareVersion:d(Q),genuineCheck:O0($)},guards:{hasError:(w)=>w.context._internalState.error!==null},actions:{assignErrorFromEvent:N({_internalState:(w)=>({...w.context._internalState,error:w.event.error})})}}).createMachine({id:"GenuineCheckDeviceAction",initial:"DeviceReady",context:(w)=>({input:{unlockTimeout:w.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None},_internalState:{error:null,result:{isGenuine:!1},getOsVersionResponse:null,deviceVersion:null,firmwareVersion:null}}),states:{DeviceReady:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:()=>w.context._internalState,Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(w)=>{},onDone:{target:"GetOsVersionCheck",actions:N({_internalState:(w)=>{if(n(w.event.output)){let F=W(),_=w.event.output.data.secureElementFlags.isSecureConnectionAllowed;return F.sessionStateType!==m.Connected&&Y({...F,isSecureConnectionAllowed:_}),{...w.context._internalState,getOsVersionResponse:w.event.output.data}}return{...w.context._internalState,error:w.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetDeviceVersion"}]},GetDeviceVersion:{invoke:{id:"getDeviceVersion",src:"getDeviceVersion",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse}),onDone:{target:"GetDeviceVersionCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,deviceVersion:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetFirmwareVersion"}]},GetFirmwareVersion:{invoke:{id:"getFirmwareVersion",src:"getFirmwareVersion",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,deviceVersion:w.context._internalState.deviceVersion}),onDone:{target:"GetFirmwareVersionCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,firmwareVersion:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetFirmwareVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GenuineCheck"}]},GenuineCheck:{invoke:{id:"genuineCheck",src:"genuineCheck",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,finalFirmware:w.context._internalState.firmwareVersion}),onSnapshot:{actions:N({intermediateValue:(w)=>{switch(w.event.snapshot.context?.type){case M.DeviceId:return{...w.context.intermediateValue,deviceId:w.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...w.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:return{...w.context.intermediateValue,requiredUserInteraction:k.None};default:return{...w.context.intermediateValue}}},_internalState:(w)=>w.event.snapshot.context?.type===M.Error?{...w.context._internalState,error:w.event.snapshot.context.error.mapDAErrors()}:w.event.snapshot.context?.type===M.Result?{...w.context._internalState,result:{isGenuine:Z$(w.event.snapshot.context.payload)}}:w.context._internalState})},onDone:{target:"GenuineCheckCheck"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GenuineCheckCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(w)=>w.context._internalState.error?j(w.context._internalState.error):L(w.context._internalState.result)})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new M0),getDeviceVersion:({input:J})=>{let{deviceInfo:Z}=J;return q.getManagerApiService().getDeviceVersion(Z)},getFirmwareVersion:({input:J})=>{let{deviceInfo:Z,deviceVersion:Q}=J;return q.getManagerApiService().getFirmwareVersion(Z,Q)},genuineCheck:({input:J})=>{let{deviceInfo:Z,finalFirmware:Q}=J,$=q.getSecureChannelService().genuineCheck(Z,Q);return new c0(q,{connection:$}).run()},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}class Tq extends a{makeStateMachine(q){let{getOsVersion:J,getDeviceVersion:Z,getFirmwareVersion:Q,listInstalledApps:$,getDeviceSessionState:W,setDeviceSessionState:Y}=this.extractDependencies(q),z=this.input.unlockTimeout??t,X=new f0({input:{unlockTimeout:z}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{goToDashboard:X,getOsVersion:d(J),getDeviceVersion:d(Z),getFirmwareVersion:d(Q),listInstalledApps:O0($)},guards:{hasError:(w)=>w.context._internalState.error!==null},actions:{assignErrorFromEvent:N({_internalState:(w)=>({...w.context._internalState,error:w.event.error})})}}).createMachine({id:"ListInstalledAppsDeviceAction",initial:"DeviceReady",context:(w)=>({input:{unlockTimeout:w.input.unlockTimeout},intermediateValue:{requiredUserInteraction:k.None},_internalState:{error:null,getOsVersionResponse:null,deviceVersion:null,firmwareVersion:null,result:{installedApps:[]}}}),states:{DeviceReady:{always:{target:"GoToDashboard"}},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:()=>w.context._internalState,Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(w)=>{},onDone:{target:"GetOsVersionCheck",actions:N({_internalState:(w)=>{if(n(w.event.output)){let F=W(),_=w.event.output.data.secureElementFlags.isSecureConnectionAllowed;return F.sessionStateType!==m.Connected&&Y({...F,isSecureConnectionAllowed:_}),{...w.context._internalState,getOsVersionResponse:w.event.output.data}}return{...w.context._internalState,error:w.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetDeviceVersion"}]},GetDeviceVersion:{invoke:{id:"getDeviceVersion",src:"getDeviceVersion",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse}),onDone:{target:"GetDeviceVersionCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,deviceVersion:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetDeviceVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetFirmwareVersion"}]},GetFirmwareVersion:{invoke:{id:"getFirmwareVersion",src:"getFirmwareVersion",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,deviceVersion:w.context._internalState.deviceVersion}),onDone:{target:"GetFirmwareVersionCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,firmwareVersion:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetFirmwareVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"ListInstalledApps"}]},ListInstalledApps:{invoke:{id:"listInstalledApps",src:"listInstalledApps",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,finalFirmware:w.context._internalState.firmwareVersion}),onSnapshot:{actions:N({intermediateValue:(w)=>{switch(w.event.snapshot.context?.type){case M.DeviceId:return{...w.context.intermediateValue,deviceId:w.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...w.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:return{...w.context.intermediateValue,requiredUserInteraction:k.None};default:return{...w.context.intermediateValue}}},_internalState:(w)=>{if(w.event.snapshot.context?.type===M.Error)return{...w.context._internalState,error:w.event.snapshot.context.error.mapDAErrors()};if(w.event.snapshot.context?.type===M.Result){if(I8(w.event.snapshot.context.payload))return{...w.context._internalState,result:{installedApps:w.event.snapshot.context.payload}};throw Error(`Invalid result ${JSON.stringify(w.event.snapshot.context.payload)}`)}return{...w.context._internalState}}})},onDone:{target:"Success"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListInstalledAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:(w)=>w.context._internalState.error?j(w.context._internalState.error):L(w.context._internalState.result)})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new M0),getDeviceVersion:({input:J})=>{let{deviceInfo:Z}=J;return q.getManagerApiService().getDeviceVersion(Z)},getFirmwareVersion:({input:J})=>{let{deviceInfo:Z,deviceVersion:Q}=J;return q.getManagerApiService().getFirmwareVersion(Z,Q)},listInstalledApps:({input:J})=>{let{deviceInfo:Z,finalFirmware:Q}=J,$=q.getSecureChannelService().listInstalledApps(Z,Q);return new c0(q,{connection:$}).run()},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}class zW extends a{makeStateMachine(q){let{getOsVersion:J,getAppList:Z,installApp:Q,getDeviceSessionState:$,setDeviceSessionState:W}=this.extractDependencies(q),Y=this.input.unlockTimeout??t,z=new Tq({input:{unlockTimeout:Y}}).makeStateMachine(q),X=new f0({input:{unlockTimeout:Y}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{listInstalledApps:z,goToDashboard:X,getOsVersion:d(J),getAppList:d(Z),installApp:O0(Q)},guards:{hasError:(w)=>w.context._internalState.error!==null,appInstalled:(w)=>w.context._internalState.installedApps.some((F)=>F.name===w.context.input.appName),appNotFound:(w)=>w.context._internalState.appList.findIndex(({versionName:F})=>F===w.context.input.appName)===-1,depAppNotInstalled:(w)=>{let F=w.context._internalState.appList.find(({versionName:_})=>_===w.context.input.appName);return F?.parentName?w.context._internalState.installedApps.findIndex(({name:_})=>_===F.parentName)===-1:!1}},actions:{assignErrorFromEvent:N({_internalState:(w)=>({...w.context._internalState,error:w.event.error})}),assignAppNotFound:N({_internalState:(w)=>({...w.context._internalState,error:new q0("App to install not found in manager API")})}),assignDepAppNotInstalled:N({_internalState:(w)=>({...w.context._internalState,error:new q0("Dep app is not installed on the device")})}),cleanupDeviceState:()=>{let w=$();w.sessionStateType!==m.Connected&&W({...w,installedApps:[],appsUpdates:void 0})}}}).createMachine({id:"InstallAppDeviceAction",initial:"DeviceReady",context:(w)=>({input:{unlockTimeout:w.input.unlockTimeout,appName:w.input.appName},intermediateValue:{requiredUserInteraction:k.None,progress:0},_internalState:{error:null,installedApps:[],getOsVersionResponse:null,appList:[]}}),states:{DeviceReady:{always:{target:"ListInstalledApps"}},ListInstalledApps:{value:"ListInstalledApps",invoke:{id:"listInstalledApps",src:"listInstalledApps",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"ListInstalledAppsCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:({installedApps:F})=>({...w.context._internalState,installedApps:F}),Left:(F)=>({...w.context._internalState,error:F})})})}}},ListInstalledAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"appInstalled"},{target:"GoToDashboard"}]},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:()=>w.context._internalState,Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(w)=>{},onDone:{target:"GetOsVersionCheck",actions:N({_internalState:(w)=>{if(n(w.event.output)){let F=$(),_=w.event.output.data.secureElementFlags.isSecureConnectionAllowed;return F.sessionStateType!==m.Connected&&W({...F,isSecureConnectionAllowed:_}),{...w.context._internalState,getOsVersionResponse:w.event.output.data}}return{...w.context._internalState,error:w.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetAppList"}]},GetAppList:{invoke:{id:"getAppList",src:"getAppList",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse}),onDone:{target:"GetAppListCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,appList:F}),Left:(F)=>({...w.context._internalState,error:F})})})}}},GetAppListCheck:{always:[{target:"Error",guard:"hasError"},{target:"Error",guard:"appNotFound",actions:"assignAppNotFound"},{target:"Error",guard:"depAppNotInstalled",actions:"assignDepAppNotInstalled"},{target:"InstallApp"}]},InstallApp:{invoke:{id:"installApp",src:"installApp",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,app:w.context._internalState.appList.find(({versionName:F})=>F===w.context.input.appName)}),onSnapshot:{actions:N({intermediateValue:(w)=>w.event.snapshot.context?.type===M.DeviceId?{...w.context.intermediateValue,deviceId:w.event.snapshot.context.payload.deviceId}:w.event.snapshot.context?.type===M.Progress?{...w.context.intermediateValue,progress:w.event.snapshot.context.payload.progress}:{...w.context.intermediateValue},_internalState:(w)=>w.event.snapshot.context?.type===M.Error?{...w.context._internalState,error:w.event.snapshot.context.error.mapInstallDAErrors()}:w.context._internalState})},onDone:{target:"ListInstalledApps",actions:"cleanupDeviceState"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final",description:"App installed successfully"},Error:{type:"final"}},output:({context:w})=>w._internalState.error?j(w._internalState.error):L(void 0)})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new M0),getAppList:({input:J})=>{let{deviceInfo:Z}=J;return q.getManagerApiService().getAppList(Z)},installApp:({input:J})=>{let{deviceInfo:Z,app:Q}=J,$=q.getSecureChannelService().installApp(Z,Q);return new c0(q,{connection:$}).run()},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}class wW extends a{makeStateMachine(q){let{getOsVersion:J,getAppsByHash:Z,uninstallApp:Q,getDeviceSessionState:$,setDeviceSessionState:W}=this.extractDependencies(q),Y=this.input.unlockTimeout??t,z=new f0({input:{unlockTimeout:Y}}).makeStateMachine(q),X=new Tq({input:{unlockTimeout:Y}}).makeStateMachine(q);return i({types:{input:{},context:{},output:{}},actors:{listInstalledApps:X,goToDashboard:z,getOsVersion:d(J),getAppsByHash:d(Z),uninstallApp:O0(Q)},guards:{hasError:(w)=>w.context._internalState.error!==null,appNotInstalled:(w)=>!w.context._internalState.installedApps.some((F)=>F.name===w.context.input.appName),appNotFound:(w)=>w.context._internalState.appList.findIndex((F)=>F?.versionName===w.context.input.appName)===-1,isDepAppOfOther:(w)=>w.context._internalState.appList.some((F)=>F?.parentName===w.context.input.appName)},actions:{assignErrorFromEvent:N({_internalState:(w)=>({...w.context._internalState,error:w.event.error})}),assignAppNotFound:N({_internalState:(w)=>({...w.context._internalState,error:new q0("App to uninstall not found in manager API")})}),assignIsDepAppOfOther:N({_internalState:(w)=>({...w.context._internalState,error:new q0("App to uninstall is a dependency of another installed app")})}),cleanupDeviceState:()=>{let w=$();w.sessionStateType!==m.Connected&&W({...w,installedApps:[],appsUpdates:void 0})}}}).createMachine({id:"UninstallAppDeviceAction",initial:"DeviceReady",context:(w)=>({input:{unlockTimeout:w.input.unlockTimeout,appName:w.input.appName},intermediateValue:{requiredUserInteraction:k.None},_internalState:{error:null,installedApps:[],appList:[],getOsVersionResponse:null}}),states:{DeviceReady:{always:{target:"ListInstalledApps"}},ListInstalledApps:{invoke:{id:"listInstalledApps",src:"listInstalledApps",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"ListInstalledAppsCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:({installedApps:F})=>({...w.context._internalState,installedApps:F,hasCheckedInstalledApps:!0}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ListInstalledAppsCheck:{always:[{target:"Error",guard:"hasError"},{target:"Success",guard:"appNotInstalled"},{target:"GetAppsByHash"}]},GetAppsByHash:{invoke:{id:"getAppsByHash",src:"getAppsByHash",input:(w)=>w.context._internalState.installedApps,onDone:{target:"GetAppsByHashCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:(F)=>({...w.context._internalState,appList:F}),Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GetAppsByHashCheck:{always:[{target:"Error",guard:"hasError"},{target:"Error",guard:"appNotFound",actions:"assignAppNotFound"},{target:"Error",guard:"isDepAppOfOther",actions:"assignIsDepAppOfOther"},{target:"GoToDashboard"}]},GoToDashboard:{invoke:{id:"goToDashboard",src:"goToDashboard",input:(w)=>({unlockTimeout:w.context.input.unlockTimeout}),onSnapshot:{actions:N({intermediateValue:(w)=>({...w.context.intermediateValue,requiredUserInteraction:w.event.snapshot.context.intermediateValue.requiredUserInteraction})})},onDone:{target:"GoToDashboardCheck",actions:N({_internalState:(w)=>w.event.output.caseOf({Right:()=>w.context._internalState,Left:(F)=>({...w.context._internalState,error:F})})})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},GoToDashboardCheck:{always:[{target:"Error",guard:"hasError"},{target:"GetOsVersion"}]},GetOsVersion:{invoke:{id:"getOsVersion",src:"getOsVersion",input:(w)=>{},onDone:{target:"GetOsVersionCheck",actions:N({_internalState:(w)=>{if(n(w.event.output)){let F=$(),_=w.event.output.data.secureElementFlags.isSecureConnectionAllowed;return F.sessionStateType!==m.Connected&&W({...F,isSecureConnectionAllowed:_}),{...w.context._internalState,getOsVersionResponse:w.event.output.data}}return{...w.context._internalState,error:w.event.output.error}}})}}},GetOsVersionCheck:{always:[{target:"Error",guard:"hasError"},{target:"UninstallApp"}]},UninstallApp:{invoke:{id:"uninstallApp",src:"uninstallApp",input:(w)=>({deviceInfo:w.context._internalState.getOsVersionResponse,app:w.context._internalState.appList.find((F)=>F?.versionName===w.context.input.appName)}),onSnapshot:{actions:N({intermediateValue:(w)=>{switch(w.event.snapshot.context?.type){case M.DeviceId:return{...w.context.intermediateValue,deviceId:w.event.snapshot.context.payload.deviceId};case M.PermissionRequested:return{...w.context.intermediateValue,requiredUserInteraction:k.AllowSecureConnection};case M.PermissionGranted:return{...w.context.intermediateValue,requiredUserInteraction:k.None};default:return{...w.context.intermediateValue}}},_internalState:(w)=>w.event.snapshot.context?.type===M.Error?{...w.context._internalState,error:w.event.snapshot.context.error.mapDAErrors()}:w.context._internalState})},onDone:{target:"ListInstalledApps",actions:"cleanupDeviceState"},onError:{target:"Error",actions:"assignErrorFromEvent"}}},Success:{type:"final",description:"App uninstalled successfully"},Error:{type:"final"}},output:({context:w})=>w._internalState.error?j(w._internalState.error):L(void 0)})}extractDependencies(q){return{getOsVersion:()=>q.sendCommand(new M0),getAppsByHash:({input:J})=>{let Z=J.map((Q)=>Q.hash);return q.getManagerApiService().getAppsByHash(Z)},uninstallApp:({input:J})=>{let{deviceInfo:Z,app:Q}=J,$=q.getSecureChannelService().uninstallApp(Z,Q);return new c0(q,{connection:$}).run()},getDeviceSessionState:()=>q.getDeviceSessionState(),setDeviceSessionState:(J)=>q.setDeviceSessionState(J)}}}var ew=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),K5={randomUUID:ew};var j5,qX=new Uint8Array(16);function I5(){if(!j5){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");j5=crypto.getRandomValues.bind(crypto)}return j5(qX)}var C0=[];for(let q=0;q<256;++q)C0.push((q+256).toString(16).slice(1));function XW(q,J=0){return(C0[q[J+0]]+C0[q[J+1]]+C0[q[J+2]]+C0[q[J+3]]+"-"+C0[q[J+4]]+C0[q[J+5]]+"-"+C0[q[J+6]]+C0[q[J+7]]+"-"+C0[q[J+8]]+C0[q[J+9]]+"-"+C0[q[J+10]]+C0[q[J+11]]+C0[q[J+12]]+C0[q[J+13]]+C0[q[J+14]]+C0[q[J+15]]).toLowerCase()}function JX(q,J,Z){if(K5.randomUUID&&!J&&!q)return K5.randomUUID();q=q||{};let Q=q.random||(q.rng||I5)();if(Q[6]=Q[6]&15|64,Q[8]=Q[8]&63|128,J){Z=Z||0;for(let $=0;$<16;++$)J[Z+$]=Q[$];return J}return XW(Q)}var R1=JX;var Q1={getLastBytesFrom(q,J){return q.slice(-J)},getFirstBytesFrom(q,J){return q.slice(0,J)},bytesToNumber(q){return q.reduce((J,Z,Q)=>J+Z*Math.pow(256,q.length-1-Q),0)},numberToByteArray(q,J){return new Uint8Array(J).map((Z,Q)=>q>>8*(J-1-Q)&255)}};var L5=2,g8=800;class m8{_tag="FramerOverflowError";originalError;constructor(){this.originalError=Error("Frame header length is greater than frame size")}}class A5{_tag="FramerApduError";originalError;constructor(){this.originalError=Error("Frame offset is greater than apdu length")}}class l8{_tag="ReceiverApduError";originalError;constructor(q){this.originalError=Error(q??"Unable to parse apdu")}}class d8{_tag="DeviceSessionNotFound";originalError;constructor(q){this.originalError=q??Error("Device session not found")}}class j6{_header;_data;constructor({header:q,data:J}){this._header=q,this._data=J}toString(){return JSON.stringify({header:this._header.toString(),data:D0(this._data)},null,2)}getRawData(){let q=this._header.getRawData(),J=new Uint8Array(q.length+this._data.length);return J.set(q,0),J.set(this._data,q.length),J}getHeader(){return this._header}getData(){return this._data}}class I6{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:q,dataSize:J,index:Z,headTag:Q,length:$,channel:W}){this._uuid=q,this._dataLength=J,this._index=Z,this._headTag=Q,this._length=$,this._channel=W}getDataLength(){return this._dataLength.map((q)=>Q1.bytesToNumber(q))}setDataSize(q){return this._dataLength=q,this}getLength(){return this._length}toString(){return JSON.stringify({uuid:this._uuid.toString(),dataSize:this._dataLength.extract()?.toString(),index:this._index.toString(),headTag:this._headTag.toString(),length:this._length.toString(),channel:this._channel.extract()?.toString()})}getRawData(){return new Uint8Array([...this._channel.caseOf({Just:(q)=>[...q],Nothing:()=>[]}),...this._headTag,...this._index,...this._dataLength.caseOf({Just:(q)=>[...q],Nothing:()=>[]})])}}var f={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var{defineProperty:ZX,getOwnPropertyDescriptor:QX}=Object,$X=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?QX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&ZX(J,Z,$),$},WX=(q,J)=>(Z,Q)=>J(Z,Q,q),Mq=class{_channel;_logger;_pendingFrames;constructor({channel:q=Z0.zero()},J){this._channel=q,this._logger=J("ApduReceiverService"),this._pendingFrames=[]}handleFrame(q){return this.getFrameFromBytes(q).map((J)=>{if(this._pendingFrames.push(J),!this._pendingFrames[0])return p;let Z=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(Z)})}getCompleteFrame(q){return q.chain((J)=>{if(!this.isComplete(J))return this._logger.debug("frame is not complete, waiting for more"),p;let Z=Q1.getFirstBytesFrom(this.concatFrames(this._pendingFrames),J),Q=Q1.getFirstBytesFrom(Z,Z.length-L5),$=Q1.getLastBytesFrom(Z,L5);return this._pendingFrames=[],L0(new bq({data:Q,statusCode:$}))})}getFrameFromBytes(q){let J=this._channel.caseOf({Just:()=>U6,Nothing:()=>0}),Z=q.slice(J,J+A1),Q=q.slice(J+A1,J+A1+g1),$=Q.reduce((_,G)=>_+G,0)===0;if(!$&&this._pendingFrames.length===0)return j(new l8);let W=J+A1+g1,Y=$?K6:0;if(q.length<J+A1+g1+Y)return j(new l8("Unable to parse header from apdu"));let z=$?L0(q.slice(W,W+Y)):p,X=W+Y,w=q.slice(X),F=new j6({header:new I6({uuid:R1(),channel:this._channel,dataSize:z,headTag:Z,index:Q,length:J+A1+g1+Y}),data:w});return L(F)}isComplete(q){return this._pendingFrames.reduce((J,Z)=>J+Z.getData().length,0)>=q}concatFrames(q){return q.reduce((J,Z)=>Uint8Array.from([...J,...Z.getData()]),new Uint8Array(0))}};Mq=$X([I(),WX(1,U(f.LoggerPublisherServiceFactory))],Mq);var YX=(q={},J)=>new Mq({channel:Z0.of(new Uint8Array([18,52])),...q},J);var{defineProperty:zX,getOwnPropertyDescriptor:wX}=Object,XX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?wX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&zX(J,Z,$),$},FX=(q,J)=>(Z,Q)=>J(Z,Q,q),fq=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:q,channel:J=Z0.zero(),padding:Z=!1},Q){this._frameSize=q,this._channel=J,this._padding=Z,this._logger=Q("DefaultApduSenderService")}getFrames(q){let J=[],Z=0,Q=this.getFrameAtIndex(q,Z);for(;Q.isRight();)J.push(Q.extract()),Z+=1,Q=this.getFrameAtIndex(q,Z).mapLeft(($)=>($ instanceof m8||this._logger.error("Error while parsing frame",{data:{error:$}}),$));return J}getFrameAtIndex(q,J){let Z=this.getFrameHeaderFrom(J,q.length),Q=J===0?0:J*this._frameSize-this.getHeaderSizeSumFrom(J);if(Q>=q.length)return j(new m8);if(Z.getLength()>this._frameSize)return j(new A5);let $=this._frameSize-Z.getLength(),W=q.slice(Q,Q+this._frameSize-Z.getLength()),Y=this._padding?new Uint8Array($).fill(0):new Uint8Array(W.length<$?W.length:$);Y.set(W,0);let z=new j6({header:Z,data:Y});return L(z)}getFrameHeaderFrom(q,J){let Z=new I6({uuid:R1(),channel:this._channel.map((Q)=>Q1.getLastBytesFrom(Q,U6)),headTag:new Uint8Array([WW]),index:Q1.numberToByteArray(q,g1),length:this.getFrameHeaderSizeFromIndex(q),dataSize:Z0.zero()});return q===0&&Z.setDataSize(Z0.of(Q1.numberToByteArray(J,K6))),Z}getHeaderSizeSumFrom(q){let J=this.getFrameHeaderSizeFromIndex(0),Z=1;for(;Z<q;)J+=this.getFrameHeaderSizeFromIndex(Z),Z+=1;return J}getFrameHeaderSizeFromIndex(q){return this._channel.caseOf({Just:()=>U6,Nothing:()=>0})+g1+A1+(q===0?K6:0)}};fq=XX([I(),FX(1,U(f.LoggerPublisherServiceFactory))],fq);var _X=(q={},J)=>new fq({frameSize:64,channel:Z0.of(new Uint8Array([18,52])),padding:!0,...q},J);var L6={SendCommandUseCase:Symbol.for("SendCommandUseCase")};var p0={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService"),GetDmkVersionUseCase:Symbol.for("GetDmkVersionUseCase")};var v={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService"),GetDeviceSessionStateUseCase:Symbol.for("GetDeviceSessionStateUseCase"),DisableDeviceSessionRefresherUseCase:Symbol.for("DisableDeviceSessionRefresherUseCase"),CloseSessionsUseCase:Symbol.for("CloseSessionsUseCase"),UnsafeBypassIntentQueueUseCase:Symbol.for("UnsafeBypassIntentQueueUseCase")};var r={StartDiscoveringUseCase:Symbol.for("StartDiscoveringUseCase"),StopDiscoveringUseCase:Symbol.for("StopDiscoveringUseCase"),ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase"),GetConnectedDeviceUseCase:Symbol.for("GetConnectedDeviceUseCase"),ListenToAvailableDevicesUseCase:Symbol.for("ListenToAvailableDevicesUseCase"),ListenToConnectedDeviceUseCase:Symbol.for("ListenToConnectedDeviceUseCase"),ListConnectedDevicesUseCase:Symbol.for("ListConnectedDevicesUseCase"),ReconnectUseCase:Symbol.for("ReconnectUseCase")};var Y0={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig"),SetProviderUseCase:Symbol.for("SetProviderUseCase"),SetFirmwareDistributionSaltUseCase:Symbol.for("SetFirmwareDistributionSaltUseCase")};var b0={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig"),SetWebSocketUrlUseCase:Symbol.for("SetWebSocketUrlUseCase")};var A6={SendApduUseCase:Symbol.for("SendApduUseCase")};var j0={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var{defineProperty:HX,getOwnPropertyDescriptor:GX}=Object,NX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?GX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&HX(J,Z,$),$},FW=(q,J)=>(Z,Q)=>J(Z,Q,q),c8=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("SendCommandUseCase")}async execute({sessionId:q,command:J,abortTimeout:Z}){return this._sessionService.getDeviceSessionById(q).caseOf({Right:async(Q)=>await Q.sendCommand(J,Z),Left:(Q)=>{throw this._logger.error("Error getting session",{data:{error:Q}}),Q}})}};c8=NX([I(),FW(0,U(v.DeviceSessionService)),FW(1,U(f.LoggerPublisherServiceFactory))],c8);var{defineProperty:VX,getOwnPropertyDescriptor:BX}=Object,DX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?BX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&VX(J,Z,$),$},J0=class{execute=vi.fn(()=>"stub")};J0=DX([I()],J0);var _W=({stub:q=!1}={})=>new F0(({bind:J,rebindSync:Z})=>{J(L6.SendCommandUseCase).to(c8),q&&Z(L6.SendCommandUseCase).to(J0)});var{defineProperty:UX,getOwnPropertyDescriptor:KX}=Object,jX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?KX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&UX(J,Z,$),$},HW=(q,J)=>(Z,Q)=>J(Z,Q,q),p8=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("ExecuteDeviceActionUseCase")}execute({sessionId:q,deviceAction:J}){return this._sessionService.getDeviceSessionById(q).caseOf({Right:(Z)=>Z.executeDeviceAction(J),Left:(Z)=>{throw this._logger.error("Error getting session",{data:{error:Z}}),Z}})}};p8=jX([I(),HW(0,U(v.DeviceSessionService)),HW(1,U(f.LoggerPublisherServiceFactory))],p8);var R6={ExecuteDeviceActionUseCase:Symbol.for("ExecuteDeviceActionUseCase")};var GW=({stub:q=!1}={})=>new F0(({bind:J,rebindSync:Z})=>{J(R6.ExecuteDeviceActionUseCase).to(p8),q&&Z(R6.ExecuteDeviceActionUseCase).to(J0)});function NW(q){return typeof q=="object"&&q!==null&&"version"in q&&"name"in q&&typeof q.version=="string"&&typeof q.name=="string"}class s8{constructor(q){this.err=q,this.originalError=q}_tag="ApiCallError";originalError}class R5{constructor(q){this.err=q,this.originalError=q}_tag="ParseResponseError";originalError}class P6{constructor(q){this.err=q,this.originalError=q}_tag="JSONParseError";originalError}class P5{constructor(q){this.err=q,this.originalError=q}_tag="ReadFileError";originalError}var E5={dependencies:{"@noble/hashes":"^1.8.0","@sentry/minimal":"catalog:",inversify:"catalog:","isomorphic-ws":"catalog:","purify-ts":"catalog:","reflect-metadata":"catalog:",semver:"catalog:",uuid:"catalog:",ws:"catalog:",xstate:"catalog:"},devDependencies:{"@ledgerhq/eslint-config-dsdk":"workspace:^","@ledgerhq/ldmk-tool":"workspace:^","@ledgerhq/prettier-config-dsdk":"workspace:^","@ledgerhq/tsconfig-dsdk":"workspace:^","@ledgerhq/vitest-config-dmk":"workspace:^","@statelyai/inspect":"catalog:","@types/semver":"catalog:","@types/uuid":"catalog:","@types/ws":"catalog:",rxjs:"catalog:","ts-node":"catalog:"},exports:{".":{import:"./lib/esm/index.js",require:"./lib/cjs/index.js",types:"./lib/types/index.d.ts"}},files:["./lib","package.json"],license:"Apache-2.0",name:"@ledgerhq/device-management-kit",peerDependencies:{rxjs:"catalog:"},private:!1,repository:{type:"git",url:"https://github.com/LedgerHQ/device-sdk-ts.git"},scripts:{build:"pnpm ldmk-tool build --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",dev:'concurrently "pnpm watch:builds" "pnpm watch:types"',lint:"eslint","lint:fix":"pnpm lint --fix","module:create":"pnpm hygen core-module with-prompt",postpack:"find . -name '*.tgz' -exec cp {} ../../dist/ \\; ",prebuild:"rimraf lib",prettier:"prettier . --check","prettier:fix":"prettier . --write",test:"vitest run","test:coverage":"vitest run --coverage","test:watch":"vitest",typecheck:"tsc --noEmit","watch:builds":"pnpm ldmk-tool watch --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json","watch:types":'concurrently "tsc --watch -p tsconfig.prod.json" "tsc-alias --watch -p tsconfig.prod.json"'},version:"1.11.0"};var{defineProperty:LX,getOwnPropertyDescriptor:AX}=Object,RX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?AX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&LX(J,Z,$),$},PX={name:E5.name,version:E5.version},EX=()=>JSON.stringify(PX),n8=class{getConfig(){return A0.encase(()=>EX()).mapLeft((q)=>new P5(q)).chain((q)=>A0.encase(()=>{let J=JSON.parse(q);if(NW(J))return J;throw Error("Invalid config file")}).mapLeft((J)=>new P6(J)))}};n8=RX([I()],n8);var{defineProperty:xX,getOwnPropertyDescriptor:kX}=Object,OX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?kX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&xX(J,Z,$),$},i8=class{getConfig(){return A0.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};i8=OX([I()],i8);var{defineProperty:CX,getOwnPropertyDescriptor:bX}=Object,TX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?bX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&CX(J,Z,$),$},a8=class{async getConfig(){let q=await this._callApi();if(q.isLeft())return j(new s8(q.extract()));if(!q.extract().ok)return j(new s8(Error("response not ok")));let J=await q.extract().json();return J.isLeft()?j(new P6):J.chain((Z)=>this._parseResponse(Z)).map((Z)=>Z)}_parseResponse(q){let{name:J,version:Z}=q;return!J||!Z?j(new R5):A0.of({name:J,version:Z})}_callApi(){return new Promise((q)=>{q(A0.of({ok:!0,json:async()=>new Promise((J)=>{J(A0.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};a8=TX([I()],a8);var{defineProperty:MX,getOwnPropertyDescriptor:fX}=Object,SX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?fX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&MX(J,Z,$),$},o8=class{async getConfig(){return new Promise((q)=>q(A0.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};o8=SX([I()],o8);var{defineProperty:hX,getOwnPropertyDescriptor:vX}=Object,yX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?vX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&hX(J,Z,$),$},x5=(q,J)=>(Z,Q)=>J(Z,Q,q),r8=class{_local;_remote;_logger;constructor(q,J,Z){this._local=q,this._remote=J,this._logger=Z("config")}async getDmkConfig(){let q=this._local.getConfig().ifLeft((J)=>{this._logger.error("Local config not available",{data:{error:J}})});if(q.isRight()){let J=q.extract();return this._logger.info("Local config available",{data:{config:J}}),J}return this._remote.getConfig().then((J)=>J.mapLeft((Z)=>(this._logger.error("Local config available",{data:{error:Z}}),{name:"DeadDmk",version:"0.0.0-dead.1"})).extract())}};r8=yX([I(),x5(0,U(p0.LocalConfigDataSource)),x5(1,U(p0.RemoteConfigDataSource)),x5(2,U(f.LoggerPublisherServiceFactory))],r8);var{defineProperty:uX,getOwnPropertyDescriptor:gX}=Object,mX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?gX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&uX(J,Z,$),$},lX=(q,J)=>(Z,Q)=>J(Z,Q,q),t8=class{_configService;constructor(q){this._configService=q}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};t8=mX([I(),lX(0,U(p0.ConfigService))],t8);var VW=({stub:q})=>new F0(({bind:J,rebindSync:Z})=>{J(p0.LocalConfigDataSource).to(n8),J(p0.RemoteConfigDataSource).to(a8),J(p0.GetDmkVersionUseCase).to(t8),J(p0.ConfigService).to(r8),q&&(Z(p0.LocalConfigDataSource).to(i8),Z(p0.RemoteConfigDataSource).to(o8))});var e8={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var BW=({stub:q})=>new F0(({bind:J})=>{J(e8.DeviceModelDataSource).to(X1)});var{defineProperty:dX,getOwnPropertyDescriptor:cX}=Object,pX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?cX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&dX(J,Z,$),$},DW=(q,J)=>(Z,Q)=>J(Z,Q,q),q9=class{constructor(q,J){this._sessionService=q,this._logger=J("DisableDeviceSessionRefresherUseCase")}_logger;execute({sessionId:q,blockerId:J}){return this._sessionService.getDeviceSessionById(q).caseOf({Left:(Z)=>{throw this._logger.error("Error getting device session",{data:{error:Z}}),Z},Right:(Z)=>Z.disableRefresher(J)})}};q9=pX([I(),DW(0,U(v.DeviceSessionService)),DW(1,U(f.LoggerPublisherServiceFactory))],q9);import{ReplaySubject as oX}from"rxjs";var{defineProperty:sX,getOwnPropertyDescriptor:nX}=Object,iX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?nX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&sX(J,Z,$),$},aX=(q,J)=>(Z,Q)=>J(Z,Q,q),J9=class{_sessions;_sessionsSubject;_logger;constructor(q){this._sessions=[],this._sessionsSubject=new oX,this._logger=q("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(q){return this._sessions.find((J)=>J.id===q.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:q}}),this):(this._sessions.push(q),this._sessionsSubject.next(q),this._logger.info("DeviceSession added",{data:{sessionId:q.id}}),this)}removeDeviceSession(q){let J=this._sessions.find((Z)=>Z.id===q);return J?(J.close(),this._sessions=this._sessions.filter((Z)=>Z.id!==q),this._logger.info("DeviceSession removed",{data:{sessionId:q}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:q}}),this)}getDeviceSessionById(q){return Z0.fromNullable(this._sessions.find((J)=>J.id===q)).toEither(new d8)}getDeviceSessionsByDeviceId(q){return Z0.fromPredicate(({length:J})=>J>0,this._sessions.filter((J)=>J.connectedDevice.id===q)).toEither(new d8)}getDeviceSessions(){return this._sessions}};J9=iX([I(),aX(0,U(f.LoggerPublisherServiceFactory))],J9);var{defineProperty:rX,getOwnPropertyDescriptor:tX}=Object,eX=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?tX(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&rX(J,Z,$),$},UW=(q,J)=>(Z,Q)=>J(Z,Q,q),Z9=class{_sessionService;_transportService;constructor(q,J){this._sessionService=q,this._transportService=J}execute(){let q=this._sessionService.getDeviceSessions();for(let J of q)this._transportService.closeConnection(J.connectedDevice),this._sessionService.removeDeviceSession(J.id)}};Z9=eX([I(),UW(0,U(v.DeviceSessionService)),UW(1,U(j0.TransportService))],Z9);var{defineProperty:qF,getOwnPropertyDescriptor:JF}=Object,ZF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?JF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&qF(J,Z,$),$},KW=(q,J)=>(Z,Q)=>J(Z,Q,q),Q9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("GetDeviceSessionStateUseCase")}execute({sessionId:q}){return this._sessionService.getDeviceSessionById(q).caseOf({Left:(J)=>{throw this._logger.error("Error getting session device",{data:{error:J}}),J},Right:(J)=>J.state})}};Q9=ZF([I(),KW(0,U(v.DeviceSessionService)),KW(1,U(f.LoggerPublisherServiceFactory))],Q9);var{defineProperty:QF,getOwnPropertyDescriptor:$F}=Object,WF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?$F(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&QF(J,Z,$),$},jW=(q,J)=>(Z,Q)=>J(Z,Q,q),$9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("UnsafeBypassIntentQueueUseCase")}execute({sessionId:q,bypass:J}){this._sessionService.getDeviceSessionById(q).caseOf({Left:(Z)=>{throw this._logger.error("Error getting session",{data:{error:Z}}),Z},Right:(Z)=>{this._logger.warn(`UNSAFE: ${J?"Enabling":"Disabling"} intent queue bypass for session ${q}`),Z._unsafeBypassIntentQueue(J)}})}};$9=WF([I(),jW(0,U(v.DeviceSessionService)),jW(1,U(f.LoggerPublisherServiceFactory))],$9);var IW=({stub:q}={stub:!1})=>new F0(({bind:J,rebindSync:Z})=>{J(v.ApduSenderServiceFactory).toFactory((Q)=>{let $=Q.get(f.LoggerPublisherServiceFactory);return(W)=>new fq(W,$)}),J(v.ApduReceiverServiceFactory).toFactory((Q)=>{let $=Q.get(f.LoggerPublisherServiceFactory);return(W={})=>new Mq(W,$)}),J(v.DeviceSessionService).to(J9).inSingletonScope(),J(v.GetDeviceSessionStateUseCase).to(Q9),J(v.CloseSessionsUseCase).to(Z9),J(v.DisableDeviceSessionRefresherUseCase).to(q9),J(v.UnsafeBypassIntentQueueUseCase).to($9),q&&(Z(v.GetDeviceSessionStateUseCase).to(J0),Z(v.DisableDeviceSessionRefresherUseCase).to(J0),Z(v.UnsafeBypassIntentQueueUseCase).to(J0))});import{BehaviorSubject as BF,from as kW,lastValueFrom as OW,timeout as CW}from"rxjs";function LW(q){return`[will send APDU] ~...> ${D0(q,!1)}`}function YF(q){return`[exchange] => ${D0(q,!1)}`}function AW(q){return`[exchange] <= ${D0(q.data,!1)}${D0(q.statusCode,!1)}`}var zF="apdu-exchange";function RW(q,J,Z){let Q=D0(J,!1),$=`${D0(Z.data,!1)}${D0(Z.statusCode,!1)}`;return{message:AW(Z),data:{type:zF,sessionId:q,apdu:Q,response:$}}}var E6=1000,W9=1000,PW={isRefresherDisabled:!1,pollingInterval:1000};import{finalize as XF,Subject as FF}from"rxjs";import{Subject as wF}from"rxjs";var Q0=((q)=>(q.NEW_STATE="NEW_STATE",q.REFRESH_NEEDED="REFRESH_NEEDED",q.COMMAND_SUCCEEDED="COMMAND_SUCCEEDED",q.DEVICE_STATE_UPDATE_BUSY="DEVICE_STATE_UPDATE_BUSY",q.DEVICE_STATE_UPDATE_LOCKED="DEVICE_STATE_UPDATE_LOCKED",q.DEVICE_STATE_UPDATE_CONNECTED="DEVICE_STATE_UPDATE_CONNECTED",q.DEVICE_STATE_UPDATE_UNKNOWN="DEVICE_STATE_UPDATE_UNKNOWN",q))(Q0||{});class k5{_eventEmitter=new wF;listen(){return this._eventEmitter.asObservable()}dispatch(q){this._eventEmitter.next(q)}}class O5{constructor(q,J){this.loggerModuleFactory=q,this.sessionEventDispatcher=J,this._logger=this.loggerModuleFactory("IntentQueueService")}_logger;_queue=[];_isProcessing=!1;_currentSubscription=null;enqueue(q){this._logger.debug("Enqueueing intent",{data:{type:q.type}});let J=new FF,Z={intent:q,subject:J,isCancelled:!1};this._queue.push(Z);let Q=()=>{this._logger.debug("Cancelling intent",{data:{type:q.type}}),Z.isCancelled=!0,this._queue[0]===Z&&this._currentSubscription?(this._currentSubscription.unsubscribe(),this._currentSubscription=null,J.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue()):(!this._isProcessing||this._queue[0]!==Z)&&J.complete()};return this._isProcessing||this._processQueue(),{observable:J.asObservable().pipe(XF(()=>{this._logger.debug("Intent observable finalized",{data:{type:q.type}})})),cancel:Q}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:Q0.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:Q0.DEVICE_STATE_UPDATE_BUSY}),this._isProcessing=!0;let q=this._queue[0];if(q.isCancelled){this._logger.debug("Skipping cancelled intent",{data:{type:q.intent.type}}),q.subject.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue();return}this._logger.debug("Processing intent",{data:{type:q.intent.type}}),this._currentSubscription=q.intent.execute().subscribe({next:(J)=>{q.isCancelled||q.subject.next(J)},error:(J)=>{q.isCancelled||q.subject.error(J),this._onIntentComplete()},complete:()=>{q.isCancelled||q.subject.complete(),this._onIntentComplete()}})}_onIntentComplete(){this._logger.debug("Intent completed"),this._currentSubscription=null,this._queue.shift(),this._isProcessing=!1,this._processQueue()}}class C5{constructor(q,J){this._refresher=J,this._logger=q("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(q){let J=`${q}-${R1()}`;this.addRefresherBlocker(J),this._logger.debug("Refresher disabled",{data:{blockerId:J,blockers:Array.from(this._refresherBlockers)}});let Z=!1;return()=>{Z||(Z=!0,this.removeRefresherBlocker(J),this._logger.debug("Refresher re-enabled",{data:{blockerId:J,blockers:Array.from(this._refresherBlockers)}}))}}addRefresherBlocker(q){let J=this._refresherBlockers.size;this._refresherBlockers.add(q),J===0&&this._refresher.stop()}removeRefresherBlocker(q){let J=this._refresherBlockers.size;this._refresherBlockers.delete(q),J>0&&this._refresherBlockers.size===0&&this._refresher.start()}}class b5{constructor(q,J,Z,Q){this.connectedDevice=J,this._sessionEventDispatcher=Z,this._sendCommandFunction=Q,this._logger=q("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async($)=>await this.mapEventAction($))}_sendCommandFunction;_subscription;_logger;async ping(){try{return await this.mapDevicePingAction(this.connectedDevice.deviceModel.id)}catch(q){return this._logger.error("Error while pinging device",{data:{error:q}}),null}}mapEventAction=async(q)=>{switch(q.eventName){case Q0.REFRESH_NEEDED:return await this.ping();default:return null}};async mapDevicePingAction(q){switch(q){case o.NANO_S:{let J=async()=>{let $=await this._sendCommandFunction(new a0,g8);return this._sendCommandFunction(new M0,g8),$},Z=new Promise(($)=>{setTimeout(()=>$(null),E6*2+100)}),Q=await Promise.race([J(),Z]);return Q?this._sessionEventDispatcher.dispatch({eventName:Q0.COMMAND_SUCCEEDED,eventData:Q}):this._sessionEventDispatcher.dispatch({eventName:Q0.DEVICE_STATE_UPDATE_LOCKED}),Q}default:{let J=await this._sendCommandFunction(new a0,g8);return this._sessionEventDispatcher.dispatch({eventName:Q0.COMMAND_SUCCEEDED,eventData:J}),J}}}unsubscribe(){this._subscription.unsubscribe()}}import{distinctUntilChanged as _F,filter as EW,map as HF,startWith as GF,tap as xW,timer as NF,withLatestFrom as VF}from"rxjs";class T5{constructor(q,J,Z,Q){this._sessionEventDispatcher=Z,this._refresherOptions=J,this._logger=q("device-session-refresher"),this._connectedDeviceID=Q.deviceModel.id}_refresherSubscription;_refresherOptions;_logger;_connectedDeviceID;startRefresher(){if(this._refresherOptions.isRefresherDisabled||this._refresherSubscription)return;let q=this.getValidPollingInterval(this._refresherOptions,this._logger),J=this._sessionEventDispatcher.listen().pipe(EW((Z)=>Z.eventName===Q0.DEVICE_STATE_UPDATE_BUSY||Z.eventName===Q0.NEW_STATE),HF((Z)=>Z.eventName===Q0.DEVICE_STATE_UPDATE_BUSY),GF(!1),_F());this._refresherSubscription=NF(0,q).pipe(VF(J),xW(([Z,Q])=>{Q&&this._logger.debug("Refresh skipped: device is busy")}),EW(([Z,Q])=>!Q),xW(()=>this._sessionEventDispatcher.dispatch({eventName:Q0.REFRESH_NEEDED}))).subscribe(),this._logger.info("Refresher started.")}stopRefresher(){this._refresherSubscription&&(this._refresherSubscription.unsubscribe(),this._refresherSubscription=void 0,this._logger.info("Refresher stopped."))}restartRefresher(){this.stopRefresher(),this.startRefresher(),this._logger.info("Refresher restarted.")}getValidPollingInterval=(q,J)=>{let{pollingInterval:Z}=q;switch(this._connectedDeviceID){case o.NANO_S:{let Q=E6*2;return Z!==void 0&&Z<Q?(J.warn(`Polling interval of ${Z} is too low, setting to minimum as ${Q}`),Q):Z??Q}default:return Z!==void 0&&Z<W9?(J.warn(`Polling interval of ${Z} is too low, setting to minimum as ${W9}`),W9):Z??E6}}}class M5{constructor(q,J,Z,Q,$){this._sessionEventDispatcher=J,this._connectedDevice=Z,this._deviceState=Q,this.setDeviceSessionState=$,this._subscription=this._sessionEventDispatcher.listen().subscribe((W)=>this.mapEventAction(W)),this._logger=q("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=g0.BUSY;_updateDeviceState(q){let J=this._parseDeviceStatus(q);if(J){let{sessionStateType:Z,deviceStatus:Q,currentApp:$}=J,W=this._deviceState.getValue();W.sessionStateType===m.Connected?this.setDeviceSessionState({sessionStateType:Z,deviceStatus:Q,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:$,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...W,sessionStateType:Z,deviceStatus:Q,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:$})}}mapEventAction=(q)=>{let{eventName:J}=q;switch(J){case Q0.COMMAND_SUCCEEDED:return this._updateDeviceState(q.eventData);case Q0.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:g0.BUSY});case Q0.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=g0.LOCKED;return;case Q0.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=g0.CONNECTED;return;case Q0.NEW_STATE:{let Z=this._pendingDeviceStatus;return this._pendingDeviceStatus=g0.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Z})}case Q0.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:g0.BUSY});case Q0.REFRESH_NEEDED:return;default:throw Error(`Unhandled context type ${J}`)}};_parseDeviceStatus(q){return n(q)?{sessionStateType:m.ReadyWithoutSecureChannel,deviceStatus:g0.CONNECTED,currentApp:{name:q.data.name,version:q.data.version}}:(this._logger.debug("Error while parsing APDU response",{data:{parsedResponse:q}}),null)}unsubscribe(){this._subscription.unsubscribe()}}class x6{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new k5;_bypassIntentQueue=!1;constructor({connectedDevice:q,id:J=R1()},Z,Q,$,W,Y=(z)=>new O5(Z,z)){this._id=J,this._connectedDevice=q,this._loggerModuleFactory=Z,this._logger=Z("device-session"),this._managerApiService=Q,this._intentQueueService=Y(this._sessionEventDispatcher),this._secureChannelService=$,this._refresherOptions={...PW,...W},this._deviceState=new BF({sessionStateType:m.Connected,deviceStatus:g0.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new b5(Z,q,this._sessionEventDispatcher,(z,X)=>this.sendCommand(z,X)),this._deviceSessionRefresher=new T5(Z,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new M5(Z,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,(z)=>this.setDeviceSessionState(z)),this._refresherService=new C5(Z,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{this._refresherOptions.isRefresherDisabled?await this._pinger.ping():this._deviceSessionRefresher.startRefresher()}catch(q){throw this._logger.error("Error while initialising session",{data:{error:q}}),q}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(q){this._deviceState.next(q)}sendApdu(q,J={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._bypassIntentQueue?this._unsafeInternalSendApdu(q,J):this._internalSendApdu(q,J)}_internalSendApdu(q,J){let Z=J.abortTimeout,Q=Date.now(),{observable:$,cancel:W}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>kW((async()=>{let z=Date.now()-Q;return await this._unsafeInternalSendApdu(q,{isPolling:J.isPolling,triggersDisconnection:J.triggersDisconnection,abortTimeout:Z?Z-z:void 0})})())}),Y=Z?$.pipe(CW({each:Z,with:()=>{throw W(),new fJ}})):$;return OW(Y)}async _unsafeInternalSendApdu(q,J={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(LW(q)),(await this._connectedDevice.sendApdu(q,J.triggersDisconnection,J.abortTimeout)).ifRight((Z)=>{let{message:Q,data:$}=RW(this._id,q,Z);this._logger.debug(Q,{data:$}),l.isLockedDeviceResponse(Z)?this._sessionEventDispatcher.dispatch({eventName:Q0.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:Q0.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:Q0.DEVICE_STATE_UPDATE_UNKNOWN})})}sendCommand(q,J){return this._logger.debug(`[sendCommand] ${q.name}`),this._bypassIntentQueue?this._unsafeInternalSendCommand(q,J):this._internalSendCommand(q,J)}_internalSendCommand(q,J){let Z=Date.now(),{observable:Q,cancel:$}=this._intentQueueService.enqueue({type:"send-command",execute:()=>kW((async()=>{let Y=Date.now()-Z;return await this._unsafeInternalSendCommand(q,J?J-Y:void 0)})())}),W=J?Q.pipe(CW({each:J,with:()=>{throw $(),new SJ}})):Q;return OW(W)}async _unsafeInternalSendCommand(q,J){let Z=q.getApdu();return(await this._unsafeInternalSendApdu(Z.getRawApdu(),{isPolling:!1,triggersDisconnection:q.triggersDisconnection??!1,abortTimeout:J})).caseOf({Left:(Q)=>{throw this._logger.error("[sendCommand] error",{data:{err:Q}}),Q},Right:(Q)=>{let $=q.parseResponse(Q,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:$}}),$}})}executeDeviceAction(q){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(q):this._internalExecuteDeviceAction(q)}_internalExecuteDeviceAction(q){let J,{observable:Z,cancel:Q}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{let{observable:$,cancel:W}=this._unsafeInternalExecuteDeviceAction(q);return J=W,$}});return{observable:Z,cancel:()=>{J?.(),Q()}}}_unsafeInternalExecuteDeviceAction(q){let{observable:J,cancel:Z}=q._execute({sendApdu:async(Q)=>this._unsafeInternalSendApdu(Q),sendCommand:async(Q)=>this._unsafeInternalSendCommand(Q),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:(Q)=>(this.setDeviceSessionState(Q),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:J,cancel:Z}}close(){this._updateDeviceStatus(g0.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher(),this._pinger.unsubscribe()}disableRefresher(q){return this._refresherService.disableRefresher(q)}_unsafeBypassIntentQueue(q){this._bypassIntentQueue=q}_updateDeviceStatus(q){let J=this._deviceState.getValue();this._deviceState.next({...J,deviceStatus:q})}}var{defineProperty:DF,getOwnPropertyDescriptor:UF}=Object,KF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?UF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&DF(J,Z,$),$},k6=(q,J)=>(Z,Q)=>J(Z,Q,q),Y9=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(q,J,Z,Q,$){this._sessionService=J,this._transportService=q,this._loggerFactory=Z,this._logger=Z("ConnectUseCase"),this._managerApi=Q,this._secureChannel=$}handleDeviceDisconnect(q){this._sessionService.getDeviceSessionsByDeviceId(q).ifRight((J)=>{J.forEach((Z)=>{this._sessionService.removeDeviceSession(Z.id),this._logger.info("Session removed",{data:{deviceId:q,sessionId:Z.id}})})})}async execute({device:q,sessionRefresherOptions:J}){let Z=this._transportService.getTransport(q.transport),Q="sessionId"in q?q.sessionId:void 0;return h.liftEither(Z.toEither(new o1(Error("Unknown transport")))).chain(async($)=>$.connect({deviceId:q.id,onDisconnect:(W)=>this.handleDeviceDisconnect(W)})).ifLeft(($)=>{this._logger.error("Error connecting to device")}).map(async($)=>{let W=new x6({connectedDevice:$,id:Q},this._loggerFactory,this._managerApi,this._secureChannel,J);return this._sessionService.addDeviceSession(W),await W.initialiseSession(),W.id}).caseOf({Left:($)=>{throw $},Right:($)=>$})}};Y9=KF([I(),k6(0,U(j0.TransportService)),k6(1,U(v.DeviceSessionService)),k6(2,U(f.LoggerPublisherServiceFactory)),k6(3,U(Y0.ManagerApiService)),k6(4,U(b0.SecureChannelService))],Y9);var{defineProperty:jF,getOwnPropertyDescriptor:IF}=Object,LF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?IF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&jF(J,Z,$),$},f5=(q,J)=>(Z,Q)=>J(Z,Q,q),z9=class{_transportService;_sessionService;_logger;constructor(q,J,Z){this._sessionService=J,this._transportService=q,this._logger=Z("DisconnectUseCase")}async execute({sessionId:q}){return this._logger.debug("Disconnecting from device",{data:{test:this._sessionService.getDeviceSessions().map((J)=>J.id)}}),h(async({liftEither:J})=>{let Z=await J(this._sessionService.getDeviceSessionById(q).ifLeft((W)=>{this._logger.error("Device session not found",{data:{sessionId:q,error:W}})})),Q=Z.connectedDevice.transport,$=await J(this._transportService.getTransport(Q).toEither(new o1(Error("Unknown transport"))));Z.close(),this._sessionService.removeDeviceSession(q),await $.disconnect({connectedDevice:Z.connectedDevice})}).caseOf({Left:(J)=>{throw this._logger.error("Error disconnecting from device",{data:{error:J}}),J},Right:()=>{}})}};z9=LF([I(),f5(0,U(j0.TransportService)),f5(1,U(v.DeviceSessionService)),f5(2,U(f.LoggerPublisherServiceFactory))],z9);class m1{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:q,deviceModel:{id:J,productName:Z},type:Q,transport:$,name:W},sessionId:Y}){this.id=q,this.sessionId=Y,this.modelId=J,this.name=W??Z,this.type=Q,this.transport=$}}var{defineProperty:AF,getOwnPropertyDescriptor:RF}=Object,PF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?RF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&AF(J,Z,$),$},bW=(q,J)=>(Z,Q)=>J(Z,Q,q),w9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("GetConnectedDeviceUseCase")}execute({sessionId:q}){return this._sessionService.getDeviceSessionById(q).caseOf({Right:(J)=>new m1({sessionId:J.id,transportConnectedDevice:J.connectedDevice}),Left:(J)=>{throw this._logger.error("Error getting session",{data:{error:J}}),J}})}};w9=PF([I(),bW(0,U(v.DeviceSessionService)),bW(1,U(f.LoggerPublisherServiceFactory))],w9);var{defineProperty:EF,getOwnPropertyDescriptor:xF}=Object,kF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?xF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&EF(J,Z,$),$},TW=(q,J)=>(Z,Q)=>J(Z,Q,q),X9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("ListConnectedDeviceUseCase")}execute(){return this._logger.info("Listing connected devices"),this._sessionService.getDeviceSessions().map((q)=>new m1({transportConnectedDevice:q.connectedDevice,sessionId:q.id}))}};X9=kF([I(),TW(0,U(v.DeviceSessionService)),TW(1,U(f.LoggerPublisherServiceFactory))],X9);import{from as TF,map as S5,merge as MF,of as fF,scan as SF}from"rxjs";var{defineProperty:OF,getOwnPropertyDescriptor:CF}=Object,bF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?CF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&OF(J,Z,$),$},MW=(q,J)=>(Z,Q)=>J(Z,Q,q),F9=class{_transports;_transportService;_logger;constructor(q,J){this._transports=q.getAllTransports(),this._transportService=q,this._logger=J("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(q){let J=new Hq({id:q.id,model:q.deviceModel.id,name:q.deviceModel.productName});return{id:q.id,deviceModel:J,transport:q.transport,name:q.name||J.name,rssi:q.rssi}}execute({transport:q}={}){if(this._logger.info("Listening to available devices"),this._transports.length===0)return this._logger.warn("No transports available"),TF([[]]);if(!q){this._logger.info("Discovering all available transports");let J=this._transports.map((Z,Q)=>Z.listenToAvailableDevices().pipe(S5(($)=>({index:Q,arr:$}))));return MF(...J).pipe(SF((Z,{index:Q,arr:$})=>(Z[Q]=$,Z),{}),S5((Z)=>Object.values(Z).flat().map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))}return this._logger.info(`Discovering devices on transport ${q}`),this._transportService.getTransport(q).caseOf({Nothing:()=>(this._logger.error(`Transport ${q} not found`),fF([])),Just:(J)=>J.listenToAvailableDevices().pipe(S5((Z)=>Z.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};F9=bF([I(),MW(0,U(j0.TransportService)),MW(1,U(f.LoggerPublisherServiceFactory))],F9);import{map as uF}from"rxjs";var{defineProperty:hF,getOwnPropertyDescriptor:vF}=Object,yF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?vF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&hF(J,Z,$),$},fW=(q,J)=>(Z,Q)=>J(Z,Q,q),_9=class{constructor(q,J){this._sessionService=q,this._logger=J("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(uF((q)=>new m1({transportConnectedDevice:q.connectedDevice,sessionId:q.id})))}};_9=yF([I(),fW(0,U(v.DeviceSessionService)),fW(1,U(f.LoggerPublisherServiceFactory))],_9);var{defineProperty:gF,getOwnPropertyDescriptor:mF}=Object,lF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?mF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&gF(J,Z,$),$},h5=(q,J)=>(Z,Q)=>J(Z,Q,q),H9=class{constructor(q,J,Z){this.connectUseCase=q,this.disconnectUseCase=J,this._logger=Z("ReconnectUseCase")}_logger;async execute({device:q,sessionRefresherOptions:J}){return this._logger.debug("Reconnecting device session",{data:{deviceId:q.id,transport:q.transport}}),await this.disconnectUseCase.execute({sessionId:q.sessionId}),this.connectUseCase.execute({device:q,sessionRefresherOptions:J})}};H9=lF([I(),h5(0,U(r.ConnectUseCase)),h5(1,U(r.DisconnectUseCase)),h5(2,U(f.LoggerPublisherServiceFactory))],H9);import{map as SW,mergeMap as nF,of as iF}from"rxjs";var{defineProperty:dF,getOwnPropertyDescriptor:cF}=Object,pF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?cF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&dF(J,Z,$),$},sF=(q,J)=>(Z,Q)=>J(Z,Q,q),G9=class{constructor(q){this._transportService=q}mapDiscoveredDevice(q){let J=new Hq({id:q.id,model:q.deviceModel.id,name:q.deviceModel.productName});return{id:q.id,deviceModel:J,transport:q.transport,name:q.name||J.name,rssi:q.rssi}}execute({transport:q}={}){if(!q){let J=this._transportService.getAllTransports();return iF(...J).pipe(nF((Z)=>Z.startDiscovering().pipe(SW((Q)=>this.mapDiscoveredDevice(Q)))))}return this._transportService.getTransport(q).caseOf({Just:(J)=>J.startDiscovering().pipe(SW((Z)=>this.mapDiscoveredDevice(Z))),Nothing:()=>{throw new o1(Error("Unknown transport"))}})}};G9=pF([I(),sF(0,U(j0.TransportService))],G9);var{defineProperty:aF,getOwnPropertyDescriptor:oF}=Object,rF=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?oF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&aF(J,Z,$),$},hW=(q,J)=>(Z,Q)=>J(Z,Q,q),N9=class{constructor(q,J){this.transportService=q,this._logger=J("StopDiscoveringUseCase")}_logger;async execute(){this._logger.debug("Stopping discovering devices");for(let q of this.transportService.getAllTransports())await q.stopDiscovering()}};N9=rF([I(),hW(0,U(j0.TransportService)),hW(1,U(f.LoggerPublisherServiceFactory))],N9);var vW=({stub:q=!1})=>new F0(({bind:J,rebindSync:Z})=>{J(r.ConnectUseCase).to(Y9),J(r.DisconnectUseCase).to(z9),J(r.ReconnectUseCase).to(H9),J(r.StartDiscoveringUseCase).to(G9),J(r.StopDiscoveringUseCase).to(N9),J(r.GetConnectedDeviceUseCase).to(w9),J(r.ListenToAvailableDevicesUseCase).to(F9),J(r.ListenToConnectedDeviceUseCase).to(_9),J(r.ListConnectedDevicesUseCase).to(X9),q&&(Z(r.ConnectUseCase).to(J0),Z(r.DisconnectUseCase).to(J0),Z(r.StartDiscoveringUseCase).to(J0),Z(r.StopDiscoveringUseCase).to(J0),Z(r.GetConnectedDeviceUseCase).to(J0),Z(r.ListenToAvailableDevicesUseCase).to(J0),Z(r.ListenToConnectedDeviceUseCase).to(J0),Z(r.ListConnectedDevicesUseCase).to(J0))});var I0=((q)=>(q[q.Fatal=0]="Fatal",q[q.Error=1]="Error",q[q.Warning=2]="Warning",q[q.Info=3]="Info",q[q.Debug=4]="Debug",q))(I0||{});class V9{format(q){return Array.isArray(q)?q.map((J)=>`[${J}]`).join(" "):`[${q}]`}}function v5(q,J){if(typeof q=="bigint")return q.toString();if(Array.isArray(q))return J.has(q)?"[Circular]":(J.add(q),q.map((Z)=>v5(Z,J)));if(q!==null&&typeof q=="object"){if(J.has(q))return"[Circular]";J.add(q);let Z={};for(let[Q,$]of Object.entries(q))Z[Q]=v5($,J);return Z}return q}function yW(q){let J=new WeakSet;J.add(q);let Z={};for(let[Q,$]of Object.entries(q))Z[Q]=v5($,J);return Z}var{defineProperty:tF,getOwnPropertyDescriptor:eF}=Object,q_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?eF(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&tF(J,Z,$),$},B9=class{subscribers;tag;tagFormatter;constructor(q,J,Z=new V9){this.subscribers=q,this.tag=J,this.tagFormatter=Z}_log(q,J,Z){let Q=Z?.data?yW(Z.data):void 0,$=Z?.tag??this.tag,W=this.tagFormatter.format($);this.subscribers.forEach((Y)=>{let z={timestamp:Z?.timestamp??Date.now(),tag:W,data:Q};Y.log(q,J,z)})}info(q,J){this._log(I0.Info,q,J)}warn(q,J){this._log(I0.Warning,q,J)}debug(q,J){this._log(I0.Debug,q,J)}error(q,J){this._log(I0.Error,q,J)}};B9=q_([I()],B9);var uW=({subscribers:q}={subscribers:[]})=>new F0(({bind:J})=>{J(f.LoggerPublisherServiceFactory).toFactory((Z)=>(Q)=>new B9(q,Q))});class F1 extends Error{status;statusText;responseBody;isTimeout;cause;constructor(q){super(q.message),this.name="DmkNetworkClientError",this.status=q.status,this.statusText=q.statusText,this.responseBody=q.responseBody,this.isTimeout=q.isTimeout??!1,this.cause=q.cause}}var J_="application/json";function Z_(q,J){if(!J)return q;let Z=q.endsWith("/")?q.slice(0,-1):q,Q=J.startsWith("/")?J:`/${J}`;return`${Z}${Q}`}function Q_(q){let J=[];for(let[Z,Q]of Object.entries(q))Q!=null&&J.push(`${encodeURIComponent(Z)}=${encodeURIComponent(String(Q))}`);return J.join("&")}function P1(q){let{url:J,params:Z,baseUrl:Q}=q,$=/^[a-z][a-z0-9+.-]*:\/\//i.test(J)?J:Q?Z_(Q,J):J,W=Z?Q_(Z):"";if(W.length===0)return $;let Y=$.includes("?")?"&":"?";return`${$}${Y}${W}`}function $_(q,J){let Z=J.toLowerCase();return Object.keys(q).some((Q)=>Q.toLowerCase()===Z)}function W_(q){return!!(typeof q=="string"||q instanceof ArrayBuffer||ArrayBuffer.isView(q)||typeof Blob<"u"&&q instanceof Blob||typeof FormData<"u"&&q instanceof FormData||typeof URLSearchParams<"u"&&q instanceof URLSearchParams||typeof ReadableStream<"u"&&q instanceof ReadableStream)}function gW(q){let{method:J,body:Z,defaultHeaders:Q,perRequestHeaders:$}=q,W={...Q,...$};return Z===void 0||J==="GET"||J==="HEAD"?{body:void 0,headers:W}:W_(Z)?{body:Z,headers:W}:($_(W,"content-type")||(W["Content-Type"]=J_),{body:JSON.stringify(Z),headers:W})}function mW(q){let{timeoutMs:J}=q;if(!J||J<=0)return{signal:void 0,cleanup:()=>{}};let Z=new AbortController,Q=setTimeout(()=>{Z.abort()},J);return{signal:Z.signal,cleanup:()=>clearTimeout(Q)}}async function lW(q,J){switch(J){case"void":return;case"text":return await q.text();case"blob":return await q.blob();case"arrayBuffer":return await q.arrayBuffer();case"json":default:{let Z=await q.text();if(Z.length===0)return;try{return JSON.parse(Z)}catch(Q){throw new F1({message:"Failed to parse JSON response body",status:q.status,statusText:q.statusText,responseBody:Z,cause:Q})}}}}async function dW(q){try{return await q.text()}catch{return}}function cW(q){let{cause:J,timeoutMs:Z}=q,Q=!!(Z&&Z>0);if(J instanceof Error&&(J.name==="AbortError"||J.name==="TimeoutError")){let $=J.name==="TimeoutError"||Q;return new F1({message:$?"Request timed out":"Request aborted",isTimeout:$,cause:J})}return new F1({message:J instanceof Error?J.message:"Network request failed",cause:J})}class D9{baseUrl;defaultHeaders;fetchImpl;constructor(q={}){this.baseUrl=q.baseUrl,this.defaultHeaders=q.headers??{},this.fetchImpl=q.fetch}getFetch(){return this.fetchImpl??globalThis.fetch.bind(globalThis)}get(q,J){return this.request({...J,method:"GET",url:q}).then((Z)=>Z.data)}post(q,J,Z){return this.request({...Z,method:"POST",url:q,body:J}).then((Q)=>Q.data)}put(q,J,Z){return this.request({...Z,method:"PUT",url:q,body:J}).then((Q)=>Q.data)}patch(q,J,Z){return this.request({...Z,method:"PATCH",url:q,body:J}).then((Q)=>Q.data)}delete(q,J){return this.request({...J,method:"DELETE",url:q}).then((Z)=>Z.data)}head(q,J){return this.request({...J,method:"HEAD",url:q,responseType:"void"}).then(()=>{})}async request(q){let J=P1({url:q.url,params:q.params,baseUrl:this.baseUrl}),{body:Z,headers:Q}=gW({method:q.method,body:q.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:q.headers}),{signal:$,cleanup:W}=mW({timeoutMs:q.timeoutMs}),Y=q.throwOnHttpError??!0,z=q.responseType??"json";try{let X;try{X=await this.getFetch()(J,{method:q.method,headers:Q,body:Z,signal:$})}catch(w){throw cW({cause:w,timeoutMs:q.timeoutMs})}if(!X.ok&&Y){let w=await dW(X);throw new F1({message:`HTTP error ${X.status} ${X.statusText}`.trim(),status:X.status,statusText:X.statusText,responseBody:w})}return{data:await lW(X,z),status:X.status,statusText:X.statusText,headers:X.headers,ok:X.ok}}finally{W()}}}var Sq=((q)=>(q.currency="currency",q.plugin="plugin",q.tool="tool",q.swap="swap",q))(Sq||{});var U9="https://manager.api.live.ledger.com/api",K9="https://device-mock-server.aws.ldg-ps-default.ldg-tech.com",hq=1,vq="0";class Zq{constructor(q){this.error=q,this.originalError=q}_tag="FetchError";originalError}var yq=((q)=>(q.currency="currency",q.plugin="plugin",q.tool="tool",q.swap="swap",q))(yq||{});var{defineProperty:Y_,getOwnPropertyDescriptor:z_}=Object,w_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?z_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&Y_(J,Z,$),$},pW=(q,J)=>(Z,Q)=>J(Z,Q,q),E1=(q)=>q instanceof F1&&q.cause!==void 0?new Zq(q.cause):new Zq(q),j9=class{http;_provider=hq;_firmwareDistributionSalt=vq;_logger;constructor({managerApiUrl:q,provider:J,firmwareDistributionSalt:Z},Q){this.http=new D9({baseUrl:q}),this._provider=J,this._firmwareDistributionSalt=Z,this._logger=Q("HttpManagerApiDataSource")}setProvider(q){this._provider===q||q<1||(this._provider=q)}getProvider(){return this._provider}setFirmwareDistributionSalt(q){this._firmwareDistributionSalt===q||q.trim()===""||(this._firmwareDistributionSalt=q)}getFirmwareDistributionSalt(){return this._firmwareDistributionSalt}getAppList(q){let{targetId:J,firmwareVersionName:Z}=q;return h(()=>this.http.get("/v2/apps/by-target",{params:{target_id:J,provider:this._provider,firmware_version_name:Z}})).chain((Q)=>this.mapApplicationDtoToApplication(Q)).mapLeft(E1)}getMcuList(){return h(()=>this.http.get("/mcu_versions")).chain((q)=>this.mapMcuDtoToMcu(q)).mapLeft(E1)}getDeviceVersion(q){let{targetId:J}=q;return h(()=>this.http.get("/get_device_version",{params:{target_id:J,provider:this._provider}})).chain((Z)=>this.mapDeviceVersionDto(Z)).mapLeft(E1)}getFirmwareVersion(q){let{deviceId:J,version:Z}=q;return h(()=>this.http.get("/get_firmware_version",{params:{device_version:J,version_name:Z,provider:this._provider}})).chain((Q)=>this.mapFinalFirmwareDto(Q)).mapLeft(E1)}getFirmwareVersionById(q){return h(()=>this.http.get(`/firmware_final_versions/${q}`)).chain((J)=>this.mapFinalFirmwareDto(J)).mapLeft(E1)}getOsuFirmwareVersion(q){let{deviceId:J,version:Z}=q;return h(()=>this.http.get("/get_osu_version",{params:{device_version:J,version_name:Z,provider:this._provider}})).chain((Q)=>this.mapOsuFirmwareDto(Q)).mapLeft(E1)}getLatestFirmwareVersion(q){let{currentFinalFirmwareId:J,deviceId:Z}=q;return h(()=>{let Q=this._firmwareDistributionSalt;return this._logger.info("Requesting latest firmware",{data:{salt:Q}}),this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:J,device_version:Z,provider:this._provider,salt:Q}})}).chain((Q)=>this.mapLatestFirmwareDto(Q)).mapLeft(E1)}getAppsByHash(q){let{hashes:J}=q;return h(()=>this.http.post("/v2/apps/hash",J)).chain((Z)=>this.mapNullableApplicationDtoToApplication(Z)).mapLeft(E1)}getLanguagePackages(q){let{deviceId:J,currentFinalFirmwareId:Z}=q;return h(()=>this.http.get("/language-packages",{params:{device_version:J,current_se_firmware_final_version:Z}})).chain((Q)=>this.mapLanguagesDtoToLanguages(Q)).mapLeft(E1)}mapAppTypeDtoToAppType(q){if(q===null)return null;switch(q){case yq.currency:return Sq.currency;case yq.plugin:return Sq.plugin;case yq.tool:return Sq.tool;case yq.swap:return Sq.swap}}mapApplicationDtoToApplication(q){return h(()=>Promise.resolve(q.map((J)=>this.mapApplicationDto(J))))}mapNullableApplicationDtoToApplication(q){return h(()=>Promise.resolve(q.map((J)=>J===null?null:this.mapApplicationDto(J))))}mapApplicationDto(q){if(typeof q!="object"||typeof q.versionId!="number"||typeof q.versionName!="string"||q.versionDisplayName!==null&&typeof q.versionDisplayName!="string"||typeof q.version!="string"||q.currencyId!==null&&typeof q.currencyId!="string"||q.description!==null&&typeof q.description!="string"||q.applicationType!==null&&typeof q.applicationType!="string"||typeof q.dateModified!="string"||q.icon!==null&&typeof q.icon!="string"||q.authorName!==null&&typeof q.authorName!="string"||q.supportURL!==null&&typeof q.supportURL!="string"||q.contactURL!==null&&typeof q.contactURL!="string"||q.sourceURL!==null&&typeof q.sourceURL!="string"||q.compatibleWallets!==null&&typeof q.compatibleWallets!="string"||typeof q.hash!="string"||typeof q.perso!="string"||typeof q.firmware!="string"||typeof q.firmwareKey!="string"||typeof q.delete!="string"||typeof q.deleteKey!="string"||q.bytes!==null&&typeof q.bytes!="number"||q.warning!==null&&typeof q.warning!="string"||typeof q.isDevTools!="boolean"||q.category!==null&&typeof q.category!="number"||q.parent!==null&&typeof q.parent!="number"||q.parentName!==null&&typeof q.parentName!="string")throw Error(`Incomplete application: ${JSON.stringify(q)}`);let{applicationType:J,hash:Z,perso:Q,firmware:$,firmwareKey:W,delete:Y,deleteKey:z,...X}=q;return{...X,hash:Z,perso:Q,firmware:$,firmwareKey:W,delete:Y,deleteKey:z,applicationType:this.mapAppTypeDtoToAppType(J)}}mapMcuDtoToMcu(q){return h(()=>Promise.resolve(q.map((J)=>{if(typeof J!="object"||typeof J.id!="number"||typeof J.name!="string"||typeof J.from_bootloader_version!="string")throw Error(`Incomplete MCU version: ${JSON.stringify(J)}`);return{id:J.id,name:J.name,fromBootloaderVersion:J.from_bootloader_version,providers:J.providers}})))}mapDeviceVersionDto(q){return h(()=>{if(typeof q!="object"||typeof q.id!="number")throw Error(`Incomplete device version: ${JSON.stringify(q)}`);let J={id:q.id};return Promise.resolve(J)})}mapFinalFirmwareDto(q){return h(()=>{if(typeof q!="object"||typeof q.id!="number"||typeof q.version!="string"||typeof q.perso!="string"||q.firmware!==null&&typeof q.firmware!="string"||q.firmware_key!==null&&typeof q.firmware_key!="string"||q.hash!==null&&typeof q.hash!="string"||q.bytes!==null&&typeof q.bytes!="number"||!Array.isArray(q.mcu_versions))throw Error(`Incomplete final firmware: ${JSON.stringify(q)}`);let J={id:q.id,version:q.version,perso:q.perso,firmware:q.firmware,firmwareKey:q.firmware_key,hash:q.hash,bytes:q.bytes,mcuVersions:q.mcu_versions};return Promise.resolve(J)})}mapLatestFirmwareDto(q){return h(()=>{if(q.result==="null")return Promise.resolve(null);if(q.result!=="success"||!q.se_firmware_osu_version)throw Error(`Latest firmware could not be retrieved: ${q.result}`);let J=q.se_firmware_osu_version;return Promise.resolve(J)}).chain((J)=>J===null?h(()=>Promise.resolve(p)):this.mapOsuFirmwareDto(J).map((Z)=>L0(Z)))}mapOsuFirmwareDto(q){return h(()=>{if(typeof q!="object"||typeof q.id!="number"||q.notes!==null&&typeof q.notes!="string"||typeof q.perso!="string"||typeof q.firmware!="string"||typeof q.firmware_key!="string"||q.hash!==null&&typeof q.hash!="string"||typeof q.next_se_firmware_final_version!="number")throw Error(`Incomplete latest firmware: ${JSON.stringify(q)}`);let J={id:q.id,notes:q.notes,perso:q.perso,firmware:q.firmware,firmwareKey:q.firmware_key,hash:q.hash,nextFinalFirmware:q.next_se_firmware_final_version};return Promise.resolve(J)})}mapLanguagesDtoToLanguages(q){return h(()=>Promise.resolve(q.map((J)=>this.mapLanguageDto(J))))}mapLanguageDto(q){if(typeof q!="object"||typeof q.language!="string"||typeof q.languagePackageVersionId!="number"||typeof q.version!="string"||typeof q.language_package_id!="number"||typeof q.apdu_install_url!="string"||typeof q.apdu_uninstall_url!="string"||typeof q.bytes!="number"||typeof q.date_creation!="string"||typeof q.date_last_modified!="string")throw Error(`Incomplete language version: ${JSON.stringify(q)}`);return{language:q.language,languagePackageVersionId:q.languagePackageVersionId,version:q.version,languagePackageId:q.language_package_id,apduInstallUrl:q.apdu_install_url,apduUninstallUrl:q.apdu_uninstall_url,bytes:q.bytes,dateCreation:q.date_creation,dateLastModified:q.date_last_modified}}};j9=w_([I(),pW(0,U(Y0.DmkConfig)),pW(1,U(f.LoggerPublisherServiceFactory))],j9);var{defineProperty:X_,getOwnPropertyDescriptor:F_}=Object,__=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?F_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&X_(J,Z,$),$},H_=(q,J)=>(Z,Q)=>J(Z,Q,q),I9=class{constructor(q){this.dataSource=q}getAppList(q){let J={targetId:q.targetId.toString(),firmwareVersionName:q.seVersion};return this.dataSource.getAppList(J)}getDeviceVersion(q){let J={targetId:q.targetId.toString()};return this.dataSource.getDeviceVersion(J)}getFirmwareVersion(q,J){let Z={version:q.seVersion,deviceId:J.id};return this.dataSource.getFirmwareVersion(Z)}getOsuFirmwareVersion(q,J){let Z={version:q.seVersion,deviceId:J.id};return this.dataSource.getOsuFirmwareVersion(Z)}getLatestFirmwareVersion(q,J){let Z={currentFinalFirmwareId:q.id,deviceId:J.id};return this.dataSource.getLatestFirmwareVersion(Z)}getNextFirmwareVersion(q){return this.dataSource.getFirmwareVersionById(q.nextFinalFirmware)}getLanguagePackages(q,J){let Z={deviceId:q.id,currentFinalFirmwareId:J.id};return this.dataSource.getLanguagePackages(Z)}getMcuList(){return this.dataSource.getMcuList()}getAppsByHash(q){let J={hashes:q};return h(async({fromPromise:Z,throwE:Q})=>{if(J.hashes.length===0)return[];try{return await Z(this.dataSource.getAppsByHash(J))}catch($){return $ instanceof Zq?Q($):Q(new Zq($))}})}getProvider(){return this.dataSource.getProvider()}};I9=__([I(),H_(0,U(Y0.ManagerApiDataSource))],I9);var{defineProperty:G_,getOwnPropertyDescriptor:N_}=Object,V_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?N_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&G_(J,Z,$),$},y5=(q,J)=>(Z,Q)=>J(Z,Q,q),L9=class{constructor(q,J,Z){this.sessionService=q,this.managerApiDataSource=J,this._logger=Z("SetFirmwareDistributionSaltUseCase")}_logger;execute(q){if(q.trim()===""){this._logger.warn("Ignoring empty firmware distribution salt");return}let J=this.managerApiDataSource.getFirmwareDistributionSalt();if(q===J){this._logger.debug("Firmware distribution salt unchanged",{data:{salt:q}});return}this.managerApiDataSource.setFirmwareDistributionSalt(q);let Z=0;for(let Q of this.sessionService.getDeviceSessions()){let $=Q.getDeviceSessionState();$.sessionStateType!==m.Connected&&$.firmwareUpdateContext!==void 0&&(Q.setDeviceSessionState({...$,firmwareUpdateContext:void 0}),Z++)}this._logger.info("Firmware distribution salt updated",{data:{previousSalt:J,salt:q,invalidatedSessions:Z}})}};L9=V_([I(),y5(0,U(v.DeviceSessionService)),y5(1,U(Y0.ManagerApiDataSource)),y5(2,U(f.LoggerPublisherServiceFactory))],L9);var{defineProperty:B_,getOwnPropertyDescriptor:D_}=Object,U_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?D_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&B_(J,Z,$),$},sW=(q,J)=>(Z,Q)=>J(Z,Q,q),A9=class{constructor(q,J){this.sessionService=q,this.managerApiDataSource=J}execute(q){for(let J of this.sessionService.getDeviceSessions()){let Z=J.getDeviceSessionState();Z.sessionStateType!==m.Connected&&J.setDeviceSessionState({...Z,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(q)}};A9=U_([I(),sW(0,U(v.DeviceSessionService)),sW(1,U(Y0.ManagerApiDataSource))],A9);var nW=({stub:q,config:J})=>new F0(({bind:Z,rebindSync:Q})=>{Z(Y0.DmkConfig).toConstantValue(J),Z(Y0.ManagerApiDataSource).to(j9).inSingletonScope(),Z(Y0.ManagerApiService).to(I9).inSingletonScope(),Z(Y0.SetProviderUseCase).to(A9),Z(Y0.SetFirmwareDistributionSaltUseCase).to(L9),q&&(Q(Y0.ManagerApiDataSource).to(J0),Q(Y0.ManagerApiService).to(J0),Q(Y0.SetProviderUseCase).to(J0),Q(Y0.SetFirmwareDistributionSaltUseCase).to(J0))});var{defineProperty:K_,getOwnPropertyDescriptor:j_}=Object,I_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?j_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&K_(J,Z,$),$},L_=(q,J)=>(Z,Q)=>J(Z,Q,q),R9=class{webSocketBaseUrl;constructor({webSocketUrl:q}){this.webSocketBaseUrl=q}setWebSocketUrl(q){this.webSocketBaseUrl===q||q.length===0||(this.webSocketBaseUrl=q)}getWebSocketUrl(){return this.webSocketBaseUrl}genuineCheck(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:q});return this._connectWebSocket(J)}installApp(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/install",params:q});return this._connectWebSocket(J)}listInstalledApps(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:q});return this._connectWebSocket(J)}uninstallApp(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/install",params:q});return this._connectWebSocket(J)}updateFirmware(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/install",params:q});return this._connectWebSocket(J)}updateMcu(q){let J=P1({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:q});return this._connectWebSocket(J)}_connectWebSocket(q){try{return L(new L8(q))}catch(J){return j(new oJ(J))}}};R9=I_([I(),L_(0,U(b0.DmkConfig))],R9);var{defineProperty:A_,getOwnPropertyDescriptor:R_}=Object,P_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?R_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&A_(J,Z,$),$},E_=(q,J)=>(Z,Q)=>J(Z,Q,q),P9=class{constructor(q){this.dataSource=q}genuineCheck(q,J){let Z={targetId:q.targetId.toString(),perso:J.perso};return this.dataSource.genuineCheck(Z)}installApp(q,J){let{perso:Z,firmware:Q,firmwareKey:$,hash:W}=J,Y={targetId:q.targetId.toString(),perso:Z,firmware:Q,firmwareKey:$,hash:W};return this.dataSource.installApp(Y)}listInstalledApps(q,J){let Z={targetId:q.targetId.toString(),perso:J.perso};return this.dataSource.listInstalledApps(Z)}uninstallApp(q,J){let{perso:Z,delete:Q,deleteKey:$,hash:W}=J,Y={targetId:q.targetId.toString(),perso:Z,firmware:Q,firmwareKey:$,hash:W};return this.dataSource.uninstallApp(Y)}updateFirmware(q,J){let Z={targetId:q.targetId.toString(),perso:J.perso,firmware:J.firmware,firmwareKey:J.firmwareKey};return this.dataSource.updateFirmware(Z)}updateMcu(q,J){let Z={targetId:q.targetId.toString(),version:J.version};return this.dataSource.updateMcu(Z)}};P9=P_([I(),E_(0,U(b0.SecureChannelDataSource))],P9);var{defineProperty:x_,getOwnPropertyDescriptor:k_}=Object,O_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?k_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&x_(J,Z,$),$},C_=(q,J)=>(Z,Q)=>J(Z,Q,q),E9=class{constructor(q){this.secureChannelDataSource=q}execute(q){this.secureChannelDataSource.setWebSocketUrl(q)}};E9=O_([I(),C_(0,U(b0.SecureChannelDataSource))],E9);var iW=({stub:q,config:J})=>new F0(({bind:Z,rebindSync:Q})=>{Z(b0.DmkConfig).toConstantValue(J),Z(b0.SecureChannelDataSource).to(R9).inSingletonScope(),Z(b0.SecureChannelService).to(P9),Z(b0.SetWebSocketUrlUseCase).to(E9),q&&Q(b0.SetWebSocketUrlUseCase).to(J0)});var x9="wss://scriptrunner.api.live.ledger.com/update";var{defineProperty:b_,getOwnPropertyDescriptor:T_}=Object,M_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?T_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&b_(J,Z,$),$},aW=(q,J)=>(Z,Q)=>J(Z,Q,q),k9=class{_sessionService;_logger;constructor(q,J){this._sessionService=q,this._logger=J("SendApduUseCase")}async execute({sessionId:q,apdu:J,abortTimeout:Z,triggersDisconnection:Q}){return this._sessionService.getDeviceSessionById(q).caseOf({Right:async($)=>(await $.sendApdu(J,{abortTimeout:Z,triggersDisconnection:Q})).caseOf({Right:(W)=>W,Left:(W)=>{throw this._logger.error("Error sending APDU",{data:{sessionId:q,apdu:J,error:W}}),W}}),Left:($)=>{throw this._logger.error("Error getting deviceSession",{data:{error:$}}),$}})}};k9=M_([I(),aW(0,U(v.DeviceSessionService)),aW(1,U(f.LoggerPublisherServiceFactory))],k9);var oW=({stub:q=!1})=>new F0(({bind:J,rebindSync:Z})=>{J(A6.SendApduUseCase).to(k9),q&&Z(A6.SendApduUseCase).to(J0)});var{defineProperty:f_,getOwnPropertyDescriptor:S_}=Object,h_=(q,J,Z,Q)=>{for(var $=Q>1?void 0:Q?S_(J,Z):J,W=q.length-1,Y;W>=0;W--)(Y=q[W])&&($=(Q?Y(J,Z,$):Y($))||$);return Q&&$&&f_(J,Z,$),$},uq=(q,J)=>(Z,Q)=>J(Z,Q,q),O9=class{constructor(q,J,Z,Q,$,W){if(this._config=J,this._loggerModuleFactory=Z,this._deviceModelDataSource=Q,this._apduSenderServiceFactory=$,this._apduReceiverServiceFactory=W,this._logger=Z("TransportService"),q.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new yJ("No transports provided, please check your configuration");for(let Y of q){let z=this.addTransport(Y);if(z.isLeft())throw z.extract()}}_transports=new Map;_logger;addTransport(q){let J=q({deviceModelDataSource:this._deviceModelDataSource,loggerServiceFactory:this._loggerModuleFactory,config:this._config,apduSenderServiceFactory:this._apduSenderServiceFactory,apduReceiverServiceFactory:this._apduReceiverServiceFactory});return this.addTransportInternal(J)}addTransportInternal(q){return this.getTransport(q.getIdentifier()).isJust()?(this._logger.warn(`Transport ${q.getIdentifier()} already exists, please check your configuration`),j(new hJ(`Transport ${q.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(q.getIdentifier(),q),L(void 0))}getTransport(q){return Z0.fromNullable(this._transports.get(q))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(q){this.getTransport(q.transport).map((J)=>J.disconnect({connectedDevice:q}))}};O9=h_([I(),uq(0,U(j0.TransportsInput)),uq(1,U(j0.DmkConfig)),uq(2,U(f.LoggerPublisherServiceFactory)),uq(3,U(e8.DeviceModelDataSource)),uq(4,U(v.ApduSenderServiceFactory)),uq(5,U(v.ApduReceiverServiceFactory))],O9);var rW=({stub:q=!1,transports:J=[],config:Z}={})=>new F0(({bind:Q})=>{Q(j0.TransportsInput).toConstantValue(J),Q(j0.TransportService).to(O9).inSingletonScope(),Q(j0.DmkConfig).toConstantValue(Z)});var tW=({stub:q=!1,transports:J=[],loggers:Z=[],config:Q={mockUrl:K9,managerApiUrl:U9,webSocketUrl:x9,provider:hq,firmwareDistributionSalt:vq}})=>{let $=new y8;return $.loadSync(VW({stub:q}),BW({stub:q}),rW({stub:q,transports:J,config:Q}),nW({stub:q,config:Q}),iW({stub:q,config:Q}),vW({stub:q}),uW({subscribers:Z}),IW({stub:q}),oW({stub:q}),_W({stub:q}),GW({stub:q})),$};class C9{container;constructor({stub:q,transports:J,loggers:Z,config:Q}={}){this.container=tW({stub:q,transports:J,loggers:Z,config:Q})}getVersion(){return this.container.get(p0.GetDmkVersionUseCase).getDmkVersion()}startDiscovering(q){return this.container.get(r.StartDiscoveringUseCase).execute(q)}stopDiscovering(){return this.container.get(r.StopDiscoveringUseCase).execute()}listenToAvailableDevices(q){return this.container.get(r.ListenToAvailableDevicesUseCase).execute(q)}async reconnect(q){return this.container.get(r.ReconnectUseCase).execute(q)}connect(q){return this.container.get(r.ConnectUseCase).execute(q)}disconnect(q){return this.container.get(r.DisconnectUseCase).execute(q)}sendApdu(q){return this.container.get(A6.SendApduUseCase).execute(q)}sendCommand(q){return this.container.get(L6.SendCommandUseCase).execute(q)}executeDeviceAction(q){return this.container.get(R6.ExecuteDeviceActionUseCase).execute(q)}getConnectedDevice(q){return this.container.get(r.GetConnectedDeviceUseCase).execute(q)}getDeviceSessionState(q){return this.container.get(v.GetDeviceSessionStateUseCase).execute(q)}close(){return this.container.get(v.CloseSessionsUseCase).execute()}listConnectedDevices(){return this.container.get(r.ListConnectedDevicesUseCase).execute()}listenToConnectedDevice(){return this.container.get(r.ListenToConnectedDeviceUseCase).execute()}disableDeviceSessionRefresher(q){return this.container.get(v.DisableDeviceSessionRefresherUseCase).execute(q)}_unsafeBypassIntentQueue(q){return this.container.get(v.UnsafeBypassIntentQueueUseCase).execute(q)}setProvider(q){return this.container.get(Y0.SetProviderUseCase).execute(q)}getProvider(){return this.container.get(Y0.ManagerApiDataSource).getProvider()}setFirmwareDistributionSalt(q){return this.container.get(Y0.SetFirmwareDistributionSaltUseCase).execute(q)}getFirmwareDistributionSalt(){return this.container.get(Y0.ManagerApiDataSource).getFirmwareDistributionSalt()}setWebSocketUrl(q){return this.container.get(b0.SetWebSocketUrlUseCase).execute(q)}getWebSocketUrl(){return this.container.get(b0.SecureChannelDataSource).getWebSocketUrl()}isEnvironmentSupported(){return this.container.get(j0.TransportService).getAllTransports().some((q)=>q.isSupported())}getLoggerFactory(){return this.container.get(f.LoggerPublisherServiceFactory)}}class eW{stub=!1;loggers=[];transports=[];config={managerApiUrl:U9,mockUrl:K9,webSocketUrl:x9,provider:hq,firmwareDistributionSalt:vq};build(){return new C9({stub:this.stub,transports:this.transports,loggers:this.loggers,config:this.config})}setStub(q){return this.stub=q,this}addTransport(q){return this.transports.push(q),this}addLogger(q){return this.loggers.push(q),this}addConfig(q){return this.config={...this.config,...q},this}}class qY{maxLevel;constructor(q=I0.Debug){this.maxLevel=q}log(q,J,Z){let Q=Z.tag;switch(q){case I0.Info:{this.maxLevel>=I0.Info&&this.logWithData(Q,console.info,J,Z);break}case I0.Warning:{this.maxLevel>=I0.Warning&&this.logWithData(Q,console.warn,J,Z);break}case I0.Debug:{this.maxLevel>=I0.Debug&&this.logWithData(Q,console.debug,J,Z);break}case I0.Error:{this.maxLevel>=I0.Error&&this.logWithData(Q,console.error,J,Z);break}case I0.Fatal:{this.maxLevel>=I0.Fatal&&this.logWithData(Q,console.error,J,Z);break}default:this.logWithData(Q,console.log,J,Z)}}logWithData(q,J,Z,Q){Q.data?J(q,Z,Q.data):J(q,Z)}}function v_(){let q=[];return function(J,Z){if(Z instanceof Uint8Array){let Q=Array.from(Z).map(($)=>$.toString(16).padStart(2,"0"));return{hex:"0x"+Q.join(""),readableHex:Q.join(" "),value:Z.toString()}}if(Z instanceof x6){let{connectedDevice:{deviceModel:Q,type:$,id:W}}=Z;return{id:Z.id,connectedDevice:{deviceModel:Q,type:$,id:W}}}if(typeof Z!="object"||Z===null)return Z;for(;q.length>0&&q.at(-1)!==this;)q.pop();return q.includes(Z)?"[Circular]":(q.push(Z),Z)}}class JY{logs=[];log(q,J,Z){this.logs.push([q,J,Z])}formatLogsToJSON(){let q=this.logs.map(([J,Z,Q])=>{let{timestamp:$,...W}=Q;return{level:I0[J],message:Z,options:{...W,date:new Date(Q.timestamp)}}});return JSON.stringify(q,v_(),2)}exportLogsToJSON(){let q=this.formatLogsToJSON(),J=new Blob([q],{type:"application/json"}),Z=URL.createObjectURL(J),Q=document.createElement("a");Q.href=Z,Q.download=`ledger-device-management-kit-logs-${new Date().toISOString()}.json`,Q.click()}}var y_=1e4;class ZY{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;previousSendApduPromise=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(q){this.deviceId=q.deviceId,this.deviceAdpuSender=q.deviceApduSender,this.timeoutDuration=q.timeoutDuration,this.machineActor=e0(u_({sendApduFn:(J,Z,Q)=>this.sendApduToDeviceConnection(J,Z,Q),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},tryToReconnect:()=>{q.tryToReconnect(this.timeoutDuration)},onTerminated:q.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(q,J,Z){this.deviceAdpuSender.sendApdu(q,J,Z).then((Q)=>{Q.caseOf({Left:($)=>{this.machineActor.send({type:"ApduSendingError",error:$})},Right:($)=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:$})}})}).catch((Q)=>{this.machineActor.send({type:"ApduSendingError",error:new zq(Q)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(q){this.deviceAdpuSender.setDependencies(q)}getDeviceId(){return this.deviceId}async sendApdu(q,J,Z){this.machineActor.getSnapshot().context.apduInProgress.isJust()&&await Promise.race([new Promise(($)=>setTimeout($,y_)),this.previousSendApduPromise]);let Q=new Promise(($)=>{this.machineActor.send({type:"SendApduCalled",apdu:q,triggersDisconnection:!!J,abortTimeout:Z,responseCallback:$})});return this.previousSendApduPromise=Q,Q.finally(()=>{this.previousSendApduPromise===Q&&(this.previousSendApduPromise=null)}),Q}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceConnected(){this.machineActor.send({type:"DeviceConnected"})}eventDeviceDisconnected(){this.machineActor.send({type:"DeviceDisconnected"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function u_({sendApduFn:q,startReconnectionTimeout:J,cancelReconnectionTimeout:Z,tryToReconnect:Q,onTerminated:$,closeConnection:W}){return i({types:{},actions:{startTimer:()=>{J()},cancelTimer:()=>{Z()},reconnectionTimeoutEvent:PJ({type:"ReconnectionTimedOut"}),sendApdu:({context:Y})=>{Y.apduInProgress.map(({apdu:z,abortTimeout:X})=>{q(z,!1,X)})},sendApduResponse:({context:Y},z)=>{Y.apduInProgress.map(({responseCallback:X})=>X(z.response))},sendGetAppAndVersion:()=>{q(new a0().getApdu().getRawApdu(),!1)},tryToReconnect:()=>{Q()},clearApduInProgress:N({apduInProgress:p}),clearApduResponse:N({apduResponse:p}),signalTermination:()=>{$()},closeConnection:()=>{W()}},guards:{isApduThatTriggersDisconnection:({context:Y,event:z})=>z.type!=="ApduResponseReceived"?!1:Y.apduInProgress.caseOf({Just:({triggersDisconnection:X,apdu:w})=>(X||l.isApduThatTriggersDisconnection(w))&&l.isSuccessResponse(z.apduResponse),Nothing:()=>!1}),isSendApduBusyError:({event:Y})=>Y.type!=="ApduResponseReceived"?!1:Y.apduResponse.statusCode[0]===102&&Y.apduResponse.statusCode[1]===1}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:p,apduResponse:p},states:{Connected:{on:{DeviceDisconnected:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:N({apduInProgress:({event:Y})=>Z0.of({apdu:Y.apdu,triggersDisconnection:Y.triggersDisconnection,abortTimeout:Y.abortTimeout,responseCallback:Y.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:"isApduThatTriggersDisconnection",target:"WaitingForDisconnection",actions:[N({apduResponse:({event:Y})=>Z0.of(Y.apduResponse)})]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:Y})=>({response:L(Y.apduResponse)})},{type:"clearApduInProgress"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:Y})=>({response:j(Y.error)})},"clearApduInProgress"]},DeviceDisconnected:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:j(new r1)}},"clearApduInProgress"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:j(new r1)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:Y})=>{Y.responseCallback(j(new W6))}}}},WaitingForDisconnection:{entry:["sendGetAppAndVersion"],exit:[{type:"sendApduResponse",params:({context:Y})=>({response:Y.apduResponse.caseOf({Just:(z)=>L(z),Nothing:()=>j(new zq)})})},{type:"clearApduInProgress"},{type:"clearApduResponse"}],on:{ApduResponseReceived:[{guard:"isSendApduBusyError",actions:["sendGetAppAndVersion"],target:"WaitingForDisconnection"},{target:"Connected"}],ApduSendingError:[{target:"WaitingForReconnection"}],SendApduCalled:{actions:({event:Y})=>{Y.responseCallback(j(new W6))}},DeviceDisconnected:{target:"WaitingForReconnection"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnection:{entry:["startTimer","tryToReconnect"],on:{DeviceConnected:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:N({apduInProgress:({event:Y})=>Z0.of({apdu:Y.apdu,triggersDisconnection:Y.triggersDisconnection,abortTimeout:Y.abortTimeout,responseCallback:Y.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceConnected:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:j(new vJ)}},{type:"clearApduInProgress"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:j(new r1)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:Y})=>{Y.responseCallback(j(new W6))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}class b9{id;deviceModel;sendApdu;type;transport;name;constructor({id:q,deviceModel:J,type:Z,transport:Q,sendApdu:$,name:W}){this.id=q,this.deviceModel=J,this.sendApdu=$,this.type=Z,this.transport=Q,this.name=W}}function QY(q={}){return{id:o.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2097152,getBlockSize:()=>4096,masks:[855638016],bluetoothSpec:[{serviceUuid:"13d63400-2c97-0004-0000-4c6564676572",notifyUuid:"13d63400-2c97-0004-0001-4c6564676572",writeUuid:"13d63400-2c97-0004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-0004-0003-4c6564676572"}],...q}}var $Y=({statusCode:q=Uint8Array.from([144,0]),data:J=Uint8Array.from([])}={})=>new bq({statusCode:q,data:J});function g_(q={}){let J=QY();return new b9({deviceModel:J,id:"42",type:"MOCK",transport:"USB",sendApdu:vi.fn(async()=>Promise.resolve(L($Y()))),...q})}var $1=k1(_q(),1);class WY{isCompatible;version;modelId;appName;constructor(q,J,Z){this.modelId=q.deviceModelId,this.appName="currentApp"in q?q.currentApp.name:void 0;let Q=Z.resolve(q,J);this.isCompatible=Q.isCompatible,this.version=Q.version}withMinVersionInclusive(q){return $1.gte(this.version,q)||(this.isCompatible=!1),this}withMinVersionExclusive(q){return $1.gt(this.version,q)||(this.isCompatible=!1),this}withMinVersionInclusiveAcceptingPrerelease(q){let J=$1.valid($1.coerce(this.version)),Z=$1.valid($1.coerce(q));return(J===null||Z===null||!$1.gte(J,Z))&&(this.isCompatible=!1),this}excludeDeviceModel(q){return this.modelId===q&&(this.isCompatible=!1),this}excludeDeviceModels(...q){for(let J of q)this.excludeDeviceModel(J);return this}excludeApp(q){return this.appName===q&&(this.isCompatible=!1),this}excludeApps(...q){for(let J of q)this.excludeApp(J);return this}check(){return this.isCompatible}}function YY(q){return q.replace(/\s/g,"")}function zY(q){let J=YY(q);return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(J)}function m_(){if(typeof window<"u"&&typeof window.atob=="function")return window.atob.bind(window);if(typeof atob=="function")return atob}function l_(){if(typeof window<"u"&&typeof window.btoa=="function")return window.btoa.bind(window);if(typeof btoa=="function")return btoa}function d_(q){let J=YY(q);if(J.length===0)return new Uint8Array;if(!zY(J))return null;let Z=m_();if(Z){let Q=Z(J),$=new Uint8Array(Q.length);for(let W=0;W<Q.length;W++)$[W]=Q.charCodeAt(W);return $}if(typeof globalThis.Buffer<"u")return Uint8Array.from(globalThis.Buffer.from(J,"base64"));throw Error("No Base64 decoder available in this environment.")}function c_(q){let J=l_();if(J){let Z="";for(let Q=0;Q<q.length;Q++){let $=q[Q];if($===void 0)throw Error("Unexpected undefined byte in array.");Z+=String.fromCharCode($)}return J(Z)}if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(q).toString("base64");throw Error("No Base64 encoder available in this environment.")}export{O6 as Oa,C6 as Pa,TY as Qa,_1 as Ra,D0 as Sa,mq as Ta,Wq as Ua,b6 as Va,T6 as Wa,lq as Xa,H0 as Ya,M6 as Za,z0 as _a,H1 as $a,Yq as ab,f6 as bb,i0 as cb,x1 as db,T as eb,n as fb,l as gb,h0 as hb,zq as ib,SY as jb,hY as kb,v0 as lb,y9 as mb,v9 as nb,G0 as ob,wq as pb,u9 as qb,S6 as rb,a0 as sb,g9 as tb,h6 as ub,$Z as vb,WZ as wb,_q as xb,o as yb,Hq as zb,C3 as Ab,rq as Bb,U0 as Cb,M0 as Db,o6 as Eb,ZJ as Fb,r6 as Gb,qQ as Hb,t6 as Ib,g0 as Jb,d1 as Kb,k as Lb,Z0 as Mb,L0 as Nb,p as Ob,A0 as Pb,j as Qb,L as Rb,t0 as Sb,WQ as Tb,YQ as Ub,aN as Vb,S3 as Wb,tN as Xb,eN as Yb,qV as Zb,h as _b,k0 as $b,Z2 as ac,d as bc,N as cc,i as dc,G8 as ec,B1 as fc,i1 as gc,T1 as hc,N8 as ic,D1 as jc,q0 as kc,V8 as lc,t as mc,nQ as nc,TJ as oc,a as pc,a1 as qc,U8 as rc,m as sc,Kq as tc,R0 as uc,d2 as vc,c2 as wc,p2 as xc,s2 as yc,n2 as zc,o1 as Ac,i2 as Bc,fJ as Cc,SJ as Dc,a2 as Ec,o2 as Fc,r2 as Gc,t2 as Hc,e2 as Ic,hJ as Jc,r1 as Kc,W6 as Lc,vJ as Mc,yJ as Nc,M1 as Oc,oQ as Pc,f0 as Qc,jq as Rc,j8 as Sc,z6 as Tc,M as Uc,w6 as Vc,dJ as Wc,X$ as Xc,cJ as Yc,rD as Zc,tD as _c,eD as $c,sJ as ad,nJ as bd,_$ as cd,x0 as dd,c0 as ed,f1 as fd,Kw as gd,j$ as hd,P8 as id,L$ as jd,R$ as kd,P$ as ld,U as md,I as nd,F0 as od,y8 as pd,u8 as qd,L1 as rd,X1 as sd,bq as td,WW as ud,A1 as vd,U6 as wd,g1 as xd,K6 as yd,YW as zd,Tq as Ad,zW as Bd,wW as Cd,R1 as Dd,Q1 as Ed,YX as Fd,_X as Gd,YF as Hd,AW as Id,m1 as Jd,I0 as Kd,V9 as Ld,F1 as Md,D9 as Nd,C9 as Od,eW as Pd,qY as Qd,JY as Rd,ZY as Sd,b9 as Td,g_ as Ud,WY as Vd,zY as Wd,d_ as Xd,c_ as Yd};
62
62
 
63
- //# debugId=4BBB65B5943456AC64756E2164756E21
64
- //# sourceMappingURL=chunk-mzan0m09.js.map
63
+ //# debugId=269769EC1A2F0EED64756E2164756E21
64
+ //# sourceMappingURL=chunk-wm89desc.js.map