@ledgerhq/device-management-kit-devtools-rozenite 0.0.0-develop-20261101001031 → 0.0.0-develop-20261102000856
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/rozenite.json +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -462,7 +462,7 @@ Details
|
|
|
462
462
|
|
|
463
463
|
${(function(o){switch(o.kind){case Oa.method:return`[class: "${o.targetClass.name}", method: "${o.method.toString()}"]`;case Oa.parameter:return`[class: "${o.targetClass.name}", index: "${o.index.toString()}"]`;case Oa.property:return`[class: "${o.targetClass.name}", property: "${o.property.toString()}"]`}})(i)}`,{cause:n})}throw n}function S4(e,t){return(r,n,i)=>{try{i===void 0?(function(o,s){const u=lm(o,s);return(c,f)=>{Uu(c.constructor,Hd,Ud,NE(u(c),f))}})(e,t)(r,n):typeof i=="number"?(function(o,s){const u=lm(o,s);return(c,f,p)=>{if(!(function(g,h){return typeof g=="function"&&h===void 0})(c,f))throw new Fa(So.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.
|
|
464
464
|
Found @inject decorator at method "${f?.toString()??""}" at class "${c.constructor.name}"`);Uu(c,Hd,Ud,(function(g,h){return m=>{const y=m.constructorArguments[h];return m.constructorArguments[h]=g(y),m}})(u(c),p))}})(e,t)(r,n,i):(function(o,s){const u=lm(o,s);return(c,f,p)=>{if(!(function(g){return g.set!==void 0})(p))throw new Fa(So.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.
|
|
465
|
-
Found @inject decorator at method "${f.toString()}" at class "${c.constructor.name}"`);Uu(c.constructor,Hd,Ud,NE(u(c),f))}})(e,t)(r,n,i)}catch(o){b4(r,n,i,o)}}}function lm(e,t){return r=>{const n=t(r);return i=>(n(i),e(i))}}function Xe(e){return S4(y4(ac.singleInjection,e),g4)}(function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property"})(Oa||(Oa={}));const jE="@inversifyjs/core/classIsInjectableFlagReflectKey",w4=[Array,BigInt,Boolean,Function,Number,Object,String];function x4(e){const t=N1(e,"design:paramtypes");t!==void 0&&Uu(e,Hd,Ud,(function(r){return n=>(r.forEach(((i,o)=>{var s;n.constructorArguments[o]!==void 0||(s=i,w4.includes(s))||(n.constructorArguments[o]=(function(u){return{isFromTypescriptParamType:!0,kind:ac.singleInjection,name:void 0,optional:!1,tags:new Map,value:u}})(i))})),n)})(t))}function St(e){return t=>{(function(r){if(N1(r,jE)!==void 0)throw new Fa(So.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${r.name}"`);d4(r,jE,!0)})(t),x4(t)}}var zE;(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection"})(zE||(zE={}));var BE;(function(e){e[e.singleMandatory=0]="singleMandatory",e[e.singleOptional=1]="singleOptional",e[e.multipleMandatory=2]="multipleMandatory",e[e.multipleOptional=3]="multipleOptional",e[e.length=4]="length"})(BE||(BE={}));let C4=class{constructor(t,r,n,i,o){this.deviceModel=t,this.serviceUuid=r,this.writeUuid=n,this.writeCmdUuid=i,this.notifyUuid=o}},Zs=class{id;productName;usbProductId;bootloaderUsbProductId;usbOnly;memorySize;getBlockSize;masks;bluetoothSpec;constructor(t){this.id=t.id,this.productName=t.productName,this.usbProductId=t.usbProductId,this.bootloaderUsbProductId=t.bootloaderUsbProductId,this.usbOnly=t.usbOnly,this.memorySize=t.memorySize,this.getBlockSize=t.getBlockSize,this.masks=t.masks,this.bluetoothSpec=t.bluetoothSpec}};var E4=Object.defineProperty,_4=(e,t,r)=>t in e?E4(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,R4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},O4=(e,t,r)=>_4(e,t+"",r);let $a=class{getAllDeviceModels(){return Object.values($a.deviceModelByIds)}getDeviceModel(t){return $a.deviceModelByIds[t.id]}filterDeviceModels(t){return this.getAllDeviceModels().filter(r=>Object.entries(t).every(([n,i])=>r[n]===i))}getBluetoothServicesInfos(){return Object.values($a.deviceModelByIds).reduce((t,r)=>{const{bluetoothSpec:n}=r;return n?{...t,...n.reduce((i,o)=>({...i,[o.serviceUuid]:new C4(r,o.serviceUuid,o.writeUuid,o.writeCmdUuid,o.notifyUuid)}),{})}:t},{})}getBluetoothServices(){return Object.values($a.deviceModelByIds).map(t=>(t.bluetoothSpec||[]).map(r=>r.serviceUuid)).flat().filter(t=>!!t)}};O4($a,"deviceModelByIds",{[Xt.NANO_S]:new Zs({id:Xt.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:320*1024,getBlockSize:e=>EE.lt(EE.coerce(e.firmwareVersion)??"","2.0.0")?4*1024:2*1024,masks:[823132160]}),[Xt.NANO_SP]:new Zs({id:Xt.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1533*1024,getBlockSize:()=>512,masks:[856686592]}),[Xt.NANO_X]:new Zs({id:Xt.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2*1024*1024,getBlockSize:()=>4*1024,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"}]}),[Xt.STAX]:new Zs({id:Xt.STAX,productName:"Ledger Stax",usbProductId:96,bootloaderUsbProductId:6,usbOnly:!1,memorySize:1533*1024,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"}]}),[Xt.FLEX]:new Zs({id:Xt.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,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"}]}),[Xt.APEX]:new Zs({id:Xt.APEX,productName:"Ledger Nano Gen5",usbProductId:128,bootloaderUsbProductId:8,usbOnly:!1,memorySize:1533*1024,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"}]})}),$a=R4([St()],$a);let $4=class{statusCode;data;constructor({statusCode:t,data:r}){this.statusCode=t,this.data=r}};const T4=5,os=1,X0=2,gl=2,K0=2,Dr=[];for(let e=0;e<256;++e)Dr.push((e+256).toString(16).slice(1));function I4(e,t=0){return(Dr[e[t+0]]+Dr[e[t+1]]+Dr[e[t+2]]+Dr[e[t+3]]+"-"+Dr[e[t+4]]+Dr[e[t+5]]+"-"+Dr[e[t+6]]+Dr[e[t+7]]+"-"+Dr[e[t+8]]+Dr[e[t+9]]+"-"+Dr[e[t+10]]+Dr[e[t+11]]+Dr[e[t+12]]+Dr[e[t+13]]+Dr[e[t+14]]+Dr[e[t+15]]).toLowerCase()}let um;const A4=new Uint8Array(16);function k4(){if(!um){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");um=crypto.getRandomValues.bind(crypto)}return um(A4)}const P4=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),VE={randomUUID:P4};function zp(e,t,r){if(VE.randomUUID&&!e)return VE.randomUUID();e=e||{};const n=e.random||(e.rng||k4)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,I4(n)}const ps={getLastBytesFrom(e,t){return e.slice(-t)},getFirstBytesFrom(e,t){return e.slice(0,t)},bytesToNumber(e){return e.reduce((t,r,n)=>t+r*Math.pow(256,e.length-1-n),0)},numberToByteArray(e,t){return new Uint8Array(t).map((r,n)=>e>>8*(t-1-n)&255)}},HE=2,cm=800;let UE=class{_tag="FramerOverflowError";originalError;constructor(){this.originalError=new Error("Frame header length is greater than frame size")}},M4=class{_tag="FramerApduError";originalError;constructor(){this.originalError=new Error("Frame offset is greater than apdu length")}},WE=class{_tag="ReceiverApduError";originalError;constructor(t){this.originalError=new Error(t??"Unable to parse apdu")}},GE=class{_tag="DeviceSessionNotFound";originalError;constructor(t){this.originalError=t??new Error("Device session not found")}},v2=class{_header;_data;constructor({header:t,data:r}){this._header=t,this._data=r}toString(){return JSON.stringify({header:this._header.toString(),data:Zo(this._data)},null,2)}getRawData(){const t=this._header.getRawData(),r=new Uint8Array(t.length+this._data.length);return r.set(t,0),r.set(this._data,t.length),r}getHeader(){return this._header}getData(){return this._data}},m2=class{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:t,dataSize:r,index:n,headTag:i,length:o,channel:s}){this._uuid=t,this._dataLength=r,this._index=n,this._headTag=i,this._length=o,this._channel=s}getDataLength(){return this._dataLength.map(t=>ps.bytesToNumber(t))}setDataSize(t){return this._dataLength=t,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:t=>[...t],Nothing:()=>[]}),...this._headTag,...this._index,...this._dataLength.caseOf({Just:t=>[...t],Nothing:()=>[]})])}};const dr={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var D4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},L4=(e,t)=>(r,n)=>t(r,n,e);let qE=class{_channel;_logger;_pendingFrames;constructor({channel:t=_n.zero()},r){this._channel=t,this._logger=r("ApduReceiverService"),this._pendingFrames=[]}handleFrame(t){return this.getFrameFromBytes(t).map(r=>{if(this._pendingFrames.push(r),!this._pendingFrames[0])return Dt;const n=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(n)})}getCompleteFrame(t){return t.chain(r=>{if(!this.isComplete(r))return this._logger.debug("frame is not complete, waiting for more"),Dt;const n=ps.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),i=ps.getFirstBytesFrom(n,n.length-HE),o=ps.getLastBytesFrom(n,HE);return this._pendingFrames=[],Lr(new $4({data:i,statusCode:o}))})}getFrameFromBytes(t){const r=this._channel.caseOf({Just:()=>X0,Nothing:()=>0}),n=t.slice(r,r+os),i=t.slice(r+os,r+os+gl),o=i.reduce((h,m)=>h+m,0)===0;if(!o&&this._pendingFrames.length===0)return Wt(new WE);const s=r+os+gl,u=o?K0:0;if(t.length<r+os+gl+u)return Wt(new WE("Unable to parse header from apdu"));const c=o?Lr(t.slice(s,s+u)):Dt,f=s+u,p=t.slice(f),g=new v2({header:new m2({uuid:zp(),channel:this._channel,dataSize:c,headTag:n,index:i,length:r+os+gl+u}),data:p});return nr(g)}isComplete(t){return this._pendingFrames.reduce((r,n)=>r+n.getData().length,0)>=t}concatFrames(t){return t.reduce((r,n)=>Uint8Array.from([...r,...n.getData()]),new Uint8Array(0))}};qE=D4([St(),L4(1,Xe(dr.LoggerPublisherServiceFactory))],qE);var F4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},N4=(e,t)=>(r,n)=>t(r,n,e);let XE=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:t,channel:r=_n.zero(),padding:n=!1},i){this._frameSize=t,this._channel=r,this._padding=n,this._logger=i("DefaultApduSenderService")}getFrames(t){const r=[];let n=0,i=this.getFrameAtIndex(t,n);for(;i.isRight();)r.push(i.extract()),n+=1,i=this.getFrameAtIndex(t,n).mapLeft(o=>(o instanceof UE||this._logger.error("Error while parsing frame",{data:{error:o}}),o));return r}getFrameAtIndex(t,r){const n=this.getFrameHeaderFrom(r,t.length),i=r===0?0:r*this._frameSize-this.getHeaderSizeSumFrom(r);if(i>=t.length)return Wt(new UE);if(n.getLength()>this._frameSize)return Wt(new M4);const o=this._frameSize-n.getLength(),s=t.slice(i,i+this._frameSize-n.getLength()),u=this._padding?new Uint8Array(o).fill(0):new Uint8Array(s.length<o?s.length:o);u.set(s,0);const c=new v2({header:n,data:u});return nr(c)}getFrameHeaderFrom(t,r){const n=new m2({uuid:zp(),channel:this._channel.map(i=>ps.getLastBytesFrom(i,X0)),headTag:new Uint8Array([T4]),index:ps.numberToByteArray(t,gl),length:this.getFrameHeaderSizeFromIndex(t),dataSize:_n.zero()});return t===0&&n.setDataSize(_n.of(ps.numberToByteArray(r,K0))),n}getHeaderSizeSumFrom(t){let r=this.getFrameHeaderSizeFromIndex(0),n=1;for(;n<t;)r+=this.getFrameHeaderSizeFromIndex(n),n+=1;return r}getFrameHeaderSizeFromIndex(t){return this._channel.caseOf({Just:()=>X0,Nothing:()=>0})+gl+os+(t===0?K0:0)}};XE=F4([St(),N4(1,Xe(dr.LoggerPublisherServiceFactory))],XE);const Y0={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService")},en={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService")},KE={ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase")},Ac={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig")},Bp={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")},Na={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var j4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},YE=(e,t)=>(r,n)=>t(r,n,e);let QE=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendCommandUseCase")}async execute({sessionId:t,command:r,abortTimeout:n}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async i=>await i.sendCommand(r,n),Left:i=>{throw this._logger.error("Error getting session",{data:{error:i}}),i}})}};QE=j4([St(),YE(0,Xe(en.DeviceSessionService)),YE(1,Xe(dr.LoggerPublisherServiceFactory))],QE);var z4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let JE=class{execute=vi.fn(()=>"stub")};JE=z4([St()],JE);var B4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},ZE=(e,t)=>(r,n)=>t(r,n,e);let e_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("ExecuteDeviceActionUseCase")}execute({sessionId:t,deviceAction:r}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:n=>n.executeDeviceAction(r),Left:n=>{throw this._logger.error("Error getting session",{data:{error:n}}),n}})}};e_=B4([St(),ZE(0,Xe(en.DeviceSessionService)),ZE(1,Xe(dr.LoggerPublisherServiceFactory))],e_);function V4(e){return typeof e=="object"&&e!==null&&"version"in e&&"name"in e&&typeof e.version=="string"&&typeof e.name=="string"}let t_=class{constructor(t){this.err=t,this.originalError=t}_tag="ApiCallError";originalError},H4=class{constructor(t){this.err=t,this.originalError=t}_tag="ParseResponseError";originalError},y2=class{constructor(t){this.err=t,this.originalError=t}_tag="JSONParseError";originalError},U4=class{constructor(t){this.err=t,this.originalError=t}_tag="ReadFileError";originalError};const W4="@ledgerhq/device-management-kit",G4="0.0.0-develop-20261101001031",r_={name:W4,version:G4};var q4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};const X4={name:r_.name,version:r_.version},K4=()=>JSON.stringify(X4);let n_=class{getConfig(){return Rn.encase(()=>K4()).mapLeft(t=>new U4(t)).chain(t=>Rn.encase(()=>{const r=JSON.parse(t);if(V4(r))return r;throw new Error("Invalid config file")}).mapLeft(r=>new y2(r)))}};n_=q4([St()],n_);var Y4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let i_=class{getConfig(){return Rn.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};i_=Y4([St()],i_);var Q4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let o_=class{async getConfig(){const t=await this._callApi();if(t.isLeft())return Wt(new t_(t.extract()));if(!t.extract().ok)return Wt(new t_(new Error("response not ok")));const r=await t.extract().json();return r.isLeft()?Wt(new y2):r.chain(n=>this._parseResponse(n)).map(n=>n)}_parseResponse(t){const{name:r,version:n}=t;return!r||!n?Wt(new H4):Rn.of({name:r,version:n})}_callApi(){return new Promise(t=>{t(Rn.of({ok:!0,json:async()=>new Promise(r=>{r(Rn.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};o_=Q4([St()],o_);var J4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let a_=class{async getConfig(){return new Promise(t=>t(Rn.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};a_=J4([St()],a_);var Z4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},fm=(e,t)=>(r,n)=>t(r,n,e);let s_=class{_local;_remote;_logger;constructor(t,r,n){this._local=t,this._remote=r,this._logger=n("config")}async getDmkConfig(){const t=this._local.getConfig().ifLeft(r=>{this._logger.error("Local config not available",{data:{error:r}})});if(t.isRight()){const r=t.extract();return this._logger.info("Local config available",{data:{config:r}}),r}return this._remote.getConfig().then(r=>r.mapLeft(n=>(this._logger.error("Local config available",{data:{error:n}}),{name:"DeadDmk",version:"0.0.0-dead.1"})).extract())}};s_=Z4([St(),fm(0,Xe(Y0.LocalConfigDataSource)),fm(1,Xe(Y0.RemoteConfigDataSource)),fm(2,Xe(dr.LoggerPublisherServiceFactory))],s_);var ej=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},tj=(e,t)=>(r,n)=>t(r,n,e);let l_=class{_configService;constructor(t){this._configService=t}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};l_=ej([St(),tj(0,Xe(Y0.ConfigService))],l_);const rj={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var nj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},u_=(e,t)=>(r,n)=>t(r,n,e);let c_=class{constructor(t,r){this._sessionService=t,this._logger=r("DisableDeviceSessionRefresherUseCase")}_logger;execute({sessionId:t,blockerId:r}){return this._sessionService.getDeviceSessionById(t).caseOf({Left:n=>{throw this._logger.error("Error getting device session",{data:{error:n}}),n},Right:n=>n.disableRefresher(r)})}};c_=nj([St(),u_(0,Xe(en.DeviceSessionService)),u_(1,Xe(dr.LoggerPublisherServiceFactory))],c_);var ij=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},oj=(e,t)=>(r,n)=>t(r,n,e);let f_=class{_sessions;_sessionsSubject;_logger;constructor(t){this._sessions=[],this._sessionsSubject=new YT,this._logger=t("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(t){return this._sessions.find(r=>r.id===t.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:t}}),this):(this._sessions.push(t),this._sessionsSubject.next(t),this._logger.info("DeviceSession added",{data:{sessionId:t.id}}),this)}removeDeviceSession(t){const r=this._sessions.find(n=>n.id===t);return r?(r.close(),this._sessions=this._sessions.filter(n=>n.id!==t),this._logger.info("DeviceSession removed",{data:{sessionId:t}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:t}}),this)}getDeviceSessionById(t){return _n.fromNullable(this._sessions.find(r=>r.id===t)).toEither(new GE)}getDeviceSessionsByDeviceId(t){return _n.fromPredicate(({length:r})=>r>0,this._sessions.filter(r=>r.connectedDevice.id===t)).toEither(new GE)}getDeviceSessions(){return this._sessions}};f_=ij([St(),oj(0,Xe(dr.LoggerPublisherServiceFactory))],f_);var aj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},d_=(e,t)=>(r,n)=>t(r,n,e);let p_=class{_sessionService;_transportService;constructor(t,r){this._sessionService=t,this._transportService=r}execute(){const t=this._sessionService.getDeviceSessions();for(const r of t)this._transportService.closeConnection(r.connectedDevice),this._sessionService.removeDeviceSession(r.id)}};p_=aj([St(),d_(0,Xe(en.DeviceSessionService)),d_(1,Xe(Na.TransportService))],p_);var sj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},h_=(e,t)=>(r,n)=>t(r,n,e);let g_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("GetDeviceSessionStateUseCase")}execute({sessionId:t}){return this._sessionService.getDeviceSessionById(t).caseOf({Left:r=>{throw this._logger.error("Error getting session device",{data:{error:r}}),r},Right:r=>r.state})}};g_=sj([St(),h_(0,Xe(en.DeviceSessionService)),h_(1,Xe(dr.LoggerPublisherServiceFactory))],g_);var lj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},v_=(e,t)=>(r,n)=>t(r,n,e);let m_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("UnsafeBypassIntentQueueUseCase")}execute({sessionId:t,bypass:r}){this._sessionService.getDeviceSessionById(t).caseOf({Left:n=>{throw this._logger.error("Error getting session",{data:{error:n}}),n},Right:n=>{this._logger.warn(`UNSAFE: ${r?"Enabling":"Disabling"} intent queue bypass for session ${t}`),n._unsafeBypassIntentQueue(r)}})}};m_=lj([St(),v_(0,Xe(en.DeviceSessionService)),v_(1,Xe(dr.LoggerPublisherServiceFactory))],m_);function uj(e){return`[will send APDU] ~...> ${Zo(e,!1)}`}function cj(e){return`[exchange] <= ${Zo(e.data,!1)}${Zo(e.statusCode,!1)}`}const fj="apdu-exchange";function dj(e,t,r){const n=Zo(t,!1),i=`${Zo(r.data,!1)}${Zo(r.statusCode,!1)}`;return{message:cj(r),data:{type:fj,sessionId:e,apdu:n,response:i}}}const Q0=1e3,dm=1e3,pj={isRefresherDisabled:!1,pollingInterval:1e3};var ur=(e=>(e.NEW_STATE="NEW_STATE",e.REFRESH_NEEDED="REFRESH_NEEDED",e.COMMAND_SUCCEEDED="COMMAND_SUCCEEDED",e.DEVICE_STATE_UPDATE_BUSY="DEVICE_STATE_UPDATE_BUSY",e.DEVICE_STATE_UPDATE_LOCKED="DEVICE_STATE_UPDATE_LOCKED",e.DEVICE_STATE_UPDATE_CONNECTED="DEVICE_STATE_UPDATE_CONNECTED",e.DEVICE_STATE_UPDATE_UNKNOWN="DEVICE_STATE_UPDATE_UNKNOWN",e))(ur||{});let hj=class{_eventEmitter=new Ul;listen(){return this._eventEmitter.asObservable()}dispatch(t){this._eventEmitter.next(t)}},gj=class{constructor(t,r){this.loggerModuleFactory=t,this.sessionEventDispatcher=r,this._logger=this.loggerModuleFactory("IntentQueueService")}_logger;_queue=[];_isProcessing=!1;_currentSubscription=null;enqueue(t){this._logger.debug("Enqueueing intent",{data:{type:t.type}});const r=new Ul,n={intent:t,subject:r,isCancelled:!1};this._queue.push(n);const i=()=>{this._logger.debug("Cancelling intent",{data:{type:t.type}}),n.isCancelled=!0,this._queue[0]===n&&this._currentSubscription?(this._currentSubscription.unsubscribe(),this._currentSubscription=null,r.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue()):(!this._isProcessing||this._queue[0]!==n)&&r.complete()};return this._isProcessing||this._processQueue(),{observable:r.asObservable().pipe(Q3(()=>{this._logger.debug("Intent observable finalized",{data:{type:t.type}})})),cancel:i}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:ur.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_BUSY}),this._isProcessing=!0;const t=this._queue[0];if(t.isCancelled){this._logger.debug("Skipping cancelled intent",{data:{type:t.intent.type}}),t.subject.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue();return}this._logger.debug("Processing intent",{data:{type:t.intent.type}}),this._currentSubscription=t.intent.execute().subscribe({next:r=>{t.isCancelled||t.subject.next(r)},error:r=>{t.isCancelled||t.subject.error(r),this._onIntentComplete()},complete:()=>{t.isCancelled||t.subject.complete(),this._onIntentComplete()}})}_onIntentComplete(){this._logger.debug("Intent completed"),this._currentSubscription=null,this._queue.shift(),this._isProcessing=!1,this._processQueue()}},vj=class{constructor(t,r){this._refresher=r,this._logger=t("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(t){const r=`${t}-${zp()}`;this.addRefresherBlocker(r),this._logger.debug("Refresher disabled",{data:{blockerId:r,blockers:Array.from(this._refresherBlockers)}});let n=!1;return()=>{n||(n=!0,this.removeRefresherBlocker(r),this._logger.debug("Refresher re-enabled",{data:{blockerId:r,blockers:Array.from(this._refresherBlockers)}}))}}addRefresherBlocker(t){const r=this._refresherBlockers.size;this._refresherBlockers.add(t),r===0&&this._refresher.stop()}removeRefresherBlocker(t){const r=this._refresherBlockers.size;this._refresherBlockers.delete(t),r>0&&this._refresherBlockers.size===0&&this._refresher.start()}},mj=class{constructor(t,r,n,i){this.connectedDevice=r,this._sessionEventDispatcher=n,this._sendCommandFunction=i,this._logger=t("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async o=>await this.mapEventAction(o))}_sendCommandFunction;_subscription;_logger;async ping(){try{return await this.mapDevicePingAction(this.connectedDevice.deviceModel.id)}catch(t){return this._logger.error("Error while pinging device",{data:{error:t}}),null}}mapEventAction=async t=>t.eventName===ur.REFRESH_NEEDED?await this.ping():null;async mapDevicePingAction(t){if(t===Xt.NANO_S){const r=async()=>{const o=await this._sendCommandFunction(new kC,cm);return this._sendCommandFunction(new QN,cm),o},n=new Promise(o=>{setTimeout(()=>o(null),Q0*2+100)}),i=await Promise.race([r(),n]);return i?this._sessionEventDispatcher.dispatch({eventName:ur.COMMAND_SUCCEEDED,eventData:i}):this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_LOCKED}),i}else{const r=await this._sendCommandFunction(new kC,cm);return this._sessionEventDispatcher.dispatch({eventName:ur.COMMAND_SUCCEEDED,eventData:r}),r}}unsubscribe(){this._subscription.unsubscribe()}},yj=class{constructor(t,r,n,i){this._sessionEventDispatcher=n,this._refresherOptions=r,this._logger=t("device-session-refresher"),this._connectedDeviceID=i.deviceModel.id}_refresherSubscription;_refresherOptions;_logger;_connectedDeviceID;startRefresher(){if(this._refresherOptions.isRefresherDisabled||this._refresherSubscription)return;const t=this.getValidPollingInterval(this._refresherOptions,this._logger),r=this._sessionEventDispatcher.listen().pipe(PE(n=>n.eventName===ur.DEVICE_STATE_UPDATE_BUSY||n.eventName===ur.NEW_STATE),La(n=>n.eventName===ur.DEVICE_STATE_UPDATE_BUSY),Z3(!1),K3());this._refresherSubscription=G3(0,t).pipe(e4(r),ME(([n,i])=>{i&&this._logger.debug("Refresh skipped: device is busy")}),PE(([n,i])=>!i),ME(()=>this._sessionEventDispatcher.dispatch({eventName:ur.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=(t,r)=>{const{pollingInterval:n}=t;if(this._connectedDeviceID===Xt.NANO_S){const i=Q0*2;return n!==void 0&&n<i?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${i}`),i):n??i}else return n!==void 0&&n<dm?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${dm}`),dm):n??Q0}},bj=class{constructor(t,r,n,i,o){this._sessionEventDispatcher=r,this._connectedDevice=n,this._deviceState=i,this.setDeviceSessionState=o,this._subscription=this._sessionEventDispatcher.listen().subscribe(s=>this.mapEventAction(s)),this._logger=t("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=ho.BUSY;_updateDeviceState(t){const r=this._parseDeviceStatus(t);if(r){const{sessionStateType:n,deviceStatus:i,currentApp:o}=r,s=this._deviceState.getValue();s.sessionStateType===Ss.Connected?this.setDeviceSessionState({sessionStateType:n,deviceStatus:i,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:o,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...s,sessionStateType:n,deviceStatus:i,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:o})}}mapEventAction=t=>{const{eventName:r}=t;switch(r){case ur.COMMAND_SUCCEEDED:return this._updateDeviceState(t.eventData);case ur.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:ho.BUSY});case ur.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=ho.LOCKED;return;case ur.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=ho.CONNECTED;return;case ur.NEW_STATE:{const n=this._pendingDeviceStatus;return this._pendingDeviceStatus=ho.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:n})}case ur.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:ho.BUSY});case ur.REFRESH_NEEDED:return;default:{const n=r;throw new Error(`Unhandled context type ${n}`)}}};_parseDeviceStatus(t){return mN(t)?{sessionStateType:Ss.ReadyWithoutSecureChannel,deviceStatus:ho.CONNECTED,currentApp:{name:t.data.name,version:t.data.version}}:(this._logger.debug("Error while parsing APDU response",{data:{parsedResponse:t}}),null)}unsubscribe(){this._subscription.unsubscribe()}},Sj=class{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new hj;_bypassIntentQueue=!1;constructor({connectedDevice:t,id:r=zp()},n,i,o,s,u=c=>new gj(n,c)){this._id=r,this._connectedDevice=t,this._loggerModuleFactory=n,this._logger=n("device-session"),this._managerApiService=i,this._intentQueueService=u(this._sessionEventDispatcher),this._secureChannelService=o,this._refresherOptions={...pj,...s},this._deviceState=new S3({sessionStateType:Ss.Connected,deviceStatus:ho.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new mj(n,t,this._sessionEventDispatcher,(c,f)=>this.sendCommand(c,f)),this._deviceSessionRefresher=new yj(n,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new bj(n,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,c=>this.setDeviceSessionState(c)),this._refresherService=new vj(n,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{this._refresherOptions.isRefresherDisabled?await this._pinger.ping():this._deviceSessionRefresher.startRefresher()}catch(t){throw this._logger.error("Error while initialising session",{data:{error:t}}),t}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(t){this._deviceState.next(t)}sendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._bypassIntentQueue?this._unsafeInternalSendApdu(t,r):this._internalSendApdu(t,r)}_internalSendApdu(t,r){const n=r.abortTimeout,i=Date.now(),{observable:o,cancel:s}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>Il((async()=>{const c=Date.now()-i;return await this._unsafeInternalSendApdu(t,{isPolling:r.isPolling,triggersDisconnection:r.triggersDisconnection,abortTimeout:n?n-c:void 0})})())}),u=n?o.pipe(AE({each:n,with:()=>{throw s(),new t4}})):o;return IE(u)}async _unsafeInternalSendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(uj(t)),(await this._connectedDevice.sendApdu(t,r.triggersDisconnection,r.abortTimeout)).ifRight(n=>{const{message:i,data:o}=dj(this._id,t,n);this._logger.debug(i,{data:o}),w1.isLockedDeviceResponse(n)?this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_UNKNOWN})})}sendCommand(t,r){return this._logger.debug(`[sendCommand] ${t.name}`),this._bypassIntentQueue?this._unsafeInternalSendCommand(t,r):this._internalSendCommand(t,r)}_internalSendCommand(t,r){const n=Date.now(),{observable:i,cancel:o}=this._intentQueueService.enqueue({type:"send-command",execute:()=>Il((async()=>{const u=Date.now()-n;return await this._unsafeInternalSendCommand(t,r?r-u:void 0)})())}),s=r?i.pipe(AE({each:r,with:()=>{throw o(),new r4}})):i;return IE(s)}async _unsafeInternalSendCommand(t,r){const n=t.getApdu();return(await this._unsafeInternalSendApdu(n.getRawApdu(),{isPolling:!1,triggersDisconnection:t.triggersDisconnection??!1,abortTimeout:r})).caseOf({Left:i=>{throw this._logger.error("[sendCommand] error",{data:{err:i}}),i},Right:i=>{const o=t.parseResponse(i,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:o}}),o}})}executeDeviceAction(t){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(t):this._internalExecuteDeviceAction(t)}_internalExecuteDeviceAction(t){let r;const{observable:n,cancel:i}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{const{observable:o,cancel:s}=this._unsafeInternalExecuteDeviceAction(t);return r=s,o}});return{observable:n,cancel:()=>{r?.(),i()}}}_unsafeInternalExecuteDeviceAction(t){const{observable:r,cancel:n}=t._execute({sendApdu:async i=>this._unsafeInternalSendApdu(i),sendCommand:async i=>this._unsafeInternalSendCommand(i),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:i=>(this.setDeviceSessionState(i),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:r,cancel:n}}close(){this._updateDeviceStatus(ho.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher(),this._pinger.unsubscribe()}disableRefresher(t){return this._refresherService.disableRefresher(t)}_unsafeBypassIntentQueue(t){this._bypassIntentQueue=t}_updateDeviceStatus(t){const r=this._deviceState.getValue();this._deviceState.next({...r,deviceStatus:t})}};var wj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},_u=(e,t)=>(r,n)=>t(r,n,e);let y_=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(t,r,n,i,o){this._sessionService=r,this._transportService=t,this._loggerFactory=n,this._logger=n("ConnectUseCase"),this._managerApi=i,this._secureChannel=o}handleDeviceDisconnect(t){this._sessionService.getDeviceSessionsByDeviceId(t).ifRight(r=>{r.forEach(n=>{this._sessionService.removeDeviceSession(n.id),this._logger.info("Session removed",{data:{deviceId:t,sessionId:n.id}})})})}async execute({device:t,sessionRefresherOptions:r}){const n=this._transportService.getTransport(t.transport),i="sessionId"in t?t.sessionId:void 0;return dt.liftEither(n.toEither(new F1(new Error("Unknown transport")))).chain(async o=>o.connect({deviceId:t.id,onDisconnect:s=>this.handleDeviceDisconnect(s)})).ifLeft(o=>{this._logger.error("Error connecting to device")}).map(async o=>{const s=new Sj({connectedDevice:o,id:i},this._loggerFactory,this._managerApi,this._secureChannel,r);return this._sessionService.addDeviceSession(s),await s.initialiseSession(),s.id}).caseOf({Left:o=>{throw o},Right:o=>o})}};y_=wj([St(),_u(0,Xe(Na.TransportService)),_u(1,Xe(en.DeviceSessionService)),_u(2,Xe(dr.LoggerPublisherServiceFactory)),_u(3,Xe(Ac.ManagerApiService)),_u(4,Xe(Bp.SecureChannelService))],y_);var xj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},pm=(e,t)=>(r,n)=>t(r,n,e);let b_=class{_transportService;_sessionService;_logger;constructor(t,r,n){this._sessionService=r,this._transportService=t,this._logger=n("DisconnectUseCase")}async execute({sessionId:t}){return this._logger.debug("Disconnecting from device",{data:{test:this._sessionService.getDeviceSessions().map(r=>r.id)}}),dt(async({liftEither:r})=>{const n=await r(this._sessionService.getDeviceSessionById(t).ifLeft(s=>{this._logger.error("Device session not found",{data:{sessionId:t,error:s}})})),i=n.connectedDevice.transport,o=await r(this._transportService.getTransport(i).toEither(new F1(new Error("Unknown transport"))));n.close(),this._sessionService.removeDeviceSession(t),await o.disconnect({connectedDevice:n.connectedDevice})}).caseOf({Left:r=>{throw this._logger.error("Error disconnecting from device",{data:{error:r}}),r},Right:()=>{}})}};b_=xj([St(),pm(0,Xe(Na.TransportService)),pm(1,Xe(en.DeviceSessionService)),pm(2,Xe(dr.LoggerPublisherServiceFactory))],b_);let j1=class{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:t,deviceModel:{id:r,productName:n},type:i,transport:o,name:s},sessionId:u}){this.id=t,this.sessionId=u,this.modelId=r,this.name=s??n,this.type=i,this.transport=o}};var Cj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},S_=(e,t)=>(r,n)=>t(r,n,e);let w_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("GetConnectedDeviceUseCase")}execute({sessionId:t}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:r=>new j1({sessionId:r.id,transportConnectedDevice:r.connectedDevice}),Left:r=>{throw this._logger.error("Error getting session",{data:{error:r}}),r}})}};w_=Cj([St(),S_(0,Xe(en.DeviceSessionService)),S_(1,Xe(dr.LoggerPublisherServiceFactory))],w_);var Ej=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},x_=(e,t)=>(r,n)=>t(r,n,e);let C_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("ListConnectedDeviceUseCase")}execute(){return this._logger.info("Listing connected devices"),this._sessionService.getDeviceSessions().map(t=>new j1({transportConnectedDevice:t.connectedDevice,sessionId:t.id}))}};C_=Ej([St(),x_(0,Xe(en.DeviceSessionService)),x_(1,Xe(dr.LoggerPublisherServiceFactory))],C_);var _j=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},E_=(e,t)=>(r,n)=>t(r,n,e);let __=class{_transports;_transportService;_logger;constructor(t,r){this._transports=t.getAllTransports(),this._transportService=t,this._logger=r("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(t){const r=new NT({id:t.id,model:t.deviceModel.id,name:t.deviceModel.productName});return{id:t.id,deviceModel:r,transport:t.transport,name:t.name||r.name,rssi:t.rssi}}execute({transport:t}={}){if(this._logger.info("Listening to available devices"),this._transports.length===0)return this._logger.warn("No transports available"),Il([[]]);if(!t){this._logger.info("Discovering all available transports");const r=this._transports.map((n,i)=>n.listenToAvailableDevices().pipe(La(o=>({index:i,arr:o}))));return q3(...r).pipe(J3((n,{index:i,arr:o})=>(n[i]=o,n),{}),La(n=>Object.values(n).flat().map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))}return this._logger.info(`Discovering devices on transport ${t}`),this._transportService.getTransport(t).caseOf({Nothing:()=>(this._logger.error(`Transport ${t} not found`),d2([])),Just:r=>r.listenToAvailableDevices().pipe(La(n=>n.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};__=_j([St(),E_(0,Xe(Na.TransportService)),E_(1,Xe(dr.LoggerPublisherServiceFactory))],__);var Rj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},R_=(e,t)=>(r,n)=>t(r,n,e);let O_=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(La(t=>new j1({transportConnectedDevice:t.connectedDevice,sessionId:t.id})))}};O_=Rj([St(),R_(0,Xe(en.DeviceSessionService)),R_(1,Xe(dr.LoggerPublisherServiceFactory))],O_);var Oj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},hm=(e,t)=>(r,n)=>t(r,n,e);let $_=class{constructor(t,r,n){this.connectUseCase=t,this.disconnectUseCase=r,this._logger=n("ReconnectUseCase")}_logger;async execute({device:t,sessionRefresherOptions:r}){return this._logger.debug("Reconnecting device session",{data:{deviceId:t.id,transport:t.transport}}),await this.disconnectUseCase.execute({sessionId:t.sessionId}),this.connectUseCase.execute({device:t,sessionRefresherOptions:r})}};$_=Oj([St(),hm(0,Xe(KE.ConnectUseCase)),hm(1,Xe(KE.DisconnectUseCase)),hm(2,Xe(dr.LoggerPublisherServiceFactory))],$_);var $j=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Tj=(e,t)=>(r,n)=>t(r,n,e);let T_=class{constructor(t){this._transportService=t}mapDiscoveredDevice(t){const r=new NT({id:t.id,model:t.deviceModel.id,name:t.deviceModel.productName});return{id:t.id,deviceModel:r,transport:t.transport,name:t.name||r.name,rssi:t.rssi}}execute({transport:t}={}){if(!t){const r=this._transportService.getAllTransports();return d2(...r).pipe(L1(n=>n.startDiscovering().pipe(La(i=>this.mapDiscoveredDevice(i)))))}return this._transportService.getTransport(t).caseOf({Just:r=>r.startDiscovering().pipe(La(n=>this.mapDiscoveredDevice(n))),Nothing:()=>{throw new F1(new Error("Unknown transport"))}})}};T_=$j([St(),Tj(0,Xe(Na.TransportService))],T_);var Ij=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},I_=(e,t)=>(r,n)=>t(r,n,e);let A_=class{constructor(t,r){this.transportService=t,this._logger=r("StopDiscoveringUseCase")}_logger;async execute(){this._logger.debug("Stopping discovering devices");for(const t of this.transportService.getAllTransports())await t.stopDiscovering()}};A_=Ij([St(),I_(0,Xe(Na.TransportService)),I_(1,Xe(dr.LoggerPublisherServiceFactory))],A_);var Du=(e=>(e[e.Fatal=0]="Fatal",e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Info=3]="Info",e[e.Debug=4]="Debug",e))(Du||{});let Aj=class{format(t){return Array.isArray(t)?t.map(r=>`[${r}]`).join(" "):`[${t}]`}};function J0(e,t){if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return t.has(e)?"[Circular]":(t.add(e),e.map(r=>J0(r,t)));if(e!==null&&typeof e=="object"){if(t.has(e))return"[Circular]";t.add(e);const r={};for(const[n,i]of Object.entries(e))r[n]=J0(i,t);return r}return e}function kj(e){const t=new WeakSet;t.add(e);const r={};for(const[n,i]of Object.entries(e))r[n]=J0(i,t);return r}var Pj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let k_=class{subscribers;tag;tagFormatter;constructor(t,r,n=new Aj){this.subscribers=t,this.tag=r,this.tagFormatter=n}_log(t,r,n){const i=n?.data?kj(n.data):void 0,o=n?.tag??this.tag,s=this.tagFormatter.format(o);this.subscribers.forEach(u=>{const c={timestamp:n?.timestamp??Date.now(),tag:s,data:i};u.log(t,r,c)})}info(t,r){this._log(Du.Info,t,r)}warn(t,r){this._log(Du.Warning,t,r)}debug(t,r){this._log(Du.Debug,t,r)}error(t,r){this._log(Du.Error,t,r)}};k_=Pj([St()],k_);let sc=class extends Error{status;statusText;responseBody;isTimeout;cause;constructor(t){super(t.message),this.name="DmkNetworkClientError",this.status=t.status,this.statusText=t.statusText,this.responseBody=t.responseBody,this.isTimeout=t.isTimeout??!1,this.cause=t.cause}};const Mj="application/json";function Dj(e,t){if(!t)return e;const r=e.endsWith("/")?e.slice(0,-1):e,n=t.startsWith("/")?t:`/${t}`;return`${r}${n}`}function Lj(e){const t=[];for(const[r,n]of Object.entries(e))n!=null&&t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return t.join("&")}function as(e){const{url:t,params:r,baseUrl:n}=e,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:n?Dj(n,t):t,o=r?Lj(r):"";if(o.length===0)return i;const s=i.includes("?")?"&":"?";return`${i}${s}${o}`}function Fj(e,t){const r=t.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===r)}function Nj(e){return!!(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||typeof URLSearchParams<"u"&&e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream)}function jj(e){const{method:t,body:r,defaultHeaders:n,perRequestHeaders:i}=e,o={...n,...i};return r===void 0||t==="GET"||t==="HEAD"?{body:void 0,headers:o}:Nj(r)?{body:r,headers:o}:(Fj(o,"content-type")||(o["Content-Type"]=Mj),{body:JSON.stringify(r),headers:o})}function zj(e){const{timeoutMs:t}=e;if(!t||t<=0)return{signal:void 0,cleanup:()=>{}};const r=new AbortController,n=setTimeout(()=>{r.abort()},t);return{signal:r.signal,cleanup:()=>clearTimeout(n)}}async function Bj(e,t){switch(t){case"void":return;case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();default:{const r=await e.text();if(r.length===0)return;try{return JSON.parse(r)}catch(n){throw new sc({message:"Failed to parse JSON response body",status:e.status,statusText:e.statusText,responseBody:r,cause:n})}}}}async function Vj(e){try{return await e.text()}catch{return}}function Hj(e){const{cause:t,timeoutMs:r}=e,n=!!(r&&r>0);if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")){const i=t.name==="TimeoutError"||n;return new sc({message:i?"Request timed out":"Request aborted",isTimeout:i,cause:t})}return new sc({message:t instanceof Error?t.message:"Network request failed",cause:t})}let b2=class{baseUrl;defaultHeaders;fetchImpl;constructor(t={}){this.baseUrl=t.baseUrl,this.defaultHeaders=t.headers??{},this.fetchImpl=t.fetch}getFetch(){return this.fetchImpl??globalThis.fetch.bind(globalThis)}get(t,r){return this.request({...r,method:"GET",url:t}).then(n=>n.data)}post(t,r,n){return this.request({...n,method:"POST",url:t,body:r}).then(i=>i.data)}put(t,r,n){return this.request({...n,method:"PUT",url:t,body:r}).then(i=>i.data)}patch(t,r,n){return this.request({...n,method:"PATCH",url:t,body:r}).then(i=>i.data)}delete(t,r){return this.request({...r,method:"DELETE",url:t}).then(n=>n.data)}head(t,r){return this.request({...r,method:"HEAD",url:t,responseType:"void"}).then(()=>{})}async request(t){const r=as({url:t.url,params:t.params,baseUrl:this.baseUrl}),{body:n,headers:i}=jj({method:t.method,body:t.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:t.headers}),{signal:o,cleanup:s}=zj({timeoutMs:t.timeoutMs}),u=t.throwOnHttpError??!0,c=t.responseType??"json";try{let f;try{f=await this.getFetch()(r,{method:t.method,headers:i,body:n,signal:o})}catch(p){throw Hj({cause:p,timeoutMs:t.timeoutMs})}if(!f.ok&&u){const p=await Vj(f);throw new sc({message:`HTTP error ${f.status} ${f.statusText}`.trim(),status:f.status,statusText:f.statusText,responseBody:p})}return{data:await Bj(f,c),status:f.status,statusText:f.statusText,headers:f.headers,ok:f.ok}}finally{s()}}};var Lu=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(Lu||{});const Uj=1,Wj="0";let fp=class{constructor(t){this.error=t,this.originalError=t}_tag="FetchError";originalError};var Fu=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(Fu||{}),Gj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},P_=(e,t)=>(r,n)=>t(r,n,e);const qo=e=>e instanceof sc&&e.cause!==void 0?new fp(e.cause):new fp(e);let M_=class{http;_provider=Uj;_firmwareDistributionSalt=Wj;_logger;constructor({managerApiUrl:t,provider:r,firmwareDistributionSalt:n},i){this.http=new b2({baseUrl:t}),this._provider=r,this._firmwareDistributionSalt=n,this._logger=i("HttpManagerApiDataSource")}setProvider(t){this._provider===t||t<1||(this._provider=t)}getProvider(){return this._provider}setFirmwareDistributionSalt(t){this._firmwareDistributionSalt===t||t.trim()===""||(this._firmwareDistributionSalt=t)}getFirmwareDistributionSalt(){return this._firmwareDistributionSalt}getAppList(t){const{targetId:r,firmwareVersionName:n}=t;return dt(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:n}})).chain(i=>this.mapApplicationDtoToApplication(i)).mapLeft(qo)}getMcuList(){return dt(()=>this.http.get("/mcu_versions")).chain(t=>this.mapMcuDtoToMcu(t)).mapLeft(qo)}getDeviceVersion(t){const{targetId:r}=t;return dt(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(n=>this.mapDeviceVersionDto(n)).mapLeft(qo)}getFirmwareVersion(t){const{deviceId:r,version:n}=t;return dt(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(i=>this.mapFinalFirmwareDto(i)).mapLeft(qo)}getFirmwareVersionById(t){return dt(()=>this.http.get(`/firmware_final_versions/${t}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(qo)}getOsuFirmwareVersion(t){const{deviceId:r,version:n}=t;return dt(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(i=>this.mapOsuFirmwareDto(i)).mapLeft(qo)}getLatestFirmwareVersion(t){const{currentFinalFirmwareId:r,deviceId:n}=t;return dt(()=>{const i=this._firmwareDistributionSalt;return this._logger.info("Requesting latest firmware",{data:{salt:i}}),this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:r,device_version:n,provider:this._provider,salt:i}})}).chain(i=>this.mapLatestFirmwareDto(i)).mapLeft(qo)}getAppsByHash(t){const{hashes:r}=t;return dt(()=>this.http.post("/v2/apps/hash",r)).chain(n=>this.mapNullableApplicationDtoToApplication(n)).mapLeft(qo)}getLanguagePackages(t){const{deviceId:r,currentFinalFirmwareId:n}=t;return dt(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:n}})).chain(i=>this.mapLanguagesDtoToLanguages(i)).mapLeft(qo)}mapAppTypeDtoToAppType(t){if(t===null)return null;switch(t){case Fu.currency:return Lu.currency;case Fu.plugin:return Lu.plugin;case Fu.tool:return Lu.tool;case Fu.swap:return Lu.swap}}mapApplicationDtoToApplication(t){return dt(()=>Promise.resolve(t.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(t){return dt(()=>Promise.resolve(t.map(r=>r===null?null:this.mapApplicationDto(r))))}mapApplicationDto(t){if(typeof t!="object"||typeof t.versionId!="number"||typeof t.versionName!="string"||t.versionDisplayName!==null&&typeof t.versionDisplayName!="string"||typeof t.version!="string"||t.currencyId!==null&&typeof t.currencyId!="string"||t.description!==null&&typeof t.description!="string"||t.applicationType!==null&&typeof t.applicationType!="string"||typeof t.dateModified!="string"||t.icon!==null&&typeof t.icon!="string"||t.authorName!==null&&typeof t.authorName!="string"||t.supportURL!==null&&typeof t.supportURL!="string"||t.contactURL!==null&&typeof t.contactURL!="string"||t.sourceURL!==null&&typeof t.sourceURL!="string"||t.compatibleWallets!==null&&typeof t.compatibleWallets!="string"||typeof t.hash!="string"||typeof t.perso!="string"||typeof t.firmware!="string"||typeof t.firmwareKey!="string"||typeof t.delete!="string"||typeof t.deleteKey!="string"||t.bytes!==null&&typeof t.bytes!="number"||t.warning!==null&&typeof t.warning!="string"||typeof t.isDevTools!="boolean"||t.category!==null&&typeof t.category!="number"||t.parent!==null&&typeof t.parent!="number"||t.parentName!==null&&typeof t.parentName!="string")throw new Error(`Incomplete application: ${JSON.stringify(t)}`);const{applicationType:r,hash:n,perso:i,firmware:o,firmwareKey:s,delete:u,deleteKey:c,...f}=t;return{...f,hash:n,perso:i,firmware:o,firmwareKey:s,delete:u,deleteKey:c,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(t){return dt(()=>Promise.resolve(t.map(r=>{if(typeof r!="object"||typeof r.id!="number"||typeof r.name!="string"||typeof r.from_bootloader_version!="string")throw new Error(`Incomplete MCU version: ${JSON.stringify(r)}`);return{id:r.id,name:r.name,fromBootloaderVersion:r.from_bootloader_version,providers:r.providers}})))}mapDeviceVersionDto(t){return dt(()=>{if(typeof t!="object"||typeof t.id!="number")throw new Error(`Incomplete device version: ${JSON.stringify(t)}`);const r={id:t.id};return Promise.resolve(r)})}mapFinalFirmwareDto(t){return dt(()=>{if(typeof t!="object"||typeof t.id!="number"||typeof t.version!="string"||typeof t.perso!="string"||t.firmware!==null&&typeof t.firmware!="string"||t.firmware_key!==null&&typeof t.firmware_key!="string"||t.hash!==null&&typeof t.hash!="string"||t.bytes!==null&&typeof t.bytes!="number"||!Array.isArray(t.mcu_versions))throw new Error(`Incomplete final firmware: ${JSON.stringify(t)}`);const r={id:t.id,version:t.version,perso:t.perso,firmware:t.firmware,firmwareKey:t.firmware_key,hash:t.hash,bytes:t.bytes,mcuVersions:t.mcu_versions};return Promise.resolve(r)})}mapLatestFirmwareDto(t){return dt(()=>{if(t.result==="null")return Promise.resolve(null);if(t.result!=="success"||!t.se_firmware_osu_version)throw new Error(`Latest firmware could not be retrieved: ${t.result}`);const r=t.se_firmware_osu_version;return Promise.resolve(r)}).chain(r=>r===null?dt(()=>Promise.resolve(Dt)):this.mapOsuFirmwareDto(r).map(n=>Lr(n)))}mapOsuFirmwareDto(t){return dt(()=>{if(typeof t!="object"||typeof t.id!="number"||t.notes!==null&&typeof t.notes!="string"||typeof t.perso!="string"||typeof t.firmware!="string"||typeof t.firmware_key!="string"||t.hash!==null&&typeof t.hash!="string"||typeof t.next_se_firmware_final_version!="number")throw new Error(`Incomplete latest firmware: ${JSON.stringify(t)}`);const r={id:t.id,notes:t.notes,perso:t.perso,firmware:t.firmware,firmwareKey:t.firmware_key,hash:t.hash,nextFinalFirmware:t.next_se_firmware_final_version};return Promise.resolve(r)})}mapLanguagesDtoToLanguages(t){return dt(()=>Promise.resolve(t.map(r=>this.mapLanguageDto(r))))}mapLanguageDto(t){if(typeof t!="object"||typeof t.language!="string"||typeof t.languagePackageVersionId!="number"||typeof t.version!="string"||typeof t.language_package_id!="number"||typeof t.apdu_install_url!="string"||typeof t.apdu_uninstall_url!="string"||typeof t.bytes!="number"||typeof t.date_creation!="string"||typeof t.date_last_modified!="string")throw new Error(`Incomplete language version: ${JSON.stringify(t)}`);return{language:t.language,languagePackageVersionId:t.languagePackageVersionId,version:t.version,languagePackageId:t.language_package_id,apduInstallUrl:t.apdu_install_url,apduUninstallUrl:t.apdu_uninstall_url,bytes:t.bytes,dateCreation:t.date_creation,dateLastModified:t.date_last_modified}}};M_=Gj([St(),P_(0,Xe(Ac.DmkConfig)),P_(1,Xe(dr.LoggerPublisherServiceFactory))],M_);var qj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Xj=(e,t)=>(r,n)=>t(r,n,e);let D_=class{constructor(t){this.dataSource=t}getAppList(t){const r={targetId:t.targetId.toString(),firmwareVersionName:t.seVersion};return this.dataSource.getAppList(r)}getDeviceVersion(t){const r={targetId:t.targetId.toString()};return this.dataSource.getDeviceVersion(r)}getFirmwareVersion(t,r){const n={version:t.seVersion,deviceId:r.id};return this.dataSource.getFirmwareVersion(n)}getOsuFirmwareVersion(t,r){const n={version:t.seVersion,deviceId:r.id};return this.dataSource.getOsuFirmwareVersion(n)}getLatestFirmwareVersion(t,r){const n={currentFinalFirmwareId:t.id,deviceId:r.id};return this.dataSource.getLatestFirmwareVersion(n)}getNextFirmwareVersion(t){return this.dataSource.getFirmwareVersionById(t.nextFinalFirmware)}getLanguagePackages(t,r){const n={deviceId:t.id,currentFinalFirmwareId:r.id};return this.dataSource.getLanguagePackages(n)}getMcuList(){return this.dataSource.getMcuList()}getAppsByHash(t){const r={hashes:t};return dt(async({fromPromise:n,throwE:i})=>{if(r.hashes.length===0)return[];try{return await n(this.dataSource.getAppsByHash(r))}catch(o){return o instanceof fp?i(o):i(new fp(o))}})}getProvider(){return this.dataSource.getProvider()}};D_=qj([St(),Xj(0,Xe(Ac.ManagerApiDataSource))],D_);var Kj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},gm=(e,t)=>(r,n)=>t(r,n,e);let L_=class{constructor(t,r,n){this.sessionService=t,this.managerApiDataSource=r,this._logger=n("SetFirmwareDistributionSaltUseCase")}_logger;execute(t){if(t.trim()===""){this._logger.warn("Ignoring empty firmware distribution salt");return}const r=this.managerApiDataSource.getFirmwareDistributionSalt();if(t===r){this._logger.debug("Firmware distribution salt unchanged",{data:{salt:t}});return}this.managerApiDataSource.setFirmwareDistributionSalt(t);let n=0;for(const i of this.sessionService.getDeviceSessions()){const o=i.getDeviceSessionState();o.sessionStateType!==Ss.Connected&&o.firmwareUpdateContext!==void 0&&(i.setDeviceSessionState({...o,firmwareUpdateContext:void 0}),n++)}this._logger.info("Firmware distribution salt updated",{data:{previousSalt:r,salt:t,invalidatedSessions:n}})}};L_=Kj([St(),gm(0,Xe(en.DeviceSessionService)),gm(1,Xe(Ac.ManagerApiDataSource)),gm(2,Xe(dr.LoggerPublisherServiceFactory))],L_);var Yj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},F_=(e,t)=>(r,n)=>t(r,n,e);let N_=class{constructor(t,r){this.sessionService=t,this.managerApiDataSource=r}execute(t){for(const r of this.sessionService.getDeviceSessions()){const n=r.getDeviceSessionState();n.sessionStateType!==Ss.Connected&&r.setDeviceSessionState({...n,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(t)}};N_=Yj([St(),F_(0,Xe(en.DeviceSessionService)),F_(1,Xe(Ac.ManagerApiDataSource))],N_);var Qj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Jj=(e,t)=>(r,n)=>t(r,n,e);let j_=class{webSocketBaseUrl;constructor({webSocketUrl:t}){this.webSocketBaseUrl=t}setWebSocketUrl(t){this.webSocketBaseUrl===t||t.length===0||(this.webSocketBaseUrl=t)}getWebSocketUrl(){return this.webSocketBaseUrl}genuineCheck(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:t});return this._connectWebSocket(r)}installApp(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}listInstalledApps(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:t});return this._connectWebSocket(r)}uninstallApp(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateFirmware(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateMcu(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:t});return this._connectWebSocket(r)}_connectWebSocket(t){try{return nr(new o4(t))}catch(r){return Wt(new f4(r))}}};j_=Qj([St(),Jj(0,Xe(Bp.DmkConfig))],j_);var Zj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},ez=(e,t)=>(r,n)=>t(r,n,e);let z_=class{constructor(t){this.dataSource=t}genuineCheck(t,r){const n={targetId:t.targetId.toString(),perso:r.perso};return this.dataSource.genuineCheck(n)}installApp(t,r){const{perso:n,firmware:i,firmwareKey:o,hash:s}=r,u={targetId:t.targetId.toString(),perso:n,firmware:i,firmwareKey:o,hash:s};return this.dataSource.installApp(u)}listInstalledApps(t,r){const n={targetId:t.targetId.toString(),perso:r.perso};return this.dataSource.listInstalledApps(n)}uninstallApp(t,r){const{perso:n,delete:i,deleteKey:o,hash:s}=r,u={targetId:t.targetId.toString(),perso:n,firmware:i,firmwareKey:o,hash:s};return this.dataSource.uninstallApp(u)}updateFirmware(t,r){const n={targetId:t.targetId.toString(),perso:r.perso,firmware:r.firmware,firmwareKey:r.firmwareKey};return this.dataSource.updateFirmware(n)}updateMcu(t,r){const n={targetId:t.targetId.toString(),version:r.version};return this.dataSource.updateMcu(n)}};z_=Zj([St(),ez(0,Xe(Bp.SecureChannelDataSource))],z_);var tz=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},rz=(e,t)=>(r,n)=>t(r,n,e);let B_=class{constructor(t){this.secureChannelDataSource=t}execute(t){this.secureChannelDataSource.setWebSocketUrl(t)}};B_=tz([St(),rz(0,Xe(Bp.SecureChannelDataSource))],B_);var nz=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},V_=(e,t)=>(r,n)=>t(r,n,e);let H_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendApduUseCase")}async execute({sessionId:t,apdu:r,abortTimeout:n,triggersDisconnection:i}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async o=>(await o.sendApdu(r,{abortTimeout:n,triggersDisconnection:i})).caseOf({Right:s=>s,Left:s=>{throw this._logger.error("Error sending APDU",{data:{sessionId:t,apdu:r,error:s}}),s}}),Left:o=>{throw this._logger.error("Error getting deviceSession",{data:{error:o}}),o}})}};H_=nz([St(),V_(0,Xe(en.DeviceSessionService)),V_(1,Xe(dr.LoggerPublisherServiceFactory))],H_);var iz=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},el=(e,t)=>(r,n)=>t(r,n,e);let U_=class{constructor(t,r,n,i,o,s){if(this._config=r,this._loggerModuleFactory=n,this._deviceModelDataSource=i,this._apduSenderServiceFactory=o,this._apduReceiverServiceFactory=s,this._logger=n("TransportService"),t.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new i4("No transports provided, please check your configuration");for(const u of t){const c=this.addTransport(u);if(c.isLeft())throw c.extract()}}_transports=new Map;_logger;addTransport(t){const r=t({deviceModelDataSource:this._deviceModelDataSource,loggerServiceFactory:this._loggerModuleFactory,config:this._config,apduSenderServiceFactory:this._apduSenderServiceFactory,apduReceiverServiceFactory:this._apduReceiverServiceFactory});return this.addTransportInternal(r)}addTransportInternal(t){return this.getTransport(t.getIdentifier()).isJust()?(this._logger.warn(`Transport ${t.getIdentifier()} already exists, please check your configuration`),Wt(new n4(`Transport ${t.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(t.getIdentifier(),t),nr(void 0))}getTransport(t){return _n.fromNullable(this._transports.get(t))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(t){this.getTransport(t.transport).map(r=>r.disconnect({connectedDevice:t}))}};U_=iz([St(),el(0,Xe(Na.TransportsInput)),el(1,Xe(Na.DmkConfig)),el(2,Xe(dr.LoggerPublisherServiceFactory)),el(3,Xe(rj.DeviceModelDataSource)),el(4,Xe(en.ApduSenderServiceFactory)),el(5,Xe(en.ApduReceiverServiceFactory))],U_);const oz={ADD_LOG:"addLog"};function az(e){return{startListeningCommand:()=>e.sendMessage(Jo.START_LISTENING_DEVICES,"{}"),stopListeningCommand:()=>e.sendMessage(Jo.STOP_LISTENING_DEVICES,"{}"),startDiscoveringCommand:()=>e.sendMessage(Jo.START_DISCOVERING,"{}"),stopDiscoveringCommand:()=>e.sendMessage(Jo.STOP_DISCOVERING,"{}"),connectDeviceCommand:(t,r)=>e.sendMessage(Jo.CONNECT_DEVICE,JSON.stringify({deviceId:t,sessionRefresherOptions:r}))}}function sz(e){return{getProviderCommand:()=>e.sendMessage(Jo.GET_PROVIDER,"{}"),setProviderCommand:t=>e.sendMessage(Jo.SET_PROVIDER,JSON.stringify({provider:t}))}}let lz=0;function uz(e){return{sendApduCommand:(t,r)=>{const n=`apdu-${++lz}`,i=r.match(/.{1,2}/g)?.map(o=>parseInt(o,16))||[];return e.sendMessage(Jo.SEND_APDU,JSON.stringify({sessionId:t,apdu:i,requestId:n})),n}}}function cz(e){const{timestamp:t,tag:r,verbosity:n,message:i,payloadJSON:o}=JSON.parse(e);return{timestamp:t,tag:r,verbosity:n,message:i,payloadJSON:o,payload:JSON.parse(o)}}const fz="apdu-exchange";function dz(e){const t=e.payload;return typeof t!="object"||t===null||Array.isArray(t)||t.type!==fz||typeof t.apdu!="string"||typeof t.response!="string"?null:{sessionId:typeof t.sessionId=="string"?t.sessionId:void 0,apdu:t.apdu,response:t.response,timestamp:e.timestamp}}function pz(e,t){try{const{module:r}=JSON.parse(e);t(n=>new Set([...n,r]))}catch(r){console.error("Failed to parse moduleConnected payload",r)}}function hz(e,t,r,n){const i=cz(e);if(i!==null){if(t(o=>[...o,i]),n){const o=dz(i);o!==null&&r(s=>[...s,o])}return!0}return!1}function gz(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse connectedDevicesUpdate payload",r)}}function vz(e,t){try{const{sessionId:r,state:n}=JSON.parse(e);t(i=>new Map(i).set(r,n))}catch(r){console.error("Failed to parse deviceSessionStateUpdate payload",r)}}function mz(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse discoveredDevicesUpdate payload",r)}}function yz(e,t){try{const{provider:r}=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse providerValue payload",r)}}function bz(e,t){try{const r=JSON.parse(e);t(n=>new Map(n).set(r.requestId,r))}catch(r){console.error("Failed to parse apduResponse payload",r)}}function Sz(e){const[t,r]=x.useState([]),[n,i]=x.useState([]),[o,s]=x.useState([]),[u,c]=x.useState(new Set),[f,p]=x.useState([]),[g,h]=x.useState(new Map),[m,y]=x.useState([]),[b,S]=x.useState(!1),[_,E]=x.useState(!1),[O,R]=x.useState(null),[$,T]=x.useState(new Map),[P,L]=x.useState([]),[z,B]=x.useState(!1),X=x.useRef(!1),Y=x.useMemo(()=>({...e,sendMessage:(W,ve)=>{e.sendMessage(W,ve),i(se=>[...se,{type:W,payload:ve}])}}),[e]);x.useEffect(()=>{const{unsubscribe:W}=e.listenToMessages((ve,se)=>{switch(r(Ce=>[...Ce,{type:ve,payload:se}]),ve){case sN:pz(se,c);break;case Eu.CONNECTED_DEVICES_UPDATE:gz(se,p);break;case Eu.DEVICE_SESSION_STATE_UPDATE:vz(se,h);break;case Eu.DISCOVERED_DEVICES_UPDATE:mz(se,y);break;case Eu.PROVIDER_VALUE:yz(se,R);break;case Eu.APDU_RESPONSE:bz(se,T);break;case oz.ADD_LOG:hz(se,s,L,X.current);break}});return W},[e]);const N=x.useMemo(()=>az(Y),[Y]),j=x.useMemo(()=>sz(Y),[Y]),F=x.useMemo(()=>uz(Y),[Y]),q=x.useCallback(()=>{S(!0),y([]),N.startListeningCommand()},[N]),U=x.useCallback(()=>{S(!1),y([]),N.stopListeningCommand()},[N]),M=x.useCallback(()=>{E(!0),y([]),N.startDiscoveringCommand()},[N]),G=x.useCallback(()=>{E(!1),y([]),N.stopDiscoveringCommand()},[N]),K=x.useCallback(()=>{s([])},[]),D=x.useCallback(()=>{X.current=!0,B(!0)},[]),A=x.useCallback(()=>{X.current=!1,B(!1)},[]),J=x.useCallback(()=>{L([])},[]),Z=u.has(RC.LOGGER),ne=u.has(RC.DMK_INSPECTOR);return{receivedMessages:t,sentMessages:n,logs:o,connectedModules:u,connectedDevices:f,sessionStates:g,discoveredDevices:m,isListening:b,isActivelyDiscovering:_,isLoggerConnected:Z,isInspectorConnected:ne,providerValue:O,apduResponses:$,apduExchanges:P,isRecordingExchanges:z,sendMessage:Y.sendMessage,clearLogs:K,startRecordingExchanges:D,stopRecordingExchanges:A,clearRecordedExchanges:J,startListening:q,stopListening:U,startDiscovering:M,stopDiscovering:G,connectDevice:N.connectDeviceCommand,getProvider:j.getProviderCommand,setProvider:j.setProviderCommand,sendApdu:F.sendApduCommand}}const wz=ge.div`
|
|
465
|
+
Found @inject decorator at method "${f.toString()}" at class "${c.constructor.name}"`);Uu(c.constructor,Hd,Ud,NE(u(c),f))}})(e,t)(r,n,i)}catch(o){b4(r,n,i,o)}}}function lm(e,t){return r=>{const n=t(r);return i=>(n(i),e(i))}}function Xe(e){return S4(y4(ac.singleInjection,e),g4)}(function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property"})(Oa||(Oa={}));const jE="@inversifyjs/core/classIsInjectableFlagReflectKey",w4=[Array,BigInt,Boolean,Function,Number,Object,String];function x4(e){const t=N1(e,"design:paramtypes");t!==void 0&&Uu(e,Hd,Ud,(function(r){return n=>(r.forEach(((i,o)=>{var s;n.constructorArguments[o]!==void 0||(s=i,w4.includes(s))||(n.constructorArguments[o]=(function(u){return{isFromTypescriptParamType:!0,kind:ac.singleInjection,name:void 0,optional:!1,tags:new Map,value:u}})(i))})),n)})(t))}function St(e){return t=>{(function(r){if(N1(r,jE)!==void 0)throw new Fa(So.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${r.name}"`);d4(r,jE,!0)})(t),x4(t)}}var zE;(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection"})(zE||(zE={}));var BE;(function(e){e[e.singleMandatory=0]="singleMandatory",e[e.singleOptional=1]="singleOptional",e[e.multipleMandatory=2]="multipleMandatory",e[e.multipleOptional=3]="multipleOptional",e[e.length=4]="length"})(BE||(BE={}));let C4=class{constructor(t,r,n,i,o){this.deviceModel=t,this.serviceUuid=r,this.writeUuid=n,this.writeCmdUuid=i,this.notifyUuid=o}},Zs=class{id;productName;usbProductId;bootloaderUsbProductId;usbOnly;memorySize;getBlockSize;masks;bluetoothSpec;constructor(t){this.id=t.id,this.productName=t.productName,this.usbProductId=t.usbProductId,this.bootloaderUsbProductId=t.bootloaderUsbProductId,this.usbOnly=t.usbOnly,this.memorySize=t.memorySize,this.getBlockSize=t.getBlockSize,this.masks=t.masks,this.bluetoothSpec=t.bluetoothSpec}};var E4=Object.defineProperty,_4=(e,t,r)=>t in e?E4(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,R4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},O4=(e,t,r)=>_4(e,t+"",r);let $a=class{getAllDeviceModels(){return Object.values($a.deviceModelByIds)}getDeviceModel(t){return $a.deviceModelByIds[t.id]}filterDeviceModels(t){return this.getAllDeviceModels().filter(r=>Object.entries(t).every(([n,i])=>r[n]===i))}getBluetoothServicesInfos(){return Object.values($a.deviceModelByIds).reduce((t,r)=>{const{bluetoothSpec:n}=r;return n?{...t,...n.reduce((i,o)=>({...i,[o.serviceUuid]:new C4(r,o.serviceUuid,o.writeUuid,o.writeCmdUuid,o.notifyUuid)}),{})}:t},{})}getBluetoothServices(){return Object.values($a.deviceModelByIds).map(t=>(t.bluetoothSpec||[]).map(r=>r.serviceUuid)).flat().filter(t=>!!t)}};O4($a,"deviceModelByIds",{[Xt.NANO_S]:new Zs({id:Xt.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:320*1024,getBlockSize:e=>EE.lt(EE.coerce(e.firmwareVersion)??"","2.0.0")?4*1024:2*1024,masks:[823132160]}),[Xt.NANO_SP]:new Zs({id:Xt.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1533*1024,getBlockSize:()=>512,masks:[856686592]}),[Xt.NANO_X]:new Zs({id:Xt.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2*1024*1024,getBlockSize:()=>4*1024,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"}]}),[Xt.STAX]:new Zs({id:Xt.STAX,productName:"Ledger Stax",usbProductId:96,bootloaderUsbProductId:6,usbOnly:!1,memorySize:1533*1024,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"}]}),[Xt.FLEX]:new Zs({id:Xt.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,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"}]}),[Xt.APEX]:new Zs({id:Xt.APEX,productName:"Ledger Nano Gen5",usbProductId:128,bootloaderUsbProductId:8,usbOnly:!1,memorySize:1533*1024,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"}]})}),$a=R4([St()],$a);let $4=class{statusCode;data;constructor({statusCode:t,data:r}){this.statusCode=t,this.data=r}};const T4=5,os=1,X0=2,gl=2,K0=2,Dr=[];for(let e=0;e<256;++e)Dr.push((e+256).toString(16).slice(1));function I4(e,t=0){return(Dr[e[t+0]]+Dr[e[t+1]]+Dr[e[t+2]]+Dr[e[t+3]]+"-"+Dr[e[t+4]]+Dr[e[t+5]]+"-"+Dr[e[t+6]]+Dr[e[t+7]]+"-"+Dr[e[t+8]]+Dr[e[t+9]]+"-"+Dr[e[t+10]]+Dr[e[t+11]]+Dr[e[t+12]]+Dr[e[t+13]]+Dr[e[t+14]]+Dr[e[t+15]]).toLowerCase()}let um;const A4=new Uint8Array(16);function k4(){if(!um){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");um=crypto.getRandomValues.bind(crypto)}return um(A4)}const P4=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),VE={randomUUID:P4};function zp(e,t,r){if(VE.randomUUID&&!e)return VE.randomUUID();e=e||{};const n=e.random||(e.rng||k4)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,I4(n)}const ps={getLastBytesFrom(e,t){return e.slice(-t)},getFirstBytesFrom(e,t){return e.slice(0,t)},bytesToNumber(e){return e.reduce((t,r,n)=>t+r*Math.pow(256,e.length-1-n),0)},numberToByteArray(e,t){return new Uint8Array(t).map((r,n)=>e>>8*(t-1-n)&255)}},HE=2,cm=800;let UE=class{_tag="FramerOverflowError";originalError;constructor(){this.originalError=new Error("Frame header length is greater than frame size")}},M4=class{_tag="FramerApduError";originalError;constructor(){this.originalError=new Error("Frame offset is greater than apdu length")}},WE=class{_tag="ReceiverApduError";originalError;constructor(t){this.originalError=new Error(t??"Unable to parse apdu")}},GE=class{_tag="DeviceSessionNotFound";originalError;constructor(t){this.originalError=t??new Error("Device session not found")}},v2=class{_header;_data;constructor({header:t,data:r}){this._header=t,this._data=r}toString(){return JSON.stringify({header:this._header.toString(),data:Zo(this._data)},null,2)}getRawData(){const t=this._header.getRawData(),r=new Uint8Array(t.length+this._data.length);return r.set(t,0),r.set(this._data,t.length),r}getHeader(){return this._header}getData(){return this._data}},m2=class{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:t,dataSize:r,index:n,headTag:i,length:o,channel:s}){this._uuid=t,this._dataLength=r,this._index=n,this._headTag=i,this._length=o,this._channel=s}getDataLength(){return this._dataLength.map(t=>ps.bytesToNumber(t))}setDataSize(t){return this._dataLength=t,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:t=>[...t],Nothing:()=>[]}),...this._headTag,...this._index,...this._dataLength.caseOf({Just:t=>[...t],Nothing:()=>[]})])}};const dr={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var D4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},L4=(e,t)=>(r,n)=>t(r,n,e);let qE=class{_channel;_logger;_pendingFrames;constructor({channel:t=_n.zero()},r){this._channel=t,this._logger=r("ApduReceiverService"),this._pendingFrames=[]}handleFrame(t){return this.getFrameFromBytes(t).map(r=>{if(this._pendingFrames.push(r),!this._pendingFrames[0])return Dt;const n=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(n)})}getCompleteFrame(t){return t.chain(r=>{if(!this.isComplete(r))return this._logger.debug("frame is not complete, waiting for more"),Dt;const n=ps.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),i=ps.getFirstBytesFrom(n,n.length-HE),o=ps.getLastBytesFrom(n,HE);return this._pendingFrames=[],Lr(new $4({data:i,statusCode:o}))})}getFrameFromBytes(t){const r=this._channel.caseOf({Just:()=>X0,Nothing:()=>0}),n=t.slice(r,r+os),i=t.slice(r+os,r+os+gl),o=i.reduce((h,m)=>h+m,0)===0;if(!o&&this._pendingFrames.length===0)return Wt(new WE);const s=r+os+gl,u=o?K0:0;if(t.length<r+os+gl+u)return Wt(new WE("Unable to parse header from apdu"));const c=o?Lr(t.slice(s,s+u)):Dt,f=s+u,p=t.slice(f),g=new v2({header:new m2({uuid:zp(),channel:this._channel,dataSize:c,headTag:n,index:i,length:r+os+gl+u}),data:p});return nr(g)}isComplete(t){return this._pendingFrames.reduce((r,n)=>r+n.getData().length,0)>=t}concatFrames(t){return t.reduce((r,n)=>Uint8Array.from([...r,...n.getData()]),new Uint8Array(0))}};qE=D4([St(),L4(1,Xe(dr.LoggerPublisherServiceFactory))],qE);var F4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},N4=(e,t)=>(r,n)=>t(r,n,e);let XE=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:t,channel:r=_n.zero(),padding:n=!1},i){this._frameSize=t,this._channel=r,this._padding=n,this._logger=i("DefaultApduSenderService")}getFrames(t){const r=[];let n=0,i=this.getFrameAtIndex(t,n);for(;i.isRight();)r.push(i.extract()),n+=1,i=this.getFrameAtIndex(t,n).mapLeft(o=>(o instanceof UE||this._logger.error("Error while parsing frame",{data:{error:o}}),o));return r}getFrameAtIndex(t,r){const n=this.getFrameHeaderFrom(r,t.length),i=r===0?0:r*this._frameSize-this.getHeaderSizeSumFrom(r);if(i>=t.length)return Wt(new UE);if(n.getLength()>this._frameSize)return Wt(new M4);const o=this._frameSize-n.getLength(),s=t.slice(i,i+this._frameSize-n.getLength()),u=this._padding?new Uint8Array(o).fill(0):new Uint8Array(s.length<o?s.length:o);u.set(s,0);const c=new v2({header:n,data:u});return nr(c)}getFrameHeaderFrom(t,r){const n=new m2({uuid:zp(),channel:this._channel.map(i=>ps.getLastBytesFrom(i,X0)),headTag:new Uint8Array([T4]),index:ps.numberToByteArray(t,gl),length:this.getFrameHeaderSizeFromIndex(t),dataSize:_n.zero()});return t===0&&n.setDataSize(_n.of(ps.numberToByteArray(r,K0))),n}getHeaderSizeSumFrom(t){let r=this.getFrameHeaderSizeFromIndex(0),n=1;for(;n<t;)r+=this.getFrameHeaderSizeFromIndex(n),n+=1;return r}getFrameHeaderSizeFromIndex(t){return this._channel.caseOf({Just:()=>X0,Nothing:()=>0})+gl+os+(t===0?K0:0)}};XE=F4([St(),N4(1,Xe(dr.LoggerPublisherServiceFactory))],XE);const Y0={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService")},en={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService")},KE={ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase")},Ac={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig")},Bp={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")},Na={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var j4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},YE=(e,t)=>(r,n)=>t(r,n,e);let QE=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendCommandUseCase")}async execute({sessionId:t,command:r,abortTimeout:n}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async i=>await i.sendCommand(r,n),Left:i=>{throw this._logger.error("Error getting session",{data:{error:i}}),i}})}};QE=j4([St(),YE(0,Xe(en.DeviceSessionService)),YE(1,Xe(dr.LoggerPublisherServiceFactory))],QE);var z4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let JE=class{execute=vi.fn(()=>"stub")};JE=z4([St()],JE);var B4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},ZE=(e,t)=>(r,n)=>t(r,n,e);let e_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("ExecuteDeviceActionUseCase")}execute({sessionId:t,deviceAction:r}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:n=>n.executeDeviceAction(r),Left:n=>{throw this._logger.error("Error getting session",{data:{error:n}}),n}})}};e_=B4([St(),ZE(0,Xe(en.DeviceSessionService)),ZE(1,Xe(dr.LoggerPublisherServiceFactory))],e_);function V4(e){return typeof e=="object"&&e!==null&&"version"in e&&"name"in e&&typeof e.version=="string"&&typeof e.name=="string"}let t_=class{constructor(t){this.err=t,this.originalError=t}_tag="ApiCallError";originalError},H4=class{constructor(t){this.err=t,this.originalError=t}_tag="ParseResponseError";originalError},y2=class{constructor(t){this.err=t,this.originalError=t}_tag="JSONParseError";originalError},U4=class{constructor(t){this.err=t,this.originalError=t}_tag="ReadFileError";originalError};const W4="@ledgerhq/device-management-kit",G4="0.0.0-develop-20261102000856",r_={name:W4,version:G4};var q4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};const X4={name:r_.name,version:r_.version},K4=()=>JSON.stringify(X4);let n_=class{getConfig(){return Rn.encase(()=>K4()).mapLeft(t=>new U4(t)).chain(t=>Rn.encase(()=>{const r=JSON.parse(t);if(V4(r))return r;throw new Error("Invalid config file")}).mapLeft(r=>new y2(r)))}};n_=q4([St()],n_);var Y4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let i_=class{getConfig(){return Rn.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};i_=Y4([St()],i_);var Q4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let o_=class{async getConfig(){const t=await this._callApi();if(t.isLeft())return Wt(new t_(t.extract()));if(!t.extract().ok)return Wt(new t_(new Error("response not ok")));const r=await t.extract().json();return r.isLeft()?Wt(new y2):r.chain(n=>this._parseResponse(n)).map(n=>n)}_parseResponse(t){const{name:r,version:n}=t;return!r||!n?Wt(new H4):Rn.of({name:r,version:n})}_callApi(){return new Promise(t=>{t(Rn.of({ok:!0,json:async()=>new Promise(r=>{r(Rn.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};o_=Q4([St()],o_);var J4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let a_=class{async getConfig(){return new Promise(t=>t(Rn.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};a_=J4([St()],a_);var Z4=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},fm=(e,t)=>(r,n)=>t(r,n,e);let s_=class{_local;_remote;_logger;constructor(t,r,n){this._local=t,this._remote=r,this._logger=n("config")}async getDmkConfig(){const t=this._local.getConfig().ifLeft(r=>{this._logger.error("Local config not available",{data:{error:r}})});if(t.isRight()){const r=t.extract();return this._logger.info("Local config available",{data:{config:r}}),r}return this._remote.getConfig().then(r=>r.mapLeft(n=>(this._logger.error("Local config available",{data:{error:n}}),{name:"DeadDmk",version:"0.0.0-dead.1"})).extract())}};s_=Z4([St(),fm(0,Xe(Y0.LocalConfigDataSource)),fm(1,Xe(Y0.RemoteConfigDataSource)),fm(2,Xe(dr.LoggerPublisherServiceFactory))],s_);var ej=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},tj=(e,t)=>(r,n)=>t(r,n,e);let l_=class{_configService;constructor(t){this._configService=t}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};l_=ej([St(),tj(0,Xe(Y0.ConfigService))],l_);const rj={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var nj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},u_=(e,t)=>(r,n)=>t(r,n,e);let c_=class{constructor(t,r){this._sessionService=t,this._logger=r("DisableDeviceSessionRefresherUseCase")}_logger;execute({sessionId:t,blockerId:r}){return this._sessionService.getDeviceSessionById(t).caseOf({Left:n=>{throw this._logger.error("Error getting device session",{data:{error:n}}),n},Right:n=>n.disableRefresher(r)})}};c_=nj([St(),u_(0,Xe(en.DeviceSessionService)),u_(1,Xe(dr.LoggerPublisherServiceFactory))],c_);var ij=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},oj=(e,t)=>(r,n)=>t(r,n,e);let f_=class{_sessions;_sessionsSubject;_logger;constructor(t){this._sessions=[],this._sessionsSubject=new YT,this._logger=t("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(t){return this._sessions.find(r=>r.id===t.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:t}}),this):(this._sessions.push(t),this._sessionsSubject.next(t),this._logger.info("DeviceSession added",{data:{sessionId:t.id}}),this)}removeDeviceSession(t){const r=this._sessions.find(n=>n.id===t);return r?(r.close(),this._sessions=this._sessions.filter(n=>n.id!==t),this._logger.info("DeviceSession removed",{data:{sessionId:t}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:t}}),this)}getDeviceSessionById(t){return _n.fromNullable(this._sessions.find(r=>r.id===t)).toEither(new GE)}getDeviceSessionsByDeviceId(t){return _n.fromPredicate(({length:r})=>r>0,this._sessions.filter(r=>r.connectedDevice.id===t)).toEither(new GE)}getDeviceSessions(){return this._sessions}};f_=ij([St(),oj(0,Xe(dr.LoggerPublisherServiceFactory))],f_);var aj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},d_=(e,t)=>(r,n)=>t(r,n,e);let p_=class{_sessionService;_transportService;constructor(t,r){this._sessionService=t,this._transportService=r}execute(){const t=this._sessionService.getDeviceSessions();for(const r of t)this._transportService.closeConnection(r.connectedDevice),this._sessionService.removeDeviceSession(r.id)}};p_=aj([St(),d_(0,Xe(en.DeviceSessionService)),d_(1,Xe(Na.TransportService))],p_);var sj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},h_=(e,t)=>(r,n)=>t(r,n,e);let g_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("GetDeviceSessionStateUseCase")}execute({sessionId:t}){return this._sessionService.getDeviceSessionById(t).caseOf({Left:r=>{throw this._logger.error("Error getting session device",{data:{error:r}}),r},Right:r=>r.state})}};g_=sj([St(),h_(0,Xe(en.DeviceSessionService)),h_(1,Xe(dr.LoggerPublisherServiceFactory))],g_);var lj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},v_=(e,t)=>(r,n)=>t(r,n,e);let m_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("UnsafeBypassIntentQueueUseCase")}execute({sessionId:t,bypass:r}){this._sessionService.getDeviceSessionById(t).caseOf({Left:n=>{throw this._logger.error("Error getting session",{data:{error:n}}),n},Right:n=>{this._logger.warn(`UNSAFE: ${r?"Enabling":"Disabling"} intent queue bypass for session ${t}`),n._unsafeBypassIntentQueue(r)}})}};m_=lj([St(),v_(0,Xe(en.DeviceSessionService)),v_(1,Xe(dr.LoggerPublisherServiceFactory))],m_);function uj(e){return`[will send APDU] ~...> ${Zo(e,!1)}`}function cj(e){return`[exchange] <= ${Zo(e.data,!1)}${Zo(e.statusCode,!1)}`}const fj="apdu-exchange";function dj(e,t,r){const n=Zo(t,!1),i=`${Zo(r.data,!1)}${Zo(r.statusCode,!1)}`;return{message:cj(r),data:{type:fj,sessionId:e,apdu:n,response:i}}}const Q0=1e3,dm=1e3,pj={isRefresherDisabled:!1,pollingInterval:1e3};var ur=(e=>(e.NEW_STATE="NEW_STATE",e.REFRESH_NEEDED="REFRESH_NEEDED",e.COMMAND_SUCCEEDED="COMMAND_SUCCEEDED",e.DEVICE_STATE_UPDATE_BUSY="DEVICE_STATE_UPDATE_BUSY",e.DEVICE_STATE_UPDATE_LOCKED="DEVICE_STATE_UPDATE_LOCKED",e.DEVICE_STATE_UPDATE_CONNECTED="DEVICE_STATE_UPDATE_CONNECTED",e.DEVICE_STATE_UPDATE_UNKNOWN="DEVICE_STATE_UPDATE_UNKNOWN",e))(ur||{});let hj=class{_eventEmitter=new Ul;listen(){return this._eventEmitter.asObservable()}dispatch(t){this._eventEmitter.next(t)}},gj=class{constructor(t,r){this.loggerModuleFactory=t,this.sessionEventDispatcher=r,this._logger=this.loggerModuleFactory("IntentQueueService")}_logger;_queue=[];_isProcessing=!1;_currentSubscription=null;enqueue(t){this._logger.debug("Enqueueing intent",{data:{type:t.type}});const r=new Ul,n={intent:t,subject:r,isCancelled:!1};this._queue.push(n);const i=()=>{this._logger.debug("Cancelling intent",{data:{type:t.type}}),n.isCancelled=!0,this._queue[0]===n&&this._currentSubscription?(this._currentSubscription.unsubscribe(),this._currentSubscription=null,r.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue()):(!this._isProcessing||this._queue[0]!==n)&&r.complete()};return this._isProcessing||this._processQueue(),{observable:r.asObservable().pipe(Q3(()=>{this._logger.debug("Intent observable finalized",{data:{type:t.type}})})),cancel:i}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:ur.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_BUSY}),this._isProcessing=!0;const t=this._queue[0];if(t.isCancelled){this._logger.debug("Skipping cancelled intent",{data:{type:t.intent.type}}),t.subject.complete(),this._queue.shift(),this._isProcessing=!1,this._processQueue();return}this._logger.debug("Processing intent",{data:{type:t.intent.type}}),this._currentSubscription=t.intent.execute().subscribe({next:r=>{t.isCancelled||t.subject.next(r)},error:r=>{t.isCancelled||t.subject.error(r),this._onIntentComplete()},complete:()=>{t.isCancelled||t.subject.complete(),this._onIntentComplete()}})}_onIntentComplete(){this._logger.debug("Intent completed"),this._currentSubscription=null,this._queue.shift(),this._isProcessing=!1,this._processQueue()}},vj=class{constructor(t,r){this._refresher=r,this._logger=t("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(t){const r=`${t}-${zp()}`;this.addRefresherBlocker(r),this._logger.debug("Refresher disabled",{data:{blockerId:r,blockers:Array.from(this._refresherBlockers)}});let n=!1;return()=>{n||(n=!0,this.removeRefresherBlocker(r),this._logger.debug("Refresher re-enabled",{data:{blockerId:r,blockers:Array.from(this._refresherBlockers)}}))}}addRefresherBlocker(t){const r=this._refresherBlockers.size;this._refresherBlockers.add(t),r===0&&this._refresher.stop()}removeRefresherBlocker(t){const r=this._refresherBlockers.size;this._refresherBlockers.delete(t),r>0&&this._refresherBlockers.size===0&&this._refresher.start()}},mj=class{constructor(t,r,n,i){this.connectedDevice=r,this._sessionEventDispatcher=n,this._sendCommandFunction=i,this._logger=t("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async o=>await this.mapEventAction(o))}_sendCommandFunction;_subscription;_logger;async ping(){try{return await this.mapDevicePingAction(this.connectedDevice.deviceModel.id)}catch(t){return this._logger.error("Error while pinging device",{data:{error:t}}),null}}mapEventAction=async t=>t.eventName===ur.REFRESH_NEEDED?await this.ping():null;async mapDevicePingAction(t){if(t===Xt.NANO_S){const r=async()=>{const o=await this._sendCommandFunction(new kC,cm);return this._sendCommandFunction(new QN,cm),o},n=new Promise(o=>{setTimeout(()=>o(null),Q0*2+100)}),i=await Promise.race([r(),n]);return i?this._sessionEventDispatcher.dispatch({eventName:ur.COMMAND_SUCCEEDED,eventData:i}):this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_LOCKED}),i}else{const r=await this._sendCommandFunction(new kC,cm);return this._sessionEventDispatcher.dispatch({eventName:ur.COMMAND_SUCCEEDED,eventData:r}),r}}unsubscribe(){this._subscription.unsubscribe()}},yj=class{constructor(t,r,n,i){this._sessionEventDispatcher=n,this._refresherOptions=r,this._logger=t("device-session-refresher"),this._connectedDeviceID=i.deviceModel.id}_refresherSubscription;_refresherOptions;_logger;_connectedDeviceID;startRefresher(){if(this._refresherOptions.isRefresherDisabled||this._refresherSubscription)return;const t=this.getValidPollingInterval(this._refresherOptions,this._logger),r=this._sessionEventDispatcher.listen().pipe(PE(n=>n.eventName===ur.DEVICE_STATE_UPDATE_BUSY||n.eventName===ur.NEW_STATE),La(n=>n.eventName===ur.DEVICE_STATE_UPDATE_BUSY),Z3(!1),K3());this._refresherSubscription=G3(0,t).pipe(e4(r),ME(([n,i])=>{i&&this._logger.debug("Refresh skipped: device is busy")}),PE(([n,i])=>!i),ME(()=>this._sessionEventDispatcher.dispatch({eventName:ur.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=(t,r)=>{const{pollingInterval:n}=t;if(this._connectedDeviceID===Xt.NANO_S){const i=Q0*2;return n!==void 0&&n<i?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${i}`),i):n??i}else return n!==void 0&&n<dm?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${dm}`),dm):n??Q0}},bj=class{constructor(t,r,n,i,o){this._sessionEventDispatcher=r,this._connectedDevice=n,this._deviceState=i,this.setDeviceSessionState=o,this._subscription=this._sessionEventDispatcher.listen().subscribe(s=>this.mapEventAction(s)),this._logger=t("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=ho.BUSY;_updateDeviceState(t){const r=this._parseDeviceStatus(t);if(r){const{sessionStateType:n,deviceStatus:i,currentApp:o}=r,s=this._deviceState.getValue();s.sessionStateType===Ss.Connected?this.setDeviceSessionState({sessionStateType:n,deviceStatus:i,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:o,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...s,sessionStateType:n,deviceStatus:i,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:o})}}mapEventAction=t=>{const{eventName:r}=t;switch(r){case ur.COMMAND_SUCCEEDED:return this._updateDeviceState(t.eventData);case ur.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:ho.BUSY});case ur.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=ho.LOCKED;return;case ur.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=ho.CONNECTED;return;case ur.NEW_STATE:{const n=this._pendingDeviceStatus;return this._pendingDeviceStatus=ho.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:n})}case ur.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:ho.BUSY});case ur.REFRESH_NEEDED:return;default:{const n=r;throw new Error(`Unhandled context type ${n}`)}}};_parseDeviceStatus(t){return mN(t)?{sessionStateType:Ss.ReadyWithoutSecureChannel,deviceStatus:ho.CONNECTED,currentApp:{name:t.data.name,version:t.data.version}}:(this._logger.debug("Error while parsing APDU response",{data:{parsedResponse:t}}),null)}unsubscribe(){this._subscription.unsubscribe()}},Sj=class{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new hj;_bypassIntentQueue=!1;constructor({connectedDevice:t,id:r=zp()},n,i,o,s,u=c=>new gj(n,c)){this._id=r,this._connectedDevice=t,this._loggerModuleFactory=n,this._logger=n("device-session"),this._managerApiService=i,this._intentQueueService=u(this._sessionEventDispatcher),this._secureChannelService=o,this._refresherOptions={...pj,...s},this._deviceState=new S3({sessionStateType:Ss.Connected,deviceStatus:ho.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new mj(n,t,this._sessionEventDispatcher,(c,f)=>this.sendCommand(c,f)),this._deviceSessionRefresher=new yj(n,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new bj(n,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,c=>this.setDeviceSessionState(c)),this._refresherService=new vj(n,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{this._refresherOptions.isRefresherDisabled?await this._pinger.ping():this._deviceSessionRefresher.startRefresher()}catch(t){throw this._logger.error("Error while initialising session",{data:{error:t}}),t}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(t){this._deviceState.next(t)}sendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._bypassIntentQueue?this._unsafeInternalSendApdu(t,r):this._internalSendApdu(t,r)}_internalSendApdu(t,r){const n=r.abortTimeout,i=Date.now(),{observable:o,cancel:s}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>Il((async()=>{const c=Date.now()-i;return await this._unsafeInternalSendApdu(t,{isPolling:r.isPolling,triggersDisconnection:r.triggersDisconnection,abortTimeout:n?n-c:void 0})})())}),u=n?o.pipe(AE({each:n,with:()=>{throw s(),new t4}})):o;return IE(u)}async _unsafeInternalSendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(uj(t)),(await this._connectedDevice.sendApdu(t,r.triggersDisconnection,r.abortTimeout)).ifRight(n=>{const{message:i,data:o}=dj(this._id,t,n);this._logger.debug(i,{data:o}),w1.isLockedDeviceResponse(n)?this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:ur.DEVICE_STATE_UPDATE_UNKNOWN})})}sendCommand(t,r){return this._logger.debug(`[sendCommand] ${t.name}`),this._bypassIntentQueue?this._unsafeInternalSendCommand(t,r):this._internalSendCommand(t,r)}_internalSendCommand(t,r){const n=Date.now(),{observable:i,cancel:o}=this._intentQueueService.enqueue({type:"send-command",execute:()=>Il((async()=>{const u=Date.now()-n;return await this._unsafeInternalSendCommand(t,r?r-u:void 0)})())}),s=r?i.pipe(AE({each:r,with:()=>{throw o(),new r4}})):i;return IE(s)}async _unsafeInternalSendCommand(t,r){const n=t.getApdu();return(await this._unsafeInternalSendApdu(n.getRawApdu(),{isPolling:!1,triggersDisconnection:t.triggersDisconnection??!1,abortTimeout:r})).caseOf({Left:i=>{throw this._logger.error("[sendCommand] error",{data:{err:i}}),i},Right:i=>{const o=t.parseResponse(i,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:o}}),o}})}executeDeviceAction(t){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(t):this._internalExecuteDeviceAction(t)}_internalExecuteDeviceAction(t){let r;const{observable:n,cancel:i}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{const{observable:o,cancel:s}=this._unsafeInternalExecuteDeviceAction(t);return r=s,o}});return{observable:n,cancel:()=>{r?.(),i()}}}_unsafeInternalExecuteDeviceAction(t){const{observable:r,cancel:n}=t._execute({sendApdu:async i=>this._unsafeInternalSendApdu(i),sendCommand:async i=>this._unsafeInternalSendCommand(i),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:i=>(this.setDeviceSessionState(i),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:r,cancel:n}}close(){this._updateDeviceStatus(ho.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher(),this._pinger.unsubscribe()}disableRefresher(t){return this._refresherService.disableRefresher(t)}_unsafeBypassIntentQueue(t){this._bypassIntentQueue=t}_updateDeviceStatus(t){const r=this._deviceState.getValue();this._deviceState.next({...r,deviceStatus:t})}};var wj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},_u=(e,t)=>(r,n)=>t(r,n,e);let y_=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(t,r,n,i,o){this._sessionService=r,this._transportService=t,this._loggerFactory=n,this._logger=n("ConnectUseCase"),this._managerApi=i,this._secureChannel=o}handleDeviceDisconnect(t){this._sessionService.getDeviceSessionsByDeviceId(t).ifRight(r=>{r.forEach(n=>{this._sessionService.removeDeviceSession(n.id),this._logger.info("Session removed",{data:{deviceId:t,sessionId:n.id}})})})}async execute({device:t,sessionRefresherOptions:r}){const n=this._transportService.getTransport(t.transport),i="sessionId"in t?t.sessionId:void 0;return dt.liftEither(n.toEither(new F1(new Error("Unknown transport")))).chain(async o=>o.connect({deviceId:t.id,onDisconnect:s=>this.handleDeviceDisconnect(s)})).ifLeft(o=>{this._logger.error("Error connecting to device")}).map(async o=>{const s=new Sj({connectedDevice:o,id:i},this._loggerFactory,this._managerApi,this._secureChannel,r);return this._sessionService.addDeviceSession(s),await s.initialiseSession(),s.id}).caseOf({Left:o=>{throw o},Right:o=>o})}};y_=wj([St(),_u(0,Xe(Na.TransportService)),_u(1,Xe(en.DeviceSessionService)),_u(2,Xe(dr.LoggerPublisherServiceFactory)),_u(3,Xe(Ac.ManagerApiService)),_u(4,Xe(Bp.SecureChannelService))],y_);var xj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},pm=(e,t)=>(r,n)=>t(r,n,e);let b_=class{_transportService;_sessionService;_logger;constructor(t,r,n){this._sessionService=r,this._transportService=t,this._logger=n("DisconnectUseCase")}async execute({sessionId:t}){return this._logger.debug("Disconnecting from device",{data:{test:this._sessionService.getDeviceSessions().map(r=>r.id)}}),dt(async({liftEither:r})=>{const n=await r(this._sessionService.getDeviceSessionById(t).ifLeft(s=>{this._logger.error("Device session not found",{data:{sessionId:t,error:s}})})),i=n.connectedDevice.transport,o=await r(this._transportService.getTransport(i).toEither(new F1(new Error("Unknown transport"))));n.close(),this._sessionService.removeDeviceSession(t),await o.disconnect({connectedDevice:n.connectedDevice})}).caseOf({Left:r=>{throw this._logger.error("Error disconnecting from device",{data:{error:r}}),r},Right:()=>{}})}};b_=xj([St(),pm(0,Xe(Na.TransportService)),pm(1,Xe(en.DeviceSessionService)),pm(2,Xe(dr.LoggerPublisherServiceFactory))],b_);let j1=class{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:t,deviceModel:{id:r,productName:n},type:i,transport:o,name:s},sessionId:u}){this.id=t,this.sessionId=u,this.modelId=r,this.name=s??n,this.type=i,this.transport=o}};var Cj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},S_=(e,t)=>(r,n)=>t(r,n,e);let w_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("GetConnectedDeviceUseCase")}execute({sessionId:t}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:r=>new j1({sessionId:r.id,transportConnectedDevice:r.connectedDevice}),Left:r=>{throw this._logger.error("Error getting session",{data:{error:r}}),r}})}};w_=Cj([St(),S_(0,Xe(en.DeviceSessionService)),S_(1,Xe(dr.LoggerPublisherServiceFactory))],w_);var Ej=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},x_=(e,t)=>(r,n)=>t(r,n,e);let C_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("ListConnectedDeviceUseCase")}execute(){return this._logger.info("Listing connected devices"),this._sessionService.getDeviceSessions().map(t=>new j1({transportConnectedDevice:t.connectedDevice,sessionId:t.id}))}};C_=Ej([St(),x_(0,Xe(en.DeviceSessionService)),x_(1,Xe(dr.LoggerPublisherServiceFactory))],C_);var _j=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},E_=(e,t)=>(r,n)=>t(r,n,e);let __=class{_transports;_transportService;_logger;constructor(t,r){this._transports=t.getAllTransports(),this._transportService=t,this._logger=r("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(t){const r=new NT({id:t.id,model:t.deviceModel.id,name:t.deviceModel.productName});return{id:t.id,deviceModel:r,transport:t.transport,name:t.name||r.name,rssi:t.rssi}}execute({transport:t}={}){if(this._logger.info("Listening to available devices"),this._transports.length===0)return this._logger.warn("No transports available"),Il([[]]);if(!t){this._logger.info("Discovering all available transports");const r=this._transports.map((n,i)=>n.listenToAvailableDevices().pipe(La(o=>({index:i,arr:o}))));return q3(...r).pipe(J3((n,{index:i,arr:o})=>(n[i]=o,n),{}),La(n=>Object.values(n).flat().map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))}return this._logger.info(`Discovering devices on transport ${t}`),this._transportService.getTransport(t).caseOf({Nothing:()=>(this._logger.error(`Transport ${t} not found`),d2([])),Just:r=>r.listenToAvailableDevices().pipe(La(n=>n.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};__=_j([St(),E_(0,Xe(Na.TransportService)),E_(1,Xe(dr.LoggerPublisherServiceFactory))],__);var Rj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},R_=(e,t)=>(r,n)=>t(r,n,e);let O_=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(La(t=>new j1({transportConnectedDevice:t.connectedDevice,sessionId:t.id})))}};O_=Rj([St(),R_(0,Xe(en.DeviceSessionService)),R_(1,Xe(dr.LoggerPublisherServiceFactory))],O_);var Oj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},hm=(e,t)=>(r,n)=>t(r,n,e);let $_=class{constructor(t,r,n){this.connectUseCase=t,this.disconnectUseCase=r,this._logger=n("ReconnectUseCase")}_logger;async execute({device:t,sessionRefresherOptions:r}){return this._logger.debug("Reconnecting device session",{data:{deviceId:t.id,transport:t.transport}}),await this.disconnectUseCase.execute({sessionId:t.sessionId}),this.connectUseCase.execute({device:t,sessionRefresherOptions:r})}};$_=Oj([St(),hm(0,Xe(KE.ConnectUseCase)),hm(1,Xe(KE.DisconnectUseCase)),hm(2,Xe(dr.LoggerPublisherServiceFactory))],$_);var $j=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Tj=(e,t)=>(r,n)=>t(r,n,e);let T_=class{constructor(t){this._transportService=t}mapDiscoveredDevice(t){const r=new NT({id:t.id,model:t.deviceModel.id,name:t.deviceModel.productName});return{id:t.id,deviceModel:r,transport:t.transport,name:t.name||r.name,rssi:t.rssi}}execute({transport:t}={}){if(!t){const r=this._transportService.getAllTransports();return d2(...r).pipe(L1(n=>n.startDiscovering().pipe(La(i=>this.mapDiscoveredDevice(i)))))}return this._transportService.getTransport(t).caseOf({Just:r=>r.startDiscovering().pipe(La(n=>this.mapDiscoveredDevice(n))),Nothing:()=>{throw new F1(new Error("Unknown transport"))}})}};T_=$j([St(),Tj(0,Xe(Na.TransportService))],T_);var Ij=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},I_=(e,t)=>(r,n)=>t(r,n,e);let A_=class{constructor(t,r){this.transportService=t,this._logger=r("StopDiscoveringUseCase")}_logger;async execute(){this._logger.debug("Stopping discovering devices");for(const t of this.transportService.getAllTransports())await t.stopDiscovering()}};A_=Ij([St(),I_(0,Xe(Na.TransportService)),I_(1,Xe(dr.LoggerPublisherServiceFactory))],A_);var Du=(e=>(e[e.Fatal=0]="Fatal",e[e.Error=1]="Error",e[e.Warning=2]="Warning",e[e.Info=3]="Info",e[e.Debug=4]="Debug",e))(Du||{});let Aj=class{format(t){return Array.isArray(t)?t.map(r=>`[${r}]`).join(" "):`[${t}]`}};function J0(e,t){if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return t.has(e)?"[Circular]":(t.add(e),e.map(r=>J0(r,t)));if(e!==null&&typeof e=="object"){if(t.has(e))return"[Circular]";t.add(e);const r={};for(const[n,i]of Object.entries(e))r[n]=J0(i,t);return r}return e}function kj(e){const t=new WeakSet;t.add(e);const r={};for(const[n,i]of Object.entries(e))r[n]=J0(i,t);return r}var Pj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i};let k_=class{subscribers;tag;tagFormatter;constructor(t,r,n=new Aj){this.subscribers=t,this.tag=r,this.tagFormatter=n}_log(t,r,n){const i=n?.data?kj(n.data):void 0,o=n?.tag??this.tag,s=this.tagFormatter.format(o);this.subscribers.forEach(u=>{const c={timestamp:n?.timestamp??Date.now(),tag:s,data:i};u.log(t,r,c)})}info(t,r){this._log(Du.Info,t,r)}warn(t,r){this._log(Du.Warning,t,r)}debug(t,r){this._log(Du.Debug,t,r)}error(t,r){this._log(Du.Error,t,r)}};k_=Pj([St()],k_);let sc=class extends Error{status;statusText;responseBody;isTimeout;cause;constructor(t){super(t.message),this.name="DmkNetworkClientError",this.status=t.status,this.statusText=t.statusText,this.responseBody=t.responseBody,this.isTimeout=t.isTimeout??!1,this.cause=t.cause}};const Mj="application/json";function Dj(e,t){if(!t)return e;const r=e.endsWith("/")?e.slice(0,-1):e,n=t.startsWith("/")?t:`/${t}`;return`${r}${n}`}function Lj(e){const t=[];for(const[r,n]of Object.entries(e))n!=null&&t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return t.join("&")}function as(e){const{url:t,params:r,baseUrl:n}=e,i=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:n?Dj(n,t):t,o=r?Lj(r):"";if(o.length===0)return i;const s=i.includes("?")?"&":"?";return`${i}${s}${o}`}function Fj(e,t){const r=t.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===r)}function Nj(e){return!!(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<"u"&&e instanceof Blob||typeof FormData<"u"&&e instanceof FormData||typeof URLSearchParams<"u"&&e instanceof URLSearchParams||typeof ReadableStream<"u"&&e instanceof ReadableStream)}function jj(e){const{method:t,body:r,defaultHeaders:n,perRequestHeaders:i}=e,o={...n,...i};return r===void 0||t==="GET"||t==="HEAD"?{body:void 0,headers:o}:Nj(r)?{body:r,headers:o}:(Fj(o,"content-type")||(o["Content-Type"]=Mj),{body:JSON.stringify(r),headers:o})}function zj(e){const{timeoutMs:t}=e;if(!t||t<=0)return{signal:void 0,cleanup:()=>{}};const r=new AbortController,n=setTimeout(()=>{r.abort()},t);return{signal:r.signal,cleanup:()=>clearTimeout(n)}}async function Bj(e,t){switch(t){case"void":return;case"text":return await e.text();case"blob":return await e.blob();case"arrayBuffer":return await e.arrayBuffer();default:{const r=await e.text();if(r.length===0)return;try{return JSON.parse(r)}catch(n){throw new sc({message:"Failed to parse JSON response body",status:e.status,statusText:e.statusText,responseBody:r,cause:n})}}}}async function Vj(e){try{return await e.text()}catch{return}}function Hj(e){const{cause:t,timeoutMs:r}=e,n=!!(r&&r>0);if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")){const i=t.name==="TimeoutError"||n;return new sc({message:i?"Request timed out":"Request aborted",isTimeout:i,cause:t})}return new sc({message:t instanceof Error?t.message:"Network request failed",cause:t})}let b2=class{baseUrl;defaultHeaders;fetchImpl;constructor(t={}){this.baseUrl=t.baseUrl,this.defaultHeaders=t.headers??{},this.fetchImpl=t.fetch}getFetch(){return this.fetchImpl??globalThis.fetch.bind(globalThis)}get(t,r){return this.request({...r,method:"GET",url:t}).then(n=>n.data)}post(t,r,n){return this.request({...n,method:"POST",url:t,body:r}).then(i=>i.data)}put(t,r,n){return this.request({...n,method:"PUT",url:t,body:r}).then(i=>i.data)}patch(t,r,n){return this.request({...n,method:"PATCH",url:t,body:r}).then(i=>i.data)}delete(t,r){return this.request({...r,method:"DELETE",url:t}).then(n=>n.data)}head(t,r){return this.request({...r,method:"HEAD",url:t,responseType:"void"}).then(()=>{})}async request(t){const r=as({url:t.url,params:t.params,baseUrl:this.baseUrl}),{body:n,headers:i}=jj({method:t.method,body:t.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:t.headers}),{signal:o,cleanup:s}=zj({timeoutMs:t.timeoutMs}),u=t.throwOnHttpError??!0,c=t.responseType??"json";try{let f;try{f=await this.getFetch()(r,{method:t.method,headers:i,body:n,signal:o})}catch(p){throw Hj({cause:p,timeoutMs:t.timeoutMs})}if(!f.ok&&u){const p=await Vj(f);throw new sc({message:`HTTP error ${f.status} ${f.statusText}`.trim(),status:f.status,statusText:f.statusText,responseBody:p})}return{data:await Bj(f,c),status:f.status,statusText:f.statusText,headers:f.headers,ok:f.ok}}finally{s()}}};var Lu=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(Lu||{});const Uj=1,Wj="0";let fp=class{constructor(t){this.error=t,this.originalError=t}_tag="FetchError";originalError};var Fu=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(Fu||{}),Gj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},P_=(e,t)=>(r,n)=>t(r,n,e);const qo=e=>e instanceof sc&&e.cause!==void 0?new fp(e.cause):new fp(e);let M_=class{http;_provider=Uj;_firmwareDistributionSalt=Wj;_logger;constructor({managerApiUrl:t,provider:r,firmwareDistributionSalt:n},i){this.http=new b2({baseUrl:t}),this._provider=r,this._firmwareDistributionSalt=n,this._logger=i("HttpManagerApiDataSource")}setProvider(t){this._provider===t||t<1||(this._provider=t)}getProvider(){return this._provider}setFirmwareDistributionSalt(t){this._firmwareDistributionSalt===t||t.trim()===""||(this._firmwareDistributionSalt=t)}getFirmwareDistributionSalt(){return this._firmwareDistributionSalt}getAppList(t){const{targetId:r,firmwareVersionName:n}=t;return dt(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:n}})).chain(i=>this.mapApplicationDtoToApplication(i)).mapLeft(qo)}getMcuList(){return dt(()=>this.http.get("/mcu_versions")).chain(t=>this.mapMcuDtoToMcu(t)).mapLeft(qo)}getDeviceVersion(t){const{targetId:r}=t;return dt(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(n=>this.mapDeviceVersionDto(n)).mapLeft(qo)}getFirmwareVersion(t){const{deviceId:r,version:n}=t;return dt(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(i=>this.mapFinalFirmwareDto(i)).mapLeft(qo)}getFirmwareVersionById(t){return dt(()=>this.http.get(`/firmware_final_versions/${t}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(qo)}getOsuFirmwareVersion(t){const{deviceId:r,version:n}=t;return dt(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(i=>this.mapOsuFirmwareDto(i)).mapLeft(qo)}getLatestFirmwareVersion(t){const{currentFinalFirmwareId:r,deviceId:n}=t;return dt(()=>{const i=this._firmwareDistributionSalt;return this._logger.info("Requesting latest firmware",{data:{salt:i}}),this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:r,device_version:n,provider:this._provider,salt:i}})}).chain(i=>this.mapLatestFirmwareDto(i)).mapLeft(qo)}getAppsByHash(t){const{hashes:r}=t;return dt(()=>this.http.post("/v2/apps/hash",r)).chain(n=>this.mapNullableApplicationDtoToApplication(n)).mapLeft(qo)}getLanguagePackages(t){const{deviceId:r,currentFinalFirmwareId:n}=t;return dt(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:n}})).chain(i=>this.mapLanguagesDtoToLanguages(i)).mapLeft(qo)}mapAppTypeDtoToAppType(t){if(t===null)return null;switch(t){case Fu.currency:return Lu.currency;case Fu.plugin:return Lu.plugin;case Fu.tool:return Lu.tool;case Fu.swap:return Lu.swap}}mapApplicationDtoToApplication(t){return dt(()=>Promise.resolve(t.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(t){return dt(()=>Promise.resolve(t.map(r=>r===null?null:this.mapApplicationDto(r))))}mapApplicationDto(t){if(typeof t!="object"||typeof t.versionId!="number"||typeof t.versionName!="string"||t.versionDisplayName!==null&&typeof t.versionDisplayName!="string"||typeof t.version!="string"||t.currencyId!==null&&typeof t.currencyId!="string"||t.description!==null&&typeof t.description!="string"||t.applicationType!==null&&typeof t.applicationType!="string"||typeof t.dateModified!="string"||t.icon!==null&&typeof t.icon!="string"||t.authorName!==null&&typeof t.authorName!="string"||t.supportURL!==null&&typeof t.supportURL!="string"||t.contactURL!==null&&typeof t.contactURL!="string"||t.sourceURL!==null&&typeof t.sourceURL!="string"||t.compatibleWallets!==null&&typeof t.compatibleWallets!="string"||typeof t.hash!="string"||typeof t.perso!="string"||typeof t.firmware!="string"||typeof t.firmwareKey!="string"||typeof t.delete!="string"||typeof t.deleteKey!="string"||t.bytes!==null&&typeof t.bytes!="number"||t.warning!==null&&typeof t.warning!="string"||typeof t.isDevTools!="boolean"||t.category!==null&&typeof t.category!="number"||t.parent!==null&&typeof t.parent!="number"||t.parentName!==null&&typeof t.parentName!="string")throw new Error(`Incomplete application: ${JSON.stringify(t)}`);const{applicationType:r,hash:n,perso:i,firmware:o,firmwareKey:s,delete:u,deleteKey:c,...f}=t;return{...f,hash:n,perso:i,firmware:o,firmwareKey:s,delete:u,deleteKey:c,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(t){return dt(()=>Promise.resolve(t.map(r=>{if(typeof r!="object"||typeof r.id!="number"||typeof r.name!="string"||typeof r.from_bootloader_version!="string")throw new Error(`Incomplete MCU version: ${JSON.stringify(r)}`);return{id:r.id,name:r.name,fromBootloaderVersion:r.from_bootloader_version,providers:r.providers}})))}mapDeviceVersionDto(t){return dt(()=>{if(typeof t!="object"||typeof t.id!="number")throw new Error(`Incomplete device version: ${JSON.stringify(t)}`);const r={id:t.id};return Promise.resolve(r)})}mapFinalFirmwareDto(t){return dt(()=>{if(typeof t!="object"||typeof t.id!="number"||typeof t.version!="string"||typeof t.perso!="string"||t.firmware!==null&&typeof t.firmware!="string"||t.firmware_key!==null&&typeof t.firmware_key!="string"||t.hash!==null&&typeof t.hash!="string"||t.bytes!==null&&typeof t.bytes!="number"||!Array.isArray(t.mcu_versions))throw new Error(`Incomplete final firmware: ${JSON.stringify(t)}`);const r={id:t.id,version:t.version,perso:t.perso,firmware:t.firmware,firmwareKey:t.firmware_key,hash:t.hash,bytes:t.bytes,mcuVersions:t.mcu_versions};return Promise.resolve(r)})}mapLatestFirmwareDto(t){return dt(()=>{if(t.result==="null")return Promise.resolve(null);if(t.result!=="success"||!t.se_firmware_osu_version)throw new Error(`Latest firmware could not be retrieved: ${t.result}`);const r=t.se_firmware_osu_version;return Promise.resolve(r)}).chain(r=>r===null?dt(()=>Promise.resolve(Dt)):this.mapOsuFirmwareDto(r).map(n=>Lr(n)))}mapOsuFirmwareDto(t){return dt(()=>{if(typeof t!="object"||typeof t.id!="number"||t.notes!==null&&typeof t.notes!="string"||typeof t.perso!="string"||typeof t.firmware!="string"||typeof t.firmware_key!="string"||t.hash!==null&&typeof t.hash!="string"||typeof t.next_se_firmware_final_version!="number")throw new Error(`Incomplete latest firmware: ${JSON.stringify(t)}`);const r={id:t.id,notes:t.notes,perso:t.perso,firmware:t.firmware,firmwareKey:t.firmware_key,hash:t.hash,nextFinalFirmware:t.next_se_firmware_final_version};return Promise.resolve(r)})}mapLanguagesDtoToLanguages(t){return dt(()=>Promise.resolve(t.map(r=>this.mapLanguageDto(r))))}mapLanguageDto(t){if(typeof t!="object"||typeof t.language!="string"||typeof t.languagePackageVersionId!="number"||typeof t.version!="string"||typeof t.language_package_id!="number"||typeof t.apdu_install_url!="string"||typeof t.apdu_uninstall_url!="string"||typeof t.bytes!="number"||typeof t.date_creation!="string"||typeof t.date_last_modified!="string")throw new Error(`Incomplete language version: ${JSON.stringify(t)}`);return{language:t.language,languagePackageVersionId:t.languagePackageVersionId,version:t.version,languagePackageId:t.language_package_id,apduInstallUrl:t.apdu_install_url,apduUninstallUrl:t.apdu_uninstall_url,bytes:t.bytes,dateCreation:t.date_creation,dateLastModified:t.date_last_modified}}};M_=Gj([St(),P_(0,Xe(Ac.DmkConfig)),P_(1,Xe(dr.LoggerPublisherServiceFactory))],M_);var qj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Xj=(e,t)=>(r,n)=>t(r,n,e);let D_=class{constructor(t){this.dataSource=t}getAppList(t){const r={targetId:t.targetId.toString(),firmwareVersionName:t.seVersion};return this.dataSource.getAppList(r)}getDeviceVersion(t){const r={targetId:t.targetId.toString()};return this.dataSource.getDeviceVersion(r)}getFirmwareVersion(t,r){const n={version:t.seVersion,deviceId:r.id};return this.dataSource.getFirmwareVersion(n)}getOsuFirmwareVersion(t,r){const n={version:t.seVersion,deviceId:r.id};return this.dataSource.getOsuFirmwareVersion(n)}getLatestFirmwareVersion(t,r){const n={currentFinalFirmwareId:t.id,deviceId:r.id};return this.dataSource.getLatestFirmwareVersion(n)}getNextFirmwareVersion(t){return this.dataSource.getFirmwareVersionById(t.nextFinalFirmware)}getLanguagePackages(t,r){const n={deviceId:t.id,currentFinalFirmwareId:r.id};return this.dataSource.getLanguagePackages(n)}getMcuList(){return this.dataSource.getMcuList()}getAppsByHash(t){const r={hashes:t};return dt(async({fromPromise:n,throwE:i})=>{if(r.hashes.length===0)return[];try{return await n(this.dataSource.getAppsByHash(r))}catch(o){return o instanceof fp?i(o):i(new fp(o))}})}getProvider(){return this.dataSource.getProvider()}};D_=qj([St(),Xj(0,Xe(Ac.ManagerApiDataSource))],D_);var Kj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},gm=(e,t)=>(r,n)=>t(r,n,e);let L_=class{constructor(t,r,n){this.sessionService=t,this.managerApiDataSource=r,this._logger=n("SetFirmwareDistributionSaltUseCase")}_logger;execute(t){if(t.trim()===""){this._logger.warn("Ignoring empty firmware distribution salt");return}const r=this.managerApiDataSource.getFirmwareDistributionSalt();if(t===r){this._logger.debug("Firmware distribution salt unchanged",{data:{salt:t}});return}this.managerApiDataSource.setFirmwareDistributionSalt(t);let n=0;for(const i of this.sessionService.getDeviceSessions()){const o=i.getDeviceSessionState();o.sessionStateType!==Ss.Connected&&o.firmwareUpdateContext!==void 0&&(i.setDeviceSessionState({...o,firmwareUpdateContext:void 0}),n++)}this._logger.info("Firmware distribution salt updated",{data:{previousSalt:r,salt:t,invalidatedSessions:n}})}};L_=Kj([St(),gm(0,Xe(en.DeviceSessionService)),gm(1,Xe(Ac.ManagerApiDataSource)),gm(2,Xe(dr.LoggerPublisherServiceFactory))],L_);var Yj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},F_=(e,t)=>(r,n)=>t(r,n,e);let N_=class{constructor(t,r){this.sessionService=t,this.managerApiDataSource=r}execute(t){for(const r of this.sessionService.getDeviceSessions()){const n=r.getDeviceSessionState();n.sessionStateType!==Ss.Connected&&r.setDeviceSessionState({...n,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(t)}};N_=Yj([St(),F_(0,Xe(en.DeviceSessionService)),F_(1,Xe(Ac.ManagerApiDataSource))],N_);var Qj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},Jj=(e,t)=>(r,n)=>t(r,n,e);let j_=class{webSocketBaseUrl;constructor({webSocketUrl:t}){this.webSocketBaseUrl=t}setWebSocketUrl(t){this.webSocketBaseUrl===t||t.length===0||(this.webSocketBaseUrl=t)}getWebSocketUrl(){return this.webSocketBaseUrl}genuineCheck(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:t});return this._connectWebSocket(r)}installApp(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}listInstalledApps(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:t});return this._connectWebSocket(r)}uninstallApp(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateFirmware(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateMcu(t){const r=as({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:t});return this._connectWebSocket(r)}_connectWebSocket(t){try{return nr(new o4(t))}catch(r){return Wt(new f4(r))}}};j_=Qj([St(),Jj(0,Xe(Bp.DmkConfig))],j_);var Zj=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},ez=(e,t)=>(r,n)=>t(r,n,e);let z_=class{constructor(t){this.dataSource=t}genuineCheck(t,r){const n={targetId:t.targetId.toString(),perso:r.perso};return this.dataSource.genuineCheck(n)}installApp(t,r){const{perso:n,firmware:i,firmwareKey:o,hash:s}=r,u={targetId:t.targetId.toString(),perso:n,firmware:i,firmwareKey:o,hash:s};return this.dataSource.installApp(u)}listInstalledApps(t,r){const n={targetId:t.targetId.toString(),perso:r.perso};return this.dataSource.listInstalledApps(n)}uninstallApp(t,r){const{perso:n,delete:i,deleteKey:o,hash:s}=r,u={targetId:t.targetId.toString(),perso:n,firmware:i,firmwareKey:o,hash:s};return this.dataSource.uninstallApp(u)}updateFirmware(t,r){const n={targetId:t.targetId.toString(),perso:r.perso,firmware:r.firmware,firmwareKey:r.firmwareKey};return this.dataSource.updateFirmware(n)}updateMcu(t,r){const n={targetId:t.targetId.toString(),version:r.version};return this.dataSource.updateMcu(n)}};z_=Zj([St(),ez(0,Xe(Bp.SecureChannelDataSource))],z_);var tz=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},rz=(e,t)=>(r,n)=>t(r,n,e);let B_=class{constructor(t){this.secureChannelDataSource=t}execute(t){this.secureChannelDataSource.setWebSocketUrl(t)}};B_=tz([St(),rz(0,Xe(Bp.SecureChannelDataSource))],B_);var nz=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},V_=(e,t)=>(r,n)=>t(r,n,e);let H_=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendApduUseCase")}async execute({sessionId:t,apdu:r,abortTimeout:n,triggersDisconnection:i}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async o=>(await o.sendApdu(r,{abortTimeout:n,triggersDisconnection:i})).caseOf({Right:s=>s,Left:s=>{throw this._logger.error("Error sending APDU",{data:{sessionId:t,apdu:r,error:s}}),s}}),Left:o=>{throw this._logger.error("Error getting deviceSession",{data:{error:o}}),o}})}};H_=nz([St(),V_(0,Xe(en.DeviceSessionService)),V_(1,Xe(dr.LoggerPublisherServiceFactory))],H_);var iz=(e,t,r,n)=>{for(var i=t,o=e.length-1,s;o>=0;o--)(s=e[o])&&(i=s(i)||i);return i},el=(e,t)=>(r,n)=>t(r,n,e);let U_=class{constructor(t,r,n,i,o,s){if(this._config=r,this._loggerModuleFactory=n,this._deviceModelDataSource=i,this._apduSenderServiceFactory=o,this._apduReceiverServiceFactory=s,this._logger=n("TransportService"),t.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new i4("No transports provided, please check your configuration");for(const u of t){const c=this.addTransport(u);if(c.isLeft())throw c.extract()}}_transports=new Map;_logger;addTransport(t){const r=t({deviceModelDataSource:this._deviceModelDataSource,loggerServiceFactory:this._loggerModuleFactory,config:this._config,apduSenderServiceFactory:this._apduSenderServiceFactory,apduReceiverServiceFactory:this._apduReceiverServiceFactory});return this.addTransportInternal(r)}addTransportInternal(t){return this.getTransport(t.getIdentifier()).isJust()?(this._logger.warn(`Transport ${t.getIdentifier()} already exists, please check your configuration`),Wt(new n4(`Transport ${t.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(t.getIdentifier(),t),nr(void 0))}getTransport(t){return _n.fromNullable(this._transports.get(t))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(t){this.getTransport(t.transport).map(r=>r.disconnect({connectedDevice:t}))}};U_=iz([St(),el(0,Xe(Na.TransportsInput)),el(1,Xe(Na.DmkConfig)),el(2,Xe(dr.LoggerPublisherServiceFactory)),el(3,Xe(rj.DeviceModelDataSource)),el(4,Xe(en.ApduSenderServiceFactory)),el(5,Xe(en.ApduReceiverServiceFactory))],U_);const oz={ADD_LOG:"addLog"};function az(e){return{startListeningCommand:()=>e.sendMessage(Jo.START_LISTENING_DEVICES,"{}"),stopListeningCommand:()=>e.sendMessage(Jo.STOP_LISTENING_DEVICES,"{}"),startDiscoveringCommand:()=>e.sendMessage(Jo.START_DISCOVERING,"{}"),stopDiscoveringCommand:()=>e.sendMessage(Jo.STOP_DISCOVERING,"{}"),connectDeviceCommand:(t,r)=>e.sendMessage(Jo.CONNECT_DEVICE,JSON.stringify({deviceId:t,sessionRefresherOptions:r}))}}function sz(e){return{getProviderCommand:()=>e.sendMessage(Jo.GET_PROVIDER,"{}"),setProviderCommand:t=>e.sendMessage(Jo.SET_PROVIDER,JSON.stringify({provider:t}))}}let lz=0;function uz(e){return{sendApduCommand:(t,r)=>{const n=`apdu-${++lz}`,i=r.match(/.{1,2}/g)?.map(o=>parseInt(o,16))||[];return e.sendMessage(Jo.SEND_APDU,JSON.stringify({sessionId:t,apdu:i,requestId:n})),n}}}function cz(e){const{timestamp:t,tag:r,verbosity:n,message:i,payloadJSON:o}=JSON.parse(e);return{timestamp:t,tag:r,verbosity:n,message:i,payloadJSON:o,payload:JSON.parse(o)}}const fz="apdu-exchange";function dz(e){const t=e.payload;return typeof t!="object"||t===null||Array.isArray(t)||t.type!==fz||typeof t.apdu!="string"||typeof t.response!="string"?null:{sessionId:typeof t.sessionId=="string"?t.sessionId:void 0,apdu:t.apdu,response:t.response,timestamp:e.timestamp}}function pz(e,t){try{const{module:r}=JSON.parse(e);t(n=>new Set([...n,r]))}catch(r){console.error("Failed to parse moduleConnected payload",r)}}function hz(e,t,r,n){const i=cz(e);if(i!==null){if(t(o=>[...o,i]),n){const o=dz(i);o!==null&&r(s=>[...s,o])}return!0}return!1}function gz(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse connectedDevicesUpdate payload",r)}}function vz(e,t){try{const{sessionId:r,state:n}=JSON.parse(e);t(i=>new Map(i).set(r,n))}catch(r){console.error("Failed to parse deviceSessionStateUpdate payload",r)}}function mz(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse discoveredDevicesUpdate payload",r)}}function yz(e,t){try{const{provider:r}=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse providerValue payload",r)}}function bz(e,t){try{const r=JSON.parse(e);t(n=>new Map(n).set(r.requestId,r))}catch(r){console.error("Failed to parse apduResponse payload",r)}}function Sz(e){const[t,r]=x.useState([]),[n,i]=x.useState([]),[o,s]=x.useState([]),[u,c]=x.useState(new Set),[f,p]=x.useState([]),[g,h]=x.useState(new Map),[m,y]=x.useState([]),[b,S]=x.useState(!1),[_,E]=x.useState(!1),[O,R]=x.useState(null),[$,T]=x.useState(new Map),[P,L]=x.useState([]),[z,B]=x.useState(!1),X=x.useRef(!1),Y=x.useMemo(()=>({...e,sendMessage:(W,ve)=>{e.sendMessage(W,ve),i(se=>[...se,{type:W,payload:ve}])}}),[e]);x.useEffect(()=>{const{unsubscribe:W}=e.listenToMessages((ve,se)=>{switch(r(Ce=>[...Ce,{type:ve,payload:se}]),ve){case sN:pz(se,c);break;case Eu.CONNECTED_DEVICES_UPDATE:gz(se,p);break;case Eu.DEVICE_SESSION_STATE_UPDATE:vz(se,h);break;case Eu.DISCOVERED_DEVICES_UPDATE:mz(se,y);break;case Eu.PROVIDER_VALUE:yz(se,R);break;case Eu.APDU_RESPONSE:bz(se,T);break;case oz.ADD_LOG:hz(se,s,L,X.current);break}});return W},[e]);const N=x.useMemo(()=>az(Y),[Y]),j=x.useMemo(()=>sz(Y),[Y]),F=x.useMemo(()=>uz(Y),[Y]),q=x.useCallback(()=>{S(!0),y([]),N.startListeningCommand()},[N]),U=x.useCallback(()=>{S(!1),y([]),N.stopListeningCommand()},[N]),M=x.useCallback(()=>{E(!0),y([]),N.startDiscoveringCommand()},[N]),G=x.useCallback(()=>{E(!1),y([]),N.stopDiscoveringCommand()},[N]),K=x.useCallback(()=>{s([])},[]),D=x.useCallback(()=>{X.current=!0,B(!0)},[]),A=x.useCallback(()=>{X.current=!1,B(!1)},[]),J=x.useCallback(()=>{L([])},[]),Z=u.has(RC.LOGGER),ne=u.has(RC.DMK_INSPECTOR);return{receivedMessages:t,sentMessages:n,logs:o,connectedModules:u,connectedDevices:f,sessionStates:g,discoveredDevices:m,isListening:b,isActivelyDiscovering:_,isLoggerConnected:Z,isInspectorConnected:ne,providerValue:O,apduResponses:$,apduExchanges:P,isRecordingExchanges:z,sendMessage:Y.sendMessage,clearLogs:K,startRecordingExchanges:D,stopRecordingExchanges:A,clearRecordedExchanges:J,startListening:q,stopListening:U,startDiscovering:M,stopDiscovering:G,connectDevice:N.connectDeviceCommand,getProvider:j.getProviderCommand,setProvider:j.setProviderCommand,sendApdu:F.sendApduCommand}}const wz=ge.div`
|
|
466
466
|
display: flex;
|
|
467
467
|
flex-direction: column;
|
|
468
468
|
align-items: center;
|
package/dist/rozenite.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@ledgerhq/device-management-kit-devtools-rozenite","version":"0.0.0-develop-
|
|
1
|
+
{"name":"@ledgerhq/device-management-kit-devtools-rozenite","version":"0.0.0-develop-20261102000856","description":"Inspect and debug your integration of the Device Management Kit","panels":[{"name":"DMK DevTools","source":"/index.html"}]}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"dependencies": {
|
|
3
3
|
"@rozenite/plugin-bridge": "1.1.0",
|
|
4
4
|
"rxjs": "7.8.2",
|
|
5
|
-
"@ledgerhq/device-management-kit-devtools-ui": "0.0.0-develop-
|
|
5
|
+
"@ledgerhq/device-management-kit-devtools-ui": "0.0.0-develop-20261102000856"
|
|
6
6
|
},
|
|
7
7
|
"description": "Inspect and debug your integration of the Device Management Kit",
|
|
8
8
|
"devDependencies": {
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"rozenite": "1.1.0",
|
|
16
16
|
"typescript": "5.9.2",
|
|
17
17
|
"vite": "7.3.7",
|
|
18
|
-
"@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-
|
|
18
|
+
"@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-20261102000856"
|
|
19
19
|
},
|
|
20
20
|
"files": [
|
|
21
21
|
"./dist"
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"peerDependencies": {
|
|
28
28
|
"react": "*",
|
|
29
29
|
"react-native": "*",
|
|
30
|
-
"@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-
|
|
30
|
+
"@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-20261102000856"
|
|
31
31
|
},
|
|
32
32
|
"private": false,
|
|
33
33
|
"repository": {
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
},
|
|
37
37
|
"type": "module",
|
|
38
38
|
"types": "./dist/react-native.d.ts",
|
|
39
|
-
"version": "0.0.0-develop-
|
|
39
|
+
"version": "0.0.0-develop-20261102000856",
|
|
40
40
|
"scripts": {
|
|
41
41
|
"build": "rozenite build",
|
|
42
42
|
"dev": "rozenite dev"
|