@swapkit/wallet-hardware 6.1.1 → 6.2.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 (101) hide show
  1. package/dist/chunk-035dayv6.js +4 -0
  2. package/dist/chunk-035dayv6.js.map +10 -0
  3. package/dist/{chunk-yrxe491r.js → chunk-2jddegc1.js} +3 -3
  4. package/dist/{chunk-yrxe491r.js.map → chunk-2jddegc1.js.map} +1 -1
  5. package/dist/{chunk-gr3eswf1.js → chunk-42xrtarj.js} +3 -3
  6. package/dist/{chunk-gr3eswf1.js.map → chunk-42xrtarj.js.map} +1 -1
  7. package/dist/{chunk-3t17wpjg.js → chunk-545s1tsc.js} +3 -3
  8. package/dist/{chunk-3t17wpjg.js.map → chunk-545s1tsc.js.map} +1 -1
  9. package/dist/{chunk-1amf58aq.js → chunk-5xg0xc0g.js} +3 -3
  10. package/dist/{chunk-1amf58aq.js.map → chunk-5xg0xc0g.js.map} +1 -1
  11. package/dist/{chunk-xn0fnag5.js → chunk-71kfnwdp.js} +3 -3
  12. package/dist/{chunk-xn0fnag5.js.map → chunk-71kfnwdp.js.map} +1 -1
  13. package/dist/{chunk-xmvg4cds.js → chunk-7kwtpk70.js} +3 -3
  14. package/dist/{chunk-xmvg4cds.js.map → chunk-7kwtpk70.js.map} +1 -1
  15. package/dist/{chunk-0arpsm5f.js → chunk-7rbvcts9.js} +3 -3
  16. package/dist/{chunk-0arpsm5f.js.map → chunk-7rbvcts9.js.map} +1 -1
  17. package/dist/{chunk-k3thje6a.js → chunk-a47dwwv6.js} +3 -3
  18. package/dist/{chunk-k3thje6a.js.map → chunk-a47dwwv6.js.map} +1 -1
  19. package/dist/{chunk-5c7b7z2d.js → chunk-a6vcbcyd.js} +3 -3
  20. package/dist/{chunk-5c7b7z2d.js.map → chunk-a6vcbcyd.js.map} +1 -1
  21. package/dist/{chunk-wfbg89d3.js → chunk-b093ajcq.js} +3 -3
  22. package/dist/{chunk-wfbg89d3.js.map → chunk-b093ajcq.js.map} +1 -1
  23. package/dist/{chunk-ds2m83jp.js → chunk-b7htg03t.js} +3 -3
  24. package/dist/{chunk-ds2m83jp.js.map → chunk-b7htg03t.js.map} +1 -1
  25. package/dist/chunk-g6rrzxcx.js +5 -0
  26. package/dist/chunk-g6rrzxcx.js.map +10 -0
  27. package/dist/{chunk-jewm2ag3.js → chunk-j3n6fbqh.js} +4 -4
  28. package/dist/{chunk-jewm2ag3.js.map → chunk-j3n6fbqh.js.map} +1 -1
  29. package/dist/{chunk-nhva847d.js → chunk-kaw35ae2.js} +3 -3
  30. package/dist/{chunk-nhva847d.js.map → chunk-kaw35ae2.js.map} +1 -1
  31. package/dist/{chunk-dptbnkzm.js → chunk-mzan0m09.js} +4 -4
  32. package/dist/{chunk-dptbnkzm.js.map → chunk-mzan0m09.js.map} +1 -1
  33. package/dist/{chunk-jzrytcrf.js → chunk-rydhx4se.js} +3 -3
  34. package/dist/{chunk-jzrytcrf.js.map → chunk-rydhx4se.js.map} +1 -1
  35. package/dist/{chunk-09e51wma.js → chunk-s2akss77.js} +3 -3
  36. package/dist/{chunk-09e51wma.js.map → chunk-s2akss77.js.map} +1 -1
  37. package/dist/{chunk-tm47brht.js → chunk-s5a5v0m1.js} +3 -3
  38. package/dist/{chunk-tm47brht.js.map → chunk-s5a5v0m1.js.map} +1 -1
  39. package/dist/{chunk-8m2sn76p.js → chunk-sbebfr50.js} +3 -3
  40. package/dist/{chunk-8m2sn76p.js.map → chunk-sbebfr50.js.map} +1 -1
  41. package/dist/{chunk-xx7cwpzq.js → chunk-sp3dq5hr.js} +2 -2
  42. package/dist/{chunk-hg71hp4m.js → chunk-tecse0bj.js} +3 -3
  43. package/dist/{chunk-hg71hp4m.js.map → chunk-tecse0bj.js.map} +1 -1
  44. package/dist/chunk-tm5gk51g.js +4 -0
  45. package/dist/{chunk-eenx3cv6.js → chunk-x28a37pz.js} +3 -3
  46. package/dist/{chunk-eenx3cv6.js.map → chunk-x28a37pz.js.map} +1 -1
  47. package/dist/{chunk-3h1f3hyp.js → chunk-ys51wj1c.js} +3 -3
  48. package/dist/{chunk-3h1f3hyp.js.map → chunk-ys51wj1c.js.map} +1 -1
  49. package/dist/keepkey/index.cjs +2 -2
  50. package/dist/keepkey/index.cjs.map +3 -3
  51. package/dist/keepkey/index.js +2 -2
  52. package/dist/keepkey/index.js.map +3 -3
  53. package/dist/ledger/index.cjs +30 -30
  54. package/dist/ledger/index.cjs.map +11 -7
  55. package/dist/ledger/index.js +2 -2
  56. package/dist/ledger/index.js.map +10 -7
  57. package/dist/trezor/index.cjs +2 -2
  58. package/dist/trezor/index.cjs.map +6 -5
  59. package/dist/trezor/index.js +2 -2
  60. package/dist/trezor/index.js.map +3 -3
  61. package/dist/types/helpers/cardano.d.ts +35 -0
  62. package/dist/types/helpers/cardano.d.ts.map +1 -0
  63. package/dist/types/keepkey/index.d.ts +1 -0
  64. package/dist/types/keepkey/index.d.ts.map +1 -1
  65. package/dist/types/ledger/clients/cardano.d.ts +24 -0
  66. package/dist/types/ledger/clients/cardano.d.ts.map +1 -0
  67. package/dist/types/ledger/clients/evm.d.ts +1 -0
  68. package/dist/types/ledger/clients/evm.d.ts.map +1 -1
  69. package/dist/types/ledger/clients/stellar.d.ts +13 -0
  70. package/dist/types/ledger/clients/stellar.d.ts.map +1 -0
  71. package/dist/types/ledger/clients/ton.d.ts +13 -0
  72. package/dist/types/ledger/clients/ton.d.ts.map +1 -0
  73. package/dist/types/ledger/helpers/getLedgerAddress.d.ts.map +1 -1
  74. package/dist/types/ledger/helpers/getLedgerClient.d.ts +8 -1
  75. package/dist/types/ledger/helpers/getLedgerClient.d.ts.map +1 -1
  76. package/dist/types/ledger/index.d.ts +3 -2
  77. package/dist/types/ledger/index.d.ts.map +1 -1
  78. package/dist/types/ledger/types.d.ts +2 -2
  79. package/dist/types/ledger/types.d.ts.map +1 -1
  80. package/dist/types/trezor/cardanoSigner.d.ts.map +1 -1
  81. package/dist/types/trezor/index.d.ts +1 -0
  82. package/dist/types/trezor/index.d.ts.map +1 -1
  83. package/dist/types/trezor/stellarSigner.d.ts +1 -1
  84. package/package.json +16 -4
  85. package/src/helpers/cardano.ts +112 -0
  86. package/src/keepkey/index.ts +14 -14
  87. package/src/ledger/clients/cardano.ts +204 -0
  88. package/src/ledger/clients/evm.ts +4 -0
  89. package/src/ledger/clients/stellar.ts +83 -0
  90. package/src/ledger/clients/ton.ts +282 -0
  91. package/src/ledger/helpers/getLedgerAddress.ts +16 -0
  92. package/src/ledger/helpers/getLedgerClient.ts +13 -0
  93. package/src/ledger/index.ts +100 -28
  94. package/src/ledger/types.ts +2 -0
  95. package/src/trezor/cardanoSigner.ts +24 -80
  96. package/src/trezor/index.ts +86 -64
  97. package/dist/chunk-5p3ttw6y.js +0 -4
  98. package/dist/chunk-qjq7gvyx.js +0 -4
  99. package/dist/chunk-qjq7gvyx.js.map +0 -10
  100. /package/dist/{chunk-xx7cwpzq.js.map → chunk-sp3dq5hr.js.map} +0 -0
  101. /package/dist/{chunk-5p3ttw6y.js.map → chunk-tm5gk51g.js.map} +0 -0
@@ -1,4 +1,4 @@
1
- import{Wd as k1,Yd as v}from"./chunk-nhva847d.js";var O6=v(()=>{/*! *****************************************************************************
1
+ import{Xd as k1,Zd as v}from"./chunk-kaw35ae2.js";var O6=v(()=>{/*! *****************************************************************************
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
@@ -58,7 +58,7 @@ ${p$(Z)}`;throw new z0(w0.planning,Q)}function c$(q,J){return J===void 0?`${f0(q
58
58
  - ${[...q.tags.keys()].map((Z)=>Z.toString()).join(`
59
59
  - `)}`;return`Binding constraints:
60
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 La,C6 as Ma,kY as Na,_1 as Oa,B0 as Pa,mq as Qa,Wq as Ra,b6 as Sa,T6 as Ta,lq as Ua,_0 as Va,M6 as Wa,Y0 as Xa,H1 as Ya,Yq as Za,f6 as _a,n0 as $a,x1 as ab,T as bb,n as cb,m as db,S0 as eb,zq as fb,bY as gb,TY as hb,h0 as ib,h9 as jb,S9 as kb,H0 as lb,wq as mb,v9 as nb,S6 as ob,i0 as pb,y9 as qb,h6 as rb,JZ as sb,ZZ as tb,_q as ub,o as vb,Hq as wb,E3 as xb,rq as yb,D0 as zb,T0 as Ab,o6 as Bb,qJ as Cb,r6 as Db,r7 as Eb,t6 as Fb,u0 as Gb,d1 as Hb,k as Ib,J0 as Jb,I0 as Kb,p as Lb,L0 as Mb,K as Nb,I as Ob,r0 as Pb,ZQ as Qb,QQ as Rb,uN as Sb,b3 as Tb,lN as Ub,dN as Vb,cN as Wb,S as Xb,k0 as Yb,t3 as Zb,l as _b,N as $b,i as ac,G8 as bc,B1 as cc,i1 as dc,T1 as ec,N8 as fc,D1 as gc,q0 as hc,V8 as ic,t as jc,cQ as kc,CJ as lc,a as mc,a1 as nc,U8 as oc,d as pc,Kq as qc,A0 as rc,u2 as sc,g2 as tc,m2 as uc,l2 as vc,d2 as wc,o1 as xc,c2 as yc,TJ as zc,MJ as Ac,p2 as Bc,s2 as Cc,n2 as Dc,i2 as Ec,a2 as Fc,fJ as Gc,r1 as Hc,W6 as Ic,SJ as Jc,hJ as Kc,M1 as Lc,nQ as Mc,M0 as Nc,jq as Oc,j8 as Pc,z6 as Qc,M as Rc,w6 as Sc,mJ as Tc,Y$ as Uc,lJ as Vc,mD as Wc,lD as Xc,dD as Yc,cJ as Zc,pJ as _c,w$ as $c,E0 as ad,d0 as bd,f1 as cd,Vw as dd,D$ as ed,P8 as fd,K$ as gd,I$ as hd,L$ as id,j as jd,R as kd,X0 as ld,y8 as md,u8 as nd,L1 as od,w1 as pd,bq as qd,ZW as rd,A1 as sd,U6 as td,g1 as ud,K6 as vd,QW as wd,Tq as xd,$W as yd,WW as zd,R1 as Ad,Z1 as Bd,ZX as Cd,zX as Dd,ZF as Ed,jW as Fd,m1 as Gd,j0 as Hd,V9 as Id,F1 as Jd,D9 as Kd,k9 as Ld,aW as Md,oW as Nd,rW as Od,tW as Pd,O9 as Qd,C_ as Rd,JY as Sd,QY as Td,M_ as Ud,f_ as Vd};
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};
62
62
 
63
- //# debugId=AFACB68B6E605FA864756E2164756E21
64
- //# sourceMappingURL=chunk-dptbnkzm.js.map
63
+ //# debugId=4BBB65B5943456AC64756E2164756E21
64
+ //# sourceMappingURL=chunk-mzan0m09.js.map