@ledgerhq/device-management-kit-devtools-rozenite 0.0.0-develop-20261119000843 → 0.0.0-develop-20261119133251
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
|
@@ -36,7 +36,7 @@ Details
|
|
|
36
36
|
|
|
37
37
|
${(function(a){switch(a.kind){case zi.method:return`[class: "${a.targetClass.name}", method: "${a.method.toString()}"]`;case zi.parameter:return`[class: "${a.targetClass.name}", index: "${a.index.toString()}"]`;case zi.property:return`[class: "${a.targetClass.name}", property: "${a.property.toString()}"]`}})(o)}`,{cause:n})}throw n}function OF(e,t){return(r,n,o)=>{try{o===void 0?(function(a,l){const u=um(a,l);return(d,p)=>{cl(d.constructor,qu,Gu,_S(u(d),p))}})(e,t)(r,n):typeof o=="number"?(function(a,l){const u=um(a,l);return(d,p,h)=>{if(!(function(m,y){return typeof m=="function"&&y===void 0})(d,p))throw new Vi(Dn.injectionDecoratorConflict,`Found an @inject decorator in a non constructor parameter.
|
|
38
38
|
Found @inject decorator at method "${p?.toString()??""}" at class "${d.constructor.name}"`);cl(d,qu,Gu,(function(m,y){return w=>{const E=w.constructorArguments[y];return w.constructorArguments[y]=m(E),w}})(u(d),h))}})(e,t)(r,n,o):(function(a,l){const u=um(a,l);return(d,p,h)=>{if(!(function(m){return m.set!==void 0})(h))throw new Vi(Dn.injectionDecoratorConflict,`Found an @inject decorator in a non setter property method.
|
|
39
|
-
Found @inject decorator at method "${p.toString()}" at class "${d.constructor.name}"`);cl(d.constructor,qu,Gu,_S(u(d),p))}})(e,t)(r,n,o)}catch(a){IF(r,n,o,a)}}}function um(e,t){return r=>{const n=t(r);return o=>(n(o),e(o))}}function Ie(e){return OF(LF(Cl.singleInjection,e),$F)}(function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property"})(zi||(zi={}));const $S="@inversifyjs/core/classIsInjectableFlagReflectKey",NF=[Array,BigInt,Boolean,Function,Number,Object,String];function PF(e){const t=Pv(e,"design:paramtypes");t!==void 0&&cl(e,qu,Gu,(function(r){return n=>(r.forEach(((o,a)=>{var l;n.constructorArguments[a]!==void 0||(l=o,NF.includes(l))||(n.constructorArguments[a]=(function(u){return{isFromTypescriptParamType:!0,kind:Cl.singleInjection,name:void 0,optional:!1,tags:new Map,value:u}})(o))})),n)})(t))}function Ke(e){return t=>{(function(r){if(Pv(r,$S)!==void 0)throw new Vi(Dn.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${r.name}"`);kF(r,$S,!0)})(t),PF(t)}}var AS;(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection"})(AS||(AS={}));var TS;(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"})(TS||(TS={}));let DF=class{constructor(t,r,n,o,a){this.deviceModel=t,this.serviceUuid=r,this.writeUuid=n,this.writeCmdUuid=o,this.notifyUuid=a}},Cs=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 jF=Object.defineProperty,MF=(e,t,r)=>t in e?jF(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,zF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},FF=(e,t,r)=>MF(e,t+"",r);let Oo=class{getAllDeviceModels(){return Object.values(Oo.deviceModelByIds)}getDeviceModel(t){return Oo.deviceModelByIds[t.id]}filterDeviceModels(t){return this.getAllDeviceModels().filter(r=>Object.entries(t).every(([n,o])=>r[n]===o))}getBluetoothServicesInfos(){return Object.values(Oo.deviceModelByIds).reduce((t,r)=>{const{bluetoothSpec:n}=r;return n?{...t,...n.reduce((o,a)=>({...o,[a.serviceUuid]:new DF(r,a.serviceUuid,a.writeUuid,a.writeCmdUuid,a.notifyUuid)}),{})}:t},{})}getBluetoothServices(){return Object.values(Oo.deviceModelByIds).map(t=>(t.bluetoothSpec||[]).map(r=>r.serviceUuid)).flat().filter(t=>!!t)}};FF(Oo,"deviceModelByIds",{[wt.NANO_S]:new Cs({id:wt.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:320*1024,getBlockSize:e=>pS.lt(pS.coerce(e.firmwareVersion)??"","2.0.0")?4*1024:2*1024,masks:[823132160]}),[wt.NANO_SP]:new Cs({id:wt.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1533*1024,getBlockSize:()=>512,masks:[856686592]}),[wt.NANO_X]:new Cs({id:wt.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"}]}),[wt.STAX]:new Cs({id:wt.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"}]}),[wt.FLEX]:new Cs({id:wt.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"}]}),[wt.APEX]:new Cs({id:wt.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"}]})}),Oo=zF([Ke()],Oo);let BF=class{statusCode;data;constructor({statusCode:t,data:r}){this.statusCode=t,this.data=r}};const UF=5,Ao=1,Eg=2,Ls=2,Cg=2,ir=[];for(let e=0;e<256;++e)ir.push((e+256).toString(16).slice(1));function VF(e,t=0){return(ir[e[t+0]]+ir[e[t+1]]+ir[e[t+2]]+ir[e[t+3]]+"-"+ir[e[t+4]]+ir[e[t+5]]+"-"+ir[e[t+6]]+ir[e[t+7]]+"-"+ir[e[t+8]]+ir[e[t+9]]+"-"+ir[e[t+10]]+ir[e[t+11]]+ir[e[t+12]]+ir[e[t+13]]+ir[e[t+14]]+ir[e[t+15]]).toLowerCase()}let dm;const WF=new Uint8Array(16);function HF(){if(!dm){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");dm=crypto.getRandomValues.bind(crypto)}return dm(WF)}const qF=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),LS={randomUUID:qF};function Yd(e,t,r){if(LS.randomUUID&&!e)return LS.randomUUID();e=e||{};const n=e.random||(e.rng||HF)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,VF(n)}const No={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)}},IS=2,fm=800;let OS=class{_tag="FramerOverflowError";originalError;constructor(){this.originalError=new Error("Frame header length is greater than frame size")}},GF=class{_tag="FramerApduError";originalError;constructor(){this.originalError=new Error("Frame offset is greater than apdu length")}},NS=class{_tag="ReceiverApduError";originalError;constructor(t){this.originalError=new Error(t??"Unable to parse apdu")}},PS=class{_tag="DeviceSessionNotFound";originalError;constructor(t){this.originalError=t??new Error("Device session not found")}},l_=class{_header;_data;constructor({header:t,data:r}){this._header=t,this._data=r}toString(){return JSON.stringify({header:this._header.toString(),data:si(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}},c_=class{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:t,dataSize:r,index:n,headTag:o,length:a,channel:l}){this._uuid=t,this._dataLength=r,this._index=n,this._headTag=o,this._length=a,this._channel=l}getDataLength(){return this._dataLength.map(t=>No.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 Ot={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var XF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},YF=(e,t)=>(r,n)=>t(r,n,e);let DS=class{_channel;_logger;_pendingFrames;constructor({channel:t=Ar.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 ft;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"),ft;const n=No.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),o=No.getFirstBytesFrom(n,n.length-IS),a=No.getLastBytesFrom(n,IS);return this._pendingFrames=[],or(new BF({data:o,statusCode:a}))})}getFrameFromBytes(t){const r=this._channel.caseOf({Just:()=>Eg,Nothing:()=>0}),n=t.slice(r,r+Ao),o=t.slice(r+Ao,r+Ao+Ls),a=o.reduce((y,w)=>y+w,0)===0;if(!a&&this._pendingFrames.length===0)return yt(new NS);const l=r+Ao+Ls,u=a?Cg:0;if(t.length<r+Ao+Ls+u)return yt(new NS("Unable to parse header from apdu"));const d=a?or(t.slice(l,l+u)):ft,p=l+u,h=t.slice(p),m=new l_({header:new c_({uuid:Yd(),channel:this._channel,dataSize:d,headTag:n,index:o,length:r+Ao+Ls+u}),data:h});return Tt(m)}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))}};DS=XF([Ke(),YF(1,Ie(Ot.LoggerPublisherServiceFactory))],DS);var KF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},QF=(e,t)=>(r,n)=>t(r,n,e);let jS=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:t,channel:r=Ar.zero(),padding:n=!1},o){this._frameSize=t,this._channel=r,this._padding=n,this._logger=o("DefaultApduSenderService")}getFrames(t){const r=[];let n=0,o=this.getFrameAtIndex(t,n);for(;o.isRight();)r.push(o.extract()),n+=1,o=this.getFrameAtIndex(t,n).mapLeft(a=>(a instanceof OS||this._logger.error("Error while parsing frame",{data:{error:a}}),a));return r}getFrameAtIndex(t,r){const n=this.getFrameHeaderFrom(r,t.length),o=r===0?0:r*this._frameSize-this.getHeaderSizeSumFrom(r);if(o>=t.length)return yt(new OS);if(n.getLength()>this._frameSize)return yt(new GF);const a=this._frameSize-n.getLength(),l=t.slice(o,o+this._frameSize-n.getLength()),u=this._padding?new Uint8Array(a).fill(0):new Uint8Array(l.length<a?l.length:a);u.set(l,0);const d=new l_({header:n,data:u});return Tt(d)}getFrameHeaderFrom(t,r){const n=new c_({uuid:Yd(),channel:this._channel.map(o=>No.getLastBytesFrom(o,Eg)),headTag:new Uint8Array([UF]),index:No.numberToByteArray(t,Ls),length:this.getFrameHeaderSizeFromIndex(t),dataSize:Ar.zero()});return t===0&&n.setDataSize(Ar.of(No.numberToByteArray(r,Cg))),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:()=>Eg,Nothing:()=>0})+Ls+Ao+(t===0?Cg:0)}};jS=KF([Ke(),QF(1,Ie(Ot.LoggerPublisherServiceFactory))],jS);const kg={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService")},ar={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService")},MS={ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase")},jl={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig")},Kd={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")},Gi={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var JF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},zS=(e,t)=>(r,n)=>t(r,n,e);let FS=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 o=>await o.sendCommand(r,n),Left:o=>{throw this._logger.error("Error getting session",{data:{error:o}}),o}})}};FS=JF([Ke(),zS(0,Ie(ar.DeviceSessionService)),zS(1,Ie(Ot.LoggerPublisherServiceFactory))],FS);var ZF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let BS=class{execute=vi.fn(()=>"stub")};BS=ZF([Ke()],BS);var eB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},US=(e,t)=>(r,n)=>t(r,n,e);let VS=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}})}};VS=eB([Ke(),US(0,Ie(ar.DeviceSessionService)),US(1,Ie(Ot.LoggerPublisherServiceFactory))],VS);function tB(e){return typeof e=="object"&&e!==null&&"version"in e&&"name"in e&&typeof e.version=="string"&&typeof e.name=="string"}let WS=class{constructor(t){this.err=t,this.originalError=t}_tag="ApiCallError";originalError},rB=class{constructor(t){this.err=t,this.originalError=t}_tag="ParseResponseError";originalError},u_=class{constructor(t){this.err=t,this.originalError=t}_tag="JSONParseError";originalError},nB=class{constructor(t){this.err=t,this.originalError=t}_tag="ReadFileError";originalError};const iB="@ledgerhq/device-management-kit",oB="0.0.0-develop-20261119000843",HS={name:iB,version:oB};var sB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};const aB={name:HS.name,version:HS.version},lB=()=>JSON.stringify(aB);let qS=class{getConfig(){return Tr.encase(()=>lB()).mapLeft(t=>new nB(t)).chain(t=>Tr.encase(()=>{const r=JSON.parse(t);if(tB(r))return r;throw new Error("Invalid config file")}).mapLeft(r=>new u_(r)))}};qS=sB([Ke()],qS);var cB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let GS=class{getConfig(){return Tr.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};GS=cB([Ke()],GS);var uB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let XS=class{async getConfig(){const t=await this._callApi();if(t.isLeft())return yt(new WS(t.extract()));if(!t.extract().ok)return yt(new WS(new Error("response not ok")));const r=await t.extract().json();return r.isLeft()?yt(new u_):r.chain(n=>this._parseResponse(n)).map(n=>n)}_parseResponse(t){const{name:r,version:n}=t;return!r||!n?yt(new rB):Tr.of({name:r,version:n})}_callApi(){return new Promise(t=>{t(Tr.of({ok:!0,json:async()=>new Promise(r=>{r(Tr.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};XS=uB([Ke()],XS);var dB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let YS=class{async getConfig(){return new Promise(t=>t(Tr.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};YS=dB([Ke()],YS);var fB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},pm=(e,t)=>(r,n)=>t(r,n,e);let KS=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())}};KS=fB([Ke(),pm(0,Ie(kg.LocalConfigDataSource)),pm(1,Ie(kg.RemoteConfigDataSource)),pm(2,Ie(Ot.LoggerPublisherServiceFactory))],KS);var pB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},hB=(e,t)=>(r,n)=>t(r,n,e);let QS=class{_configService;constructor(t){this._configService=t}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};QS=pB([Ke(),hB(0,Ie(kg.ConfigService))],QS);const mB={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var gB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},JS=(e,t)=>(r,n)=>t(r,n,e);let ZS=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)})}};ZS=gB([Ke(),JS(0,Ie(ar.DeviceSessionService)),JS(1,Ie(Ot.LoggerPublisherServiceFactory))],ZS);var vB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},yB=(e,t)=>(r,n)=>t(r,n,e);let e1=class{_sessions;_sessionsSubject;_sessionListSubject;_logger;constructor(t){this._sessions=[],this._sessionsSubject=new UR,this._sessionListSubject=new BR([]),this._logger=t("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}get sessionListObs(){return this._sessionListSubject.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._sessionListSubject.next([...this._sessions]),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._sessionListSubject.next([...this._sessions]),this._logger.info("DeviceSession removed",{data:{sessionId:t}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:t}}),this)}getDeviceSessionById(t){return Ar.fromNullable(this._sessions.find(r=>r.id===t)).toEither(new PS)}getDeviceSessionsByDeviceId(t){return Ar.fromPredicate(({length:r})=>r>0,this._sessions.filter(r=>r.connectedDevice.id===t)).toEither(new PS)}getDeviceSessions(){return this._sessions}};e1=vB([Ke(),yB(0,Ie(Ot.LoggerPublisherServiceFactory))],e1);var bB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},t1=(e,t)=>(r,n)=>t(r,n,e);let r1=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)}};r1=bB([Ke(),t1(0,Ie(ar.DeviceSessionService)),t1(1,Ie(Gi.TransportService))],r1);var xB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},n1=(e,t)=>(r,n)=>t(r,n,e);let i1=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})}};i1=xB([Ke(),n1(0,Ie(ar.DeviceSessionService)),n1(1,Ie(Ot.LoggerPublisherServiceFactory))],i1);var wB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},o1=(e,t)=>(r,n)=>t(r,n,e);let s1=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)}})}};s1=wB([Ke(),o1(0,Ie(ar.DeviceSessionService)),o1(1,Ie(Ot.LoggerPublisherServiceFactory))],s1);function SB(e){return`[will send APDU] ~...> ${si(e,!1)}`}function EB(e){return`[exchange] <= ${si(e.data,!1)}${si(e.statusCode,!1)}`}const CB="apdu-exchange";function kB(e,t,r){const n=si(t,!1),o=`${si(r.data,!1)}${si(r.statusCode,!1)}`;return{message:EB(r),data:{type:CB,sessionId:e,apdu:n,response:o}}}const Rg=1e3,hm=1e3,RB={isRefresherDisabled:!1,pollingInterval:1e3};var Pt=(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))(Pt||{});let _B=class{_eventEmitter=new oa;listen(){return this._eventEmitter.asObservable()}dispatch(t){this._eventEmitter.next(t)}},$B=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 oa,n={intent:t,subject:r,isCancelled:!1};this._queue.push(n);const o=()=>{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(lF(()=>{this._logger.debug("Intent observable finalized",{data:{type:t.type}})})),cancel:o}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:Pt.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:Pt.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()}},AB=class{constructor(t,r){this._refresher=r,this._logger=t("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(t){const r=`${t}-${Yd()}`;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()}},TB=class{constructor(t,r,n,o){this.connectedDevice=r,this._sessionEventDispatcher=n,this._sendCommandFunction=o,this._logger=t("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async a=>await this.mapEventAction(a))}_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===Pt.REFRESH_NEEDED?await this.ping():null;async mapDevicePingAction(t){if(t===wt.NANO_S){const r=async()=>{const a=await this._sendCommandFunction(new ww,fm);return this._sendCommandFunction(new fz,fm),a},n=new Promise(a=>{setTimeout(()=>a(null),Rg*2+100)}),o=await Promise.race([r(),n]);return o?this._sessionEventDispatcher.dispatch({eventName:Pt.COMMAND_SUCCEEDED,eventData:o}):this._sessionEventDispatcher.dispatch({eventName:Pt.DEVICE_STATE_UPDATE_LOCKED}),o}else{const r=await this._sendCommandFunction(new ww,fm);return this._sessionEventDispatcher.dispatch({eventName:Pt.COMMAND_SUCCEEDED,eventData:r}),r}}unsubscribe(){this._subscription.unsubscribe()}},LB=class{constructor(t,r,n,o){this._sessionEventDispatcher=n,this._refresherOptions=r,this._logger=t("device-session-refresher"),this._connectedDeviceID=o.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(SS(n=>n.eventName===Pt.DEVICE_STATE_UPDATE_BUSY||n.eventName===Pt.NEW_STATE),ai(n=>n.eventName===Pt.DEVICE_STATE_UPDATE_BUSY),uF(!1),sF());this._refresherSubscription=nF(0,t).pipe(dF(r),ES(([n,o])=>{o&&this._logger.debug("Refresh skipped: device is busy")}),SS(([n,o])=>!o),ES(()=>this._sessionEventDispatcher.dispatch({eventName:Pt.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===wt.NANO_S){const o=Rg*2;return n!==void 0&&n<o?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${o}`),o):n??o}else return n!==void 0&&n<hm?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${hm}`),hm):n??Rg}},IB=class{constructor(t,r,n,o,a){this._sessionEventDispatcher=r,this._connectedDevice=n,this._deviceState=o,this.setDeviceSessionState=a,this._subscription=this._sessionEventDispatcher.listen().subscribe(l=>this.mapEventAction(l)),this._logger=t("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=Ln.BUSY;_updateDeviceState(t){const r=this._parseDeviceStatus(t);if(r){const{sessionStateType:n,deviceStatus:o,currentApp:a}=r,l=this._deviceState.getValue();l.sessionStateType===Ys.Connected?this.setDeviceSessionState({sessionStateType:n,deviceStatus:o,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:a,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...l,sessionStateType:n,deviceStatus:o,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:a})}}mapEventAction=t=>{const{eventName:r}=t;switch(r){case Pt.COMMAND_SUCCEEDED:return this._updateDeviceState(t.eventData);case Pt.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Ln.BUSY});case Pt.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=Ln.LOCKED;return;case Pt.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=Ln.CONNECTED;return;case Pt.NEW_STATE:{const n=this._pendingDeviceStatus;return this._pendingDeviceStatus=Ln.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:n})}case Pt.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Ln.BUSY});case Pt.REFRESH_NEEDED:return;default:{const n=r;throw new Error(`Unhandled context type ${n}`)}}};_parseDeviceStatus(t){return I5(t)?{sessionStateType:Ys.ReadyWithoutSecureChannel,deviceStatus:Ln.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()}};class OB{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new _B;_bypassIntentQueue=!1;constructor({connectedDevice:t,id:r=Yd()},n,o,a,l,u=d=>new $B(n,d)){this._id=r,this._connectedDevice=t,this._loggerModuleFactory=n,this._logger=n("device-session"),this._managerApiService=o,this._intentQueueService=u(this._sessionEventDispatcher),this._secureChannelService=a,this._refresherOptions={...RB,...l},this._deviceState=new BR({sessionStateType:Ys.Connected,deviceStatus:Ln.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new TB(n,t,this._sessionEventDispatcher,(d,p)=>this.sendCommand(d,p)),this._deviceSessionRefresher=new LB(n,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new IB(n,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,d=>this.setDeviceSessionState(d)),this._refresherService=new AB(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,o=Date.now(),{observable:a,cancel:l}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>Xs((async()=>{const d=Date.now()-o;return await this._unsafeInternalSendApdu(t,{isPolling:r.isPolling,triggersDisconnection:r.triggersDisconnection,abortTimeout:n?n-d:void 0})})())}),u=n?a.pipe(xS({each:n,with:()=>{throw l(),new hF}})):a;return bS(u)}async _unsafeInternalSendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(SB(t)),(await this._connectedDevice.sendApdu(t,r.triggersDisconnection,r.abortTimeout)).ifRight(n=>{const{message:o,data:a}=kB(this._id,t,n);this._logger.debug(o,{data:a}),vv.isLockedDeviceResponse(n)?this._sessionEventDispatcher.dispatch({eventName:Pt.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:Pt.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:Pt.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:o,cancel:a}=this._intentQueueService.enqueue({type:"send-command",execute:()=>Xs((async()=>{const u=Date.now()-n;return await this._unsafeInternalSendCommand(t,r?r-u:void 0)})())}),l=r?o.pipe(xS({each:r,with:()=>{throw a(),new mF}})):o;return bS(l)}async _unsafeInternalSendCommand(t,r){const n=t.getApdu();return(await this._unsafeInternalSendApdu(n.getRawApdu(),{isPolling:!1,triggersDisconnection:t.triggersDisconnection??!1,abortTimeout:r})).caseOf({Left:o=>{throw this._logger.error("[sendCommand] error",{data:{err:o}}),o},Right:o=>{const a=t.parseResponse(o,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:a}}),a}})}executeDeviceAction(t){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(t):this._internalExecuteDeviceAction(t)}_internalExecuteDeviceAction(t){let r;const{observable:n,cancel:o}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{const{observable:a,cancel:l}=this._unsafeInternalExecuteDeviceAction(t);return r=l,a}});return{observable:n,cancel:()=>{r?.(),o()}}}_unsafeInternalExecuteDeviceAction(t){const{observable:r,cancel:n}=t._execute({sendApdu:async o=>this._unsafeInternalSendApdu(o),sendCommand:async o=>this._unsafeInternalSendCommand(o),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:o=>(this.setDeviceSessionState(o),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:r,cancel:n}}close(){this._updateDeviceStatus(Ln.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 NB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},Za=(e,t)=>(r,n)=>t(r,n,e);let a1=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(t,r,n,o,a){this._sessionService=r,this._transportService=t,this._loggerFactory=n,this._logger=n("ConnectUseCase"),this._managerApi=o,this._secureChannel=a}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),o="sessionId"in t?t.sessionId:void 0;return He.liftEither(n.toEither(new Nv(new Error("Unknown transport")))).chain(async a=>a.connect({deviceId:t.id,onDisconnect:l=>this.handleDeviceDisconnect(l)})).ifLeft(a=>{this._logger.error("Error connecting to device")}).map(async a=>{const l=new OB({connectedDevice:a,id:o},this._loggerFactory,this._managerApi,this._secureChannel,r);return this._sessionService.addDeviceSession(l),await l.initialiseSession(),l.id}).caseOf({Left:a=>{throw a},Right:a=>a})}};a1=NB([Ke(),Za(0,Ie(Gi.TransportService)),Za(1,Ie(ar.DeviceSessionService)),Za(2,Ie(Ot.LoggerPublisherServiceFactory)),Za(3,Ie(jl.ManagerApiService)),Za(4,Ie(Kd.SecureChannelService))],a1);var PB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},mm=(e,t)=>(r,n)=>t(r,n,e);let l1=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)}}),He(async({liftEither:r})=>{const n=await r(this._sessionService.getDeviceSessionById(t).ifLeft(l=>{this._logger.error("Device session not found",{data:{sessionId:t,error:l}})})),o=n.connectedDevice.transport,a=await r(this._transportService.getTransport(o).toEither(new Nv(new Error("Unknown transport"))));n.close(),this._sessionService.removeDeviceSession(t),await a.disconnect({connectedDevice:n.connectedDevice})}).caseOf({Left:r=>{throw this._logger.error("Error disconnecting from device",{data:{error:r}}),r},Right:()=>{}})}};l1=PB([Ke(),mm(0,Ie(Gi.TransportService)),mm(1,Ie(ar.DeviceSessionService)),mm(2,Ie(Ot.LoggerPublisherServiceFactory))],l1);let Qd=class{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:t,deviceModel:{id:r,productName:n},type:o,transport:a,name:l},sessionId:u}){this.id=t,this.sessionId=u,this.modelId=r,this.name=l??n,this.type=o,this.transport=a}};var DB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},c1=(e,t)=>(r,n)=>t(r,n,e);let u1=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 Qd({sessionId:r.id,transportConnectedDevice:r.connectedDevice}),Left:r=>{throw this._logger.error("Error getting session",{data:{error:r}}),r}})}};u1=DB([Ke(),c1(0,Ie(ar.DeviceSessionService)),c1(1,Ie(Ot.LoggerPublisherServiceFactory))],u1);var jB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},d1=(e,t)=>(r,n)=>t(r,n,e);let f1=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 Qd({transportConnectedDevice:t.connectedDevice,sessionId:t.id}))}};f1=jB([Ke(),d1(0,Ie(ar.DeviceSessionService)),d1(1,Ie(Ot.LoggerPublisherServiceFactory))],f1);var MB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},p1=(e,t)=>(r,n)=>t(r,n,e);let h1=class{_transports;_transportService;_logger;constructor(t,r){this._transports=t.getAllTransports(),this._transportService=t,this._logger=r("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(t){const r=new TR({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"),Xs([[]]);if(!t){this._logger.info("Discovering all available transports");const r=this._transports.map((n,o)=>n.listenToAvailableDevices().pipe(ai(a=>({index:o,arr:a}))));return iF(...r).pipe(cF((n,{index:o,arr:a})=>(n[o]=a,n),{}),ai(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`),i_([])),Just:r=>r.listenToAvailableDevices().pipe(ai(n=>n.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};h1=MB([Ke(),p1(0,Ie(Gi.TransportService)),p1(1,Ie(Ot.LoggerPublisherServiceFactory))],h1);var zB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},m1=(e,t)=>(r,n)=>t(r,n,e);let g1=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDevicesUseCase")}_logger;execute(){return this._logger.info("Observe the list of connected devices"),this._sessionService.sessionListObs.pipe(ai(t=>t.map(r=>new Qd({transportConnectedDevice:r.connectedDevice,sessionId:r.id}))))}};g1=zB([Ke(),m1(0,Ie(ar.DeviceSessionService)),m1(1,Ie(Ot.LoggerPublisherServiceFactory))],g1);var FB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},v1=(e,t)=>(r,n)=>t(r,n,e);let y1=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(ai(t=>new Qd({transportConnectedDevice:t.connectedDevice,sessionId:t.id})))}};y1=FB([Ke(),v1(0,Ie(ar.DeviceSessionService)),v1(1,Ie(Ot.LoggerPublisherServiceFactory))],y1);var BB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},gm=(e,t)=>(r,n)=>t(r,n,e);let b1=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})}};b1=BB([Ke(),gm(0,Ie(MS.ConnectUseCase)),gm(1,Ie(MS.DisconnectUseCase)),gm(2,Ie(Ot.LoggerPublisherServiceFactory))],b1);var UB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},VB=(e,t)=>(r,n)=>t(r,n,e);let x1=class{constructor(t){this._transportService=t}mapDiscoveredDevice(t){const r=new TR({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 i_(...r).pipe(Iv(n=>n.startDiscovering().pipe(ai(o=>this.mapDiscoveredDevice(o)))))}return this._transportService.getTransport(t).caseOf({Just:r=>r.startDiscovering().pipe(ai(n=>this.mapDiscoveredDevice(n))),Nothing:()=>{throw new Nv(new Error("Unknown transport"))}})}};x1=UB([Ke(),VB(0,Ie(Gi.TransportService))],x1);var WB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},w1=(e,t)=>(r,n)=>t(r,n,e);let S1=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()}};S1=WB([Ke(),w1(0,Ie(Gi.TransportService)),w1(1,Ie(Ot.LoggerPublisherServiceFactory))],S1);var nl=(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))(nl||{});let HB=class{format(t){return Array.isArray(t)?t.map(r=>`[${r}]`).join(" "):`[${t}]`}};function _g(e,t){if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return t.has(e)?"[Circular]":(t.add(e),e.map(r=>_g(r,t)));if(e!==null&&typeof e=="object"){if(t.has(e))return"[Circular]";t.add(e);const r={};for(const[n,o]of Object.entries(e))r[n]=_g(o,t);return r}return e}function qB(e){const t=new WeakSet;t.add(e);const r={};for(const[n,o]of Object.entries(e))r[n]=_g(o,t);return r}var GB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let E1=class{subscribers;tag;tagFormatter;constructor(t,r,n=new HB){this.subscribers=t,this.tag=r,this.tagFormatter=n}_log(t,r,n){const o=n?.data?qB(n.data):void 0,a=n?.tag??this.tag,l=this.tagFormatter.format(a);this.subscribers.forEach(u=>{const d={timestamp:n?.timestamp??Date.now(),tag:l,data:o};u.log(t,r,d)})}info(t,r){this._log(nl.Info,t,r)}warn(t,r){this._log(nl.Warning,t,r)}debug(t,r){this._log(nl.Debug,t,r)}error(t,r){this._log(nl.Error,t,r)}};E1=GB([Ke()],E1);let kl=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 XB="application/json";function YB(e,t){if(!t)return e;const r=e.endsWith("/")?e.slice(0,-1):e,n=t.startsWith("/")?t:`/${t}`;return`${r}${n}`}function KB(e){const t=[];for(const[r,n]of Object.entries(e))n!=null&&t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return t.join("&")}function To(e){const{url:t,params:r,baseUrl:n}=e,o=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:n?YB(n,t):t,a=r?KB(r):"";if(a.length===0)return o;const l=o.includes("?")?"&":"?";return`${o}${l}${a}`}function QB(e,t){const r=t.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===r)}function JB(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 ZB(e){const{method:t,body:r,defaultHeaders:n,perRequestHeaders:o}=e,a={...n,...o};return r===void 0||t==="GET"||t==="HEAD"?{body:void 0,headers:a}:JB(r)?{body:r,headers:a}:(QB(a,"content-type")||(a["Content-Type"]=XB),{body:JSON.stringify(r),headers:a})}function e8(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 t8(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 kl({message:"Failed to parse JSON response body",status:e.status,statusText:e.statusText,responseBody:r,cause:n})}}}}async function r8(e){try{return await e.text()}catch{return}}function n8(e){const{cause:t,timeoutMs:r}=e,n=!!(r&&r>0);if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")){const o=t.name==="TimeoutError"||n;return new kl({message:o?"Request timed out":"Request aborted",isTimeout:o,cause:t})}return new kl({message:t instanceof Error?t.message:"Network request failed",cause:t})}let d_=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(o=>o.data)}put(t,r,n){return this.request({...n,method:"PUT",url:t,body:r}).then(o=>o.data)}patch(t,r,n){return this.request({...n,method:"PATCH",url:t,body:r}).then(o=>o.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=To({url:t.url,params:t.params,baseUrl:this.baseUrl}),{body:n,headers:o}=ZB({method:t.method,body:t.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:t.headers}),{signal:a,cleanup:l}=e8({timeoutMs:t.timeoutMs}),u=t.throwOnHttpError??!0,d=t.responseType??"json";try{let p;try{p=await this.getFetch()(r,{method:t.method,headers:o,body:n,signal:a})}catch(h){throw n8({cause:h,timeoutMs:t.timeoutMs})}if(!p.ok&&u){const h=await r8(p);throw new kl({message:`HTTP error ${p.status} ${p.statusText}`.trim(),status:p.status,statusText:p.statusText,responseBody:h})}return{data:await t8(p,d),status:p.status,statusText:p.statusText,headers:p.headers,ok:p.ok}}finally{l()}}};var il=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(il||{});const i8=1,o8="0";let xd=class{constructor(t){this.error=t,this.originalError=t}_tag="FetchError";originalError};var ol=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(ol||{}),s8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},C1=(e,t)=>(r,n)=>t(r,n,e);const Qn=e=>e instanceof kl&&e.cause!==void 0?new xd(e.cause):new xd(e);let k1=class{http;_provider=i8;_firmwareDistributionSalt=o8;_logger;constructor({managerApiUrl:t,provider:r,firmwareDistributionSalt:n},o){this.http=new d_({baseUrl:t}),this._provider=r,this._firmwareDistributionSalt=n,this._logger=o("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 He(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:n}})).chain(o=>this.mapApplicationDtoToApplication(o)).mapLeft(Qn)}getMcuList(){return He(()=>this.http.get("/mcu_versions")).chain(t=>this.mapMcuDtoToMcu(t)).mapLeft(Qn)}getDeviceVersion(t){const{targetId:r}=t;return He(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(n=>this.mapDeviceVersionDto(n)).mapLeft(Qn)}getFirmwareVersion(t){const{deviceId:r,version:n}=t;return He(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(o=>this.mapFinalFirmwareDto(o)).mapLeft(Qn)}getFirmwareVersionById(t){return He(()=>this.http.get(`/firmware_final_versions/${t}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(Qn)}getOsuFirmwareVersion(t){const{deviceId:r,version:n}=t;return He(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(o=>this.mapOsuFirmwareDto(o)).mapLeft(Qn)}getLatestFirmwareVersion(t){const{currentFinalFirmwareId:r,deviceId:n}=t;return He(()=>{const o=this._firmwareDistributionSalt;return this._logger.info("Requesting latest firmware",{data:{salt:o}}),this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:r,device_version:n,provider:this._provider,salt:o}})}).chain(o=>this.mapLatestFirmwareDto(o)).mapLeft(Qn)}getAppsByHash(t){const{hashes:r}=t;return He(()=>this.http.post("/v2/apps/hash",r)).chain(n=>this.mapNullableApplicationDtoToApplication(n)).mapLeft(Qn)}getLanguagePackages(t){const{deviceId:r,currentFinalFirmwareId:n}=t;return He(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:n}})).chain(o=>this.mapLanguagesDtoToLanguages(o)).mapLeft(Qn)}mapAppTypeDtoToAppType(t){if(t===null)return null;switch(t){case ol.currency:return il.currency;case ol.plugin:return il.plugin;case ol.tool:return il.tool;case ol.swap:return il.swap}}mapApplicationDtoToApplication(t){return He(()=>Promise.resolve(t.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(t){return He(()=>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:o,firmware:a,firmwareKey:l,delete:u,deleteKey:d,...p}=t;return{...p,hash:n,perso:o,firmware:a,firmwareKey:l,delete:u,deleteKey:d,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(t){return He(()=>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 He(()=>{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 He(()=>{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 He(()=>{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?He(()=>Promise.resolve(ft)):this.mapOsuFirmwareDto(r).map(n=>or(n)))}mapOsuFirmwareDto(t){return He(()=>{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 He(()=>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}}};k1=s8([Ke(),C1(0,Ie(jl.DmkConfig)),C1(1,Ie(Ot.LoggerPublisherServiceFactory))],k1);var a8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},l8=(e,t)=>(r,n)=>t(r,n,e);let R1=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 He(async({fromPromise:n,throwE:o})=>{if(r.hashes.length===0)return[];try{return await n(this.dataSource.getAppsByHash(r))}catch(a){return a instanceof xd?o(a):o(new xd(a))}})}getProvider(){return this.dataSource.getProvider()}};R1=a8([Ke(),l8(0,Ie(jl.ManagerApiDataSource))],R1);var c8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},vm=(e,t)=>(r,n)=>t(r,n,e);let _1=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 o of this.sessionService.getDeviceSessions()){const a=o.getDeviceSessionState();a.sessionStateType!==Ys.Connected&&a.firmwareUpdateContext!==void 0&&(o.setDeviceSessionState({...a,firmwareUpdateContext:void 0}),n++)}this._logger.info("Firmware distribution salt updated",{data:{previousSalt:r,salt:t,invalidatedSessions:n}})}};_1=c8([Ke(),vm(0,Ie(ar.DeviceSessionService)),vm(1,Ie(jl.ManagerApiDataSource)),vm(2,Ie(Ot.LoggerPublisherServiceFactory))],_1);var u8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},$1=(e,t)=>(r,n)=>t(r,n,e);let A1=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!==Ys.Connected&&r.setDeviceSessionState({...n,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(t)}};A1=u8([Ke(),$1(0,Ie(ar.DeviceSessionService)),$1(1,Ie(jl.ManagerApiDataSource))],A1);var d8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},f8=(e,t)=>(r,n)=>t(r,n,e);let T1=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=To({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:t});return this._connectWebSocket(r)}installApp(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}listInstalledApps(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:t});return this._connectWebSocket(r)}uninstallApp(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateFirmware(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateMcu(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:t});return this._connectWebSocket(r)}_connectWebSocket(t){try{return Tt(new yF(t))}catch(r){return yt(new CF(r))}}};T1=d8([Ke(),f8(0,Ie(Kd.DmkConfig))],T1);var p8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},h8=(e,t)=>(r,n)=>t(r,n,e);let L1=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:o,firmwareKey:a,hash:l}=r,u={targetId:t.targetId.toString(),perso:n,firmware:o,firmwareKey:a,hash:l};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:o,deleteKey:a,hash:l}=r,u={targetId:t.targetId.toString(),perso:n,firmware:o,firmwareKey:a,hash:l};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)}};L1=p8([Ke(),h8(0,Ie(Kd.SecureChannelDataSource))],L1);var m8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},g8=(e,t)=>(r,n)=>t(r,n,e);let I1=class{constructor(t){this.secureChannelDataSource=t}execute(t){this.secureChannelDataSource.setWebSocketUrl(t)}};I1=m8([Ke(),g8(0,Ie(Kd.SecureChannelDataSource))],I1);var v8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},O1=(e,t)=>(r,n)=>t(r,n,e);let N1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendApduUseCase")}async execute({sessionId:t,apdu:r,abortTimeout:n,triggersDisconnection:o}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async a=>(await a.sendApdu(r,{abortTimeout:n,triggersDisconnection:o})).caseOf({Right:l=>l,Left:l=>{throw this._logger.error("Error sending APDU",{data:{sessionId:t,apdu:r,error:l}}),l}}),Left:a=>{throw this._logger.error("Error getting deviceSession",{data:{error:a}}),a}})}};N1=v8([Ke(),O1(0,Ie(ar.DeviceSessionService)),O1(1,Ie(Ot.LoggerPublisherServiceFactory))],N1);var y8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},ks=(e,t)=>(r,n)=>t(r,n,e);let P1=class{constructor(t,r,n,o,a,l){if(this._config=r,this._loggerModuleFactory=n,this._deviceModelDataSource=o,this._apduSenderServiceFactory=a,this._apduReceiverServiceFactory=l,this._logger=n("TransportService"),t.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new vF("No transports provided, please check your configuration");for(const u of t){const d=this.addTransport(u);if(d.isLeft())throw d.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`),yt(new gF(`Transport ${t.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(t.getIdentifier(),t),Tt(void 0))}getTransport(t){return Ar.fromNullable(this._transports.get(t))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(t){this.getTransport(t.transport).map(r=>r.disconnect({connectedDevice:t}))}};P1=y8([Ke(),ks(0,Ie(Gi.TransportsInput)),ks(1,Ie(Gi.DmkConfig)),ks(2,Ie(Ot.LoggerPublisherServiceFactory)),ks(3,Ie(mB.DeviceModelDataSource)),ks(4,Ie(ar.ApduSenderServiceFactory)),ks(5,Ie(ar.ApduReceiverServiceFactory))],P1);const b8={ADD_LOG:"addLog"};function x8(e){return{startListeningCommand:()=>e.sendMessage(Fi.START_LISTENING_DEVICES,"{}"),stopListeningCommand:()=>e.sendMessage(Fi.STOP_LISTENING_DEVICES,"{}"),startDiscoveringCommand:()=>e.sendMessage(Fi.START_DISCOVERING,"{}"),stopDiscoveringCommand:()=>e.sendMessage(Fi.STOP_DISCOVERING,"{}"),connectDeviceCommand:(t,r)=>e.sendMessage(Fi.CONNECT_DEVICE,JSON.stringify({deviceId:t,sessionRefresherOptions:r}))}}function w8(e){return{getProviderCommand:()=>e.sendMessage(Fi.GET_PROVIDER,"{}"),setProviderCommand:t=>e.sendMessage(Fi.SET_PROVIDER,JSON.stringify({provider:t}))}}let S8=0;function E8(e){return{sendApduCommand:(t,r)=>{const n=`apdu-${++S8}`,o=r.match(/.{1,2}/g)?.map(a=>parseInt(a,16))||[];return e.sendMessage(Fi.SEND_APDU,JSON.stringify({sessionId:t,apdu:o,requestId:n})),n}}}const C8=e=>{try{const t=JSON.parse(e);return typeof t=="string"||t!==null&&typeof t=="object"?t:t===null?{}:JSON.stringify(t)}catch{return e}},k8=new Set(["debug","info","warning","error","fatal"]),R8=e=>{if(e===null||typeof e!="object")return!1;const{timestamp:t,tag:r,verbosity:n,message:o,payloadJSON:a}=e;return typeof t=="string"&&typeof r=="string"&&typeof o=="string"&&typeof n=="string"&&k8.has(n)&&(a===void 0||typeof a=="string")};function _8(e){let t;try{t=JSON.parse(e)}catch{return null}if(!R8(t))return null;const r=t.payloadJSON??"{}";return{timestamp:t.timestamp,tag:t.tag,verbosity:t.verbosity,message:t.message,payloadJSON:r,payload:C8(r)}}function $8(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 A8(e,t){const r=_8(e);return r!==null?(t(r),!0):!1}function T8(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse connectedDevicesUpdate payload",r)}}function L8(e,t){try{const{sessionId:r,state:n}=JSON.parse(e);t(o=>new Map(o).set(r,n))}catch(r){console.error("Failed to parse deviceSessionStateUpdate payload",r)}}function I8(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse discoveredDevicesUpdate payload",r)}}function O8(e,t){try{const{provider:r}=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse providerValue payload",r)}}const N8=e=>{try{const{protocol:t,host:r}=new URL(e);return(t==="http:"||t==="https:")&&r!==""}catch{return!1}};function P8(e){try{const t=JSON.parse(e);if(t===null)return null;if(typeof t!="object")return;const{url:r,sessionToken:n}=t;return typeof r!="string"||!N8(r)||n!==void 0&&typeof n!="string"?void 0:n===void 0?{url:r}:{url:r,sessionToken:n}}catch{return}}function D8(e,t){const r=P8(e);if(r===void 0){console.error("Ignored an invalid mockServerConfig payload");return}t(r)}function j8(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)}}const M8=250;function z8(e){const[t,r]=x.useState([]),[n,o]=x.useState(new Set),[a,l]=x.useState([]),[u,d]=x.useState(new Map),[p,h]=x.useState([]),[m,y]=x.useState(!1),[w,E]=x.useState(!1),[S,C]=x.useState(null),[R,k]=x.useState(new Map),[$,A]=x.useState(null),D=x.useRef([]);x.useEffect(()=>{let H;const O=()=>{H=void 0;const U=D.current;D.current=[],U.length>0&&r(z=>[...z,...U].slice(-2e4))},{unsubscribe:L}=e.listenToMessages((U,z)=>{switch(H??=setTimeout(O,M8),U){case S5:$8(z,o);break;case Es.CONNECTED_DEVICES_UPDATE:T8(z,l);break;case Es.DEVICE_SESSION_STATE_UPDATE:L8(z,d);break;case Es.DISCOVERED_DEVICES_UPDATE:I8(z,h);break;case Es.PROVIDER_VALUE:O8(z,C);break;case Es.APDU_RESPONSE:j8(z,k);break;case Es.MOCK_SERVER_CONFIG:D8(z,A);break;case b8.ADD_LOG:A8(z,T=>D.current.push(T));break}});return()=>{L(),clearTimeout(H),D.current=[]}},[e]);const N=x.useMemo(()=>x8(e),[e]),P=x.useMemo(()=>w8(e),[e]),I=x.useMemo(()=>E8(e),[e]),re=x.useCallback(()=>{y(!0),h([]),N.startListeningCommand()},[N]),Z=x.useCallback(()=>{y(!1),h([]),N.stopListeningCommand()},[N]),ee=x.useCallback(()=>{E(!0),h([]),N.startDiscoveringCommand()},[N]),ne=x.useCallback(()=>{E(!1),h([]),N.stopDiscoveringCommand()},[N]),X=x.useCallback(()=>{D.current=[],r([])},[]),F=n.has(mw.LOGGER),V=n.has(mw.DMK_INSPECTOR);return{logs:t,connectedModules:n,connectedDevices:a,sessionStates:u,discoveredDevices:p,isListening:m,isActivelyDiscovering:w,isLoggerConnected:F,isInspectorConnected:V,providerValue:S,apduResponses:R,mockServer:$,sendMessage:e.sendMessage,clearLogs:X,startListening:re,stopListening:Z,startDiscovering:ee,stopDiscovering:ne,connectDevice:N.connectDeviceCommand,getProvider:P.getProviderCommand,setProvider:P.setProviderCommand,sendApdu:I.sendApduCommand}}const $g=e=>`devtools-panel-width-${e}`,F8=e=>{try{const t=Number(localStorage.getItem($g(e)));return t>0?t:null}catch{return null}},ym=(e,t)=>{try{t===null?localStorage.removeItem($g(e)):localStorage.setItem($g(e),String(t))}catch{}},Dv=({name:e,defaultWidth:t,minWidth:r,maxWidth:n,edge:o,className:a="",children:l})=>{const[u,d]=x.useState(()=>F8(e)??t),p=y=>{y.preventDefault();const w=y.clientX,E=u;let S=E;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const C=k=>{const $=k.clientX-w;S=Math.min(n,Math.max(r,E+(o==="right"?$:-$))),d(S)},R=()=>{document.body.style.cursor="",document.body.style.userSelect="",ym(e,S),window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",R)};window.addEventListener("mousemove",C),window.addEventListener("mouseup",R)},h=y=>{const w=y.key==="ArrowRight"?16:y.key==="ArrowLeft"?-16:0;if(w===0)return;y.preventDefault();const E=Math.min(n,Math.max(r,u+(o==="right"?w:-w)));d(E),ym(e,E)},m=()=>{d(t),ym(e,null)};return v.jsxs("div",{className:`relative flex flex-col ${a}`,style:{flex:`0 1 ${u}px`,minWidth:r},children:[l,v.jsx("span",{role:"separator","aria-orientation":"vertical","aria-label":"Resize the panel","aria-valuenow":u,"aria-valuemin":r,"aria-valuemax":n,tabIndex:0,title:"Drag or use the arrow keys to resize, double-click to reset",onMouseDown:p,onKeyDown:h,onDoubleClick:m,className:`absolute inset-y-0 z-10 w-6 cursor-col-resize border-transparent hover:border-active focus-visible:border-active focus-visible:outline-none ${o==="right"?"-right-3 border-r-2":"-left-3 border-l-2"}`})]})},f_="relative w-320 min-w-160 shrink",Ml="flex h-32 items-center gap-6 overflow-hidden rounded-sm border border-muted-subtle bg-surface px-8 transition-colors hover:border-muted focus-within:border-active",zl="min-w-0 flex-1 bg-transparent font-mono! body-3 text-base outline-none placeholder:text-muted",Lo="flex size-24 shrink-0 cursor-pointer items-center justify-center rounded-xs text-muted transition-colors hover:bg-base-transparent-hover hover:text-base disabled:cursor-default disabled:text-disabled disabled:hover:bg-transparent",p_=/Mac|iPhone|iPad/.test(navigator.userAgent)?"⌘":"Ctrl+",h_="rounded-xs border border-muted px-4 font-mono! body-4 text-muted",B8="body-4-semi-bold text-muted uppercase",U8=e=>{const t=[{title:null,blocks:[]}],r=e.split(`
|
|
39
|
+
Found @inject decorator at method "${p.toString()}" at class "${d.constructor.name}"`);cl(d.constructor,qu,Gu,_S(u(d),p))}})(e,t)(r,n,o)}catch(a){IF(r,n,o,a)}}}function um(e,t){return r=>{const n=t(r);return o=>(n(o),e(o))}}function Ie(e){return OF(LF(Cl.singleInjection,e),$F)}(function(e){e[e.method=0]="method",e[e.parameter=1]="parameter",e[e.property=2]="property"})(zi||(zi={}));const $S="@inversifyjs/core/classIsInjectableFlagReflectKey",NF=[Array,BigInt,Boolean,Function,Number,Object,String];function PF(e){const t=Pv(e,"design:paramtypes");t!==void 0&&cl(e,qu,Gu,(function(r){return n=>(r.forEach(((o,a)=>{var l;n.constructorArguments[a]!==void 0||(l=o,NF.includes(l))||(n.constructorArguments[a]=(function(u){return{isFromTypescriptParamType:!0,kind:Cl.singleInjection,name:void 0,optional:!1,tags:new Map,value:u}})(o))})),n)})(t))}function Ke(e){return t=>{(function(r){if(Pv(r,$S)!==void 0)throw new Vi(Dn.injectionDecoratorConflict,`Cannot apply @injectable decorator multiple times at class "${r.name}"`);kF(r,$S,!0)})(t),PF(t)}}var AS;(function(e){e[e.multipleInjection=0]="multipleInjection",e[e.singleInjection=1]="singleInjection"})(AS||(AS={}));var TS;(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"})(TS||(TS={}));let DF=class{constructor(t,r,n,o,a){this.deviceModel=t,this.serviceUuid=r,this.writeUuid=n,this.writeCmdUuid=o,this.notifyUuid=a}},Cs=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 jF=Object.defineProperty,MF=(e,t,r)=>t in e?jF(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,zF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},FF=(e,t,r)=>MF(e,t+"",r);let Oo=class{getAllDeviceModels(){return Object.values(Oo.deviceModelByIds)}getDeviceModel(t){return Oo.deviceModelByIds[t.id]}filterDeviceModels(t){return this.getAllDeviceModels().filter(r=>Object.entries(t).every(([n,o])=>r[n]===o))}getBluetoothServicesInfos(){return Object.values(Oo.deviceModelByIds).reduce((t,r)=>{const{bluetoothSpec:n}=r;return n?{...t,...n.reduce((o,a)=>({...o,[a.serviceUuid]:new DF(r,a.serviceUuid,a.writeUuid,a.writeCmdUuid,a.notifyUuid)}),{})}:t},{})}getBluetoothServices(){return Object.values(Oo.deviceModelByIds).map(t=>(t.bluetoothSpec||[]).map(r=>r.serviceUuid)).flat().filter(t=>!!t)}};FF(Oo,"deviceModelByIds",{[wt.NANO_S]:new Cs({id:wt.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:320*1024,getBlockSize:e=>pS.lt(pS.coerce(e.firmwareVersion)??"","2.0.0")?4*1024:2*1024,masks:[823132160]}),[wt.NANO_SP]:new Cs({id:wt.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1533*1024,getBlockSize:()=>512,masks:[856686592]}),[wt.NANO_X]:new Cs({id:wt.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"}]}),[wt.STAX]:new Cs({id:wt.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"}]}),[wt.FLEX]:new Cs({id:wt.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"}]}),[wt.APEX]:new Cs({id:wt.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"}]})}),Oo=zF([Ke()],Oo);let BF=class{statusCode;data;constructor({statusCode:t,data:r}){this.statusCode=t,this.data=r}};const UF=5,Ao=1,Eg=2,Ls=2,Cg=2,ir=[];for(let e=0;e<256;++e)ir.push((e+256).toString(16).slice(1));function VF(e,t=0){return(ir[e[t+0]]+ir[e[t+1]]+ir[e[t+2]]+ir[e[t+3]]+"-"+ir[e[t+4]]+ir[e[t+5]]+"-"+ir[e[t+6]]+ir[e[t+7]]+"-"+ir[e[t+8]]+ir[e[t+9]]+"-"+ir[e[t+10]]+ir[e[t+11]]+ir[e[t+12]]+ir[e[t+13]]+ir[e[t+14]]+ir[e[t+15]]).toLowerCase()}let dm;const WF=new Uint8Array(16);function HF(){if(!dm){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");dm=crypto.getRandomValues.bind(crypto)}return dm(WF)}const qF=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),LS={randomUUID:qF};function Yd(e,t,r){if(LS.randomUUID&&!e)return LS.randomUUID();e=e||{};const n=e.random||(e.rng||HF)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,VF(n)}const No={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)}},IS=2,fm=800;let OS=class{_tag="FramerOverflowError";originalError;constructor(){this.originalError=new Error("Frame header length is greater than frame size")}},GF=class{_tag="FramerApduError";originalError;constructor(){this.originalError=new Error("Frame offset is greater than apdu length")}},NS=class{_tag="ReceiverApduError";originalError;constructor(t){this.originalError=new Error(t??"Unable to parse apdu")}},PS=class{_tag="DeviceSessionNotFound";originalError;constructor(t){this.originalError=t??new Error("Device session not found")}},l_=class{_header;_data;constructor({header:t,data:r}){this._header=t,this._data=r}toString(){return JSON.stringify({header:this._header.toString(),data:si(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}},c_=class{_uuid;_channel;_headTag;_index;_length;_dataLength;constructor({uuid:t,dataSize:r,index:n,headTag:o,length:a,channel:l}){this._uuid=t,this._dataLength=r,this._index=n,this._headTag=o,this._length=a,this._channel=l}getDataLength(){return this._dataLength.map(t=>No.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 Ot={LoggerPublisherServiceFactory:Symbol.for("LoggerPublisherServiceFactory")};var XF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},YF=(e,t)=>(r,n)=>t(r,n,e);let DS=class{_channel;_logger;_pendingFrames;constructor({channel:t=Ar.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 ft;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"),ft;const n=No.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),o=No.getFirstBytesFrom(n,n.length-IS),a=No.getLastBytesFrom(n,IS);return this._pendingFrames=[],or(new BF({data:o,statusCode:a}))})}getFrameFromBytes(t){const r=this._channel.caseOf({Just:()=>Eg,Nothing:()=>0}),n=t.slice(r,r+Ao),o=t.slice(r+Ao,r+Ao+Ls),a=o.reduce((y,w)=>y+w,0)===0;if(!a&&this._pendingFrames.length===0)return yt(new NS);const l=r+Ao+Ls,u=a?Cg:0;if(t.length<r+Ao+Ls+u)return yt(new NS("Unable to parse header from apdu"));const d=a?or(t.slice(l,l+u)):ft,p=l+u,h=t.slice(p),m=new l_({header:new c_({uuid:Yd(),channel:this._channel,dataSize:d,headTag:n,index:o,length:r+Ao+Ls+u}),data:h});return Tt(m)}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))}};DS=XF([Ke(),YF(1,Ie(Ot.LoggerPublisherServiceFactory))],DS);var KF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},QF=(e,t)=>(r,n)=>t(r,n,e);let jS=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:t,channel:r=Ar.zero(),padding:n=!1},o){this._frameSize=t,this._channel=r,this._padding=n,this._logger=o("DefaultApduSenderService")}getFrames(t){const r=[];let n=0,o=this.getFrameAtIndex(t,n);for(;o.isRight();)r.push(o.extract()),n+=1,o=this.getFrameAtIndex(t,n).mapLeft(a=>(a instanceof OS||this._logger.error("Error while parsing frame",{data:{error:a}}),a));return r}getFrameAtIndex(t,r){const n=this.getFrameHeaderFrom(r,t.length),o=r===0?0:r*this._frameSize-this.getHeaderSizeSumFrom(r);if(o>=t.length)return yt(new OS);if(n.getLength()>this._frameSize)return yt(new GF);const a=this._frameSize-n.getLength(),l=t.slice(o,o+this._frameSize-n.getLength()),u=this._padding?new Uint8Array(a).fill(0):new Uint8Array(l.length<a?l.length:a);u.set(l,0);const d=new l_({header:n,data:u});return Tt(d)}getFrameHeaderFrom(t,r){const n=new c_({uuid:Yd(),channel:this._channel.map(o=>No.getLastBytesFrom(o,Eg)),headTag:new Uint8Array([UF]),index:No.numberToByteArray(t,Ls),length:this.getFrameHeaderSizeFromIndex(t),dataSize:Ar.zero()});return t===0&&n.setDataSize(Ar.of(No.numberToByteArray(r,Cg))),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:()=>Eg,Nothing:()=>0})+Ls+Ao+(t===0?Cg:0)}};jS=KF([Ke(),QF(1,Ie(Ot.LoggerPublisherServiceFactory))],jS);const kg={LocalConfigDataSource:Symbol.for("LocalConfigDataSource"),RemoteConfigDataSource:Symbol.for("RemoteConfigDataSource"),ConfigService:Symbol.for("ConfigService")},ar={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService")},MS={ConnectUseCase:Symbol.for("ConnectUseCase"),DisconnectUseCase:Symbol.for("DisconnectUseCase")},jl={ManagerApiService:Symbol.for("ManagerApiService"),ManagerApiDataSource:Symbol.for("ManagerApiDataSource"),DmkConfig:Symbol.for("ManagerApiDmkConfig")},Kd={SecureChannelService:Symbol.for("SecureChannelService"),SecureChannelDataSource:Symbol.for("SecureChannelDataSource"),DmkConfig:Symbol.for("SecureChannelDmkConfig")},Gi={DmkConfig:Symbol.for("TransportDmkConfig"),TransportService:Symbol.for("TransportService"),TransportsInput:Symbol.for("TransportsInput")};var JF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},zS=(e,t)=>(r,n)=>t(r,n,e);let FS=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 o=>await o.sendCommand(r,n),Left:o=>{throw this._logger.error("Error getting session",{data:{error:o}}),o}})}};FS=JF([Ke(),zS(0,Ie(ar.DeviceSessionService)),zS(1,Ie(Ot.LoggerPublisherServiceFactory))],FS);var ZF=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let BS=class{execute=vi.fn(()=>"stub")};BS=ZF([Ke()],BS);var eB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},US=(e,t)=>(r,n)=>t(r,n,e);let VS=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}})}};VS=eB([Ke(),US(0,Ie(ar.DeviceSessionService)),US(1,Ie(Ot.LoggerPublisherServiceFactory))],VS);function tB(e){return typeof e=="object"&&e!==null&&"version"in e&&"name"in e&&typeof e.version=="string"&&typeof e.name=="string"}let WS=class{constructor(t){this.err=t,this.originalError=t}_tag="ApiCallError";originalError},rB=class{constructor(t){this.err=t,this.originalError=t}_tag="ParseResponseError";originalError},u_=class{constructor(t){this.err=t,this.originalError=t}_tag="JSONParseError";originalError},nB=class{constructor(t){this.err=t,this.originalError=t}_tag="ReadFileError";originalError};const iB="@ledgerhq/device-management-kit",oB="0.0.0-develop-20261119133251",HS={name:iB,version:oB};var sB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};const aB={name:HS.name,version:HS.version},lB=()=>JSON.stringify(aB);let qS=class{getConfig(){return Tr.encase(()=>lB()).mapLeft(t=>new nB(t)).chain(t=>Tr.encase(()=>{const r=JSON.parse(t);if(tB(r))return r;throw new Error("Invalid config file")}).mapLeft(r=>new u_(r)))}};qS=sB([Ke()],qS);var cB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let GS=class{getConfig(){return Tr.of({name:"DeviceSDK",version:"0.0.0-stub.1"})}};GS=cB([Ke()],GS);var uB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let XS=class{async getConfig(){const t=await this._callApi();if(t.isLeft())return yt(new WS(t.extract()));if(!t.extract().ok)return yt(new WS(new Error("response not ok")));const r=await t.extract().json();return r.isLeft()?yt(new u_):r.chain(n=>this._parseResponse(n)).map(n=>n)}_parseResponse(t){const{name:r,version:n}=t;return!r||!n?yt(new rB):Tr.of({name:r,version:n})}_callApi(){return new Promise(t=>{t(Tr.of({ok:!0,json:async()=>new Promise(r=>{r(Tr.of({name:"DeviceSDK",version:"0.0.0-fake.1",yolo:"yolo"}))})}))})}};XS=uB([Ke()],XS);var dB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let YS=class{async getConfig(){return new Promise(t=>t(Tr.of({name:"DeviceSDK",version:"0.0.0-fake.2"})))}};YS=dB([Ke()],YS);var fB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},pm=(e,t)=>(r,n)=>t(r,n,e);let KS=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())}};KS=fB([Ke(),pm(0,Ie(kg.LocalConfigDataSource)),pm(1,Ie(kg.RemoteConfigDataSource)),pm(2,Ie(Ot.LoggerPublisherServiceFactory))],KS);var pB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},hB=(e,t)=>(r,n)=>t(r,n,e);let QS=class{_configService;constructor(t){this._configService=t}async getDmkVersion(){return(await this._configService.getDmkConfig()).version}};QS=pB([Ke(),hB(0,Ie(kg.ConfigService))],QS);const mB={DeviceModelDataSource:Symbol.for("DeviceModelDataSource")};var gB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},JS=(e,t)=>(r,n)=>t(r,n,e);let ZS=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)})}};ZS=gB([Ke(),JS(0,Ie(ar.DeviceSessionService)),JS(1,Ie(Ot.LoggerPublisherServiceFactory))],ZS);var vB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},yB=(e,t)=>(r,n)=>t(r,n,e);let e1=class{_sessions;_sessionsSubject;_sessionListSubject;_logger;constructor(t){this._sessions=[],this._sessionsSubject=new UR,this._sessionListSubject=new BR([]),this._logger=t("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}get sessionListObs(){return this._sessionListSubject.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._sessionListSubject.next([...this._sessions]),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._sessionListSubject.next([...this._sessions]),this._logger.info("DeviceSession removed",{data:{sessionId:t}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:t}}),this)}getDeviceSessionById(t){return Ar.fromNullable(this._sessions.find(r=>r.id===t)).toEither(new PS)}getDeviceSessionsByDeviceId(t){return Ar.fromPredicate(({length:r})=>r>0,this._sessions.filter(r=>r.connectedDevice.id===t)).toEither(new PS)}getDeviceSessions(){return this._sessions}};e1=vB([Ke(),yB(0,Ie(Ot.LoggerPublisherServiceFactory))],e1);var bB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},t1=(e,t)=>(r,n)=>t(r,n,e);let r1=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)}};r1=bB([Ke(),t1(0,Ie(ar.DeviceSessionService)),t1(1,Ie(Gi.TransportService))],r1);var xB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},n1=(e,t)=>(r,n)=>t(r,n,e);let i1=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})}};i1=xB([Ke(),n1(0,Ie(ar.DeviceSessionService)),n1(1,Ie(Ot.LoggerPublisherServiceFactory))],i1);var wB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},o1=(e,t)=>(r,n)=>t(r,n,e);let s1=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)}})}};s1=wB([Ke(),o1(0,Ie(ar.DeviceSessionService)),o1(1,Ie(Ot.LoggerPublisherServiceFactory))],s1);function SB(e){return`[will send APDU] ~...> ${si(e,!1)}`}function EB(e){return`[exchange] <= ${si(e.data,!1)}${si(e.statusCode,!1)}`}const CB="apdu-exchange";function kB(e,t,r){const n=si(t,!1),o=`${si(r.data,!1)}${si(r.statusCode,!1)}`;return{message:EB(r),data:{type:CB,sessionId:e,apdu:n,response:o}}}const Rg=1e3,hm=1e3,RB={isRefresherDisabled:!1,pollingInterval:1e3};var Pt=(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))(Pt||{});let _B=class{_eventEmitter=new oa;listen(){return this._eventEmitter.asObservable()}dispatch(t){this._eventEmitter.next(t)}},$B=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 oa,n={intent:t,subject:r,isCancelled:!1};this._queue.push(n);const o=()=>{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(lF(()=>{this._logger.debug("Intent observable finalized",{data:{type:t.type}})})),cancel:o}}_processQueue(){if(this._isProcessing)return;if(this._queue.length===0){this.sessionEventDispatcher.dispatch({eventName:Pt.NEW_STATE});return}this.sessionEventDispatcher.dispatch({eventName:Pt.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()}},AB=class{constructor(t,r){this._refresher=r,this._logger=t("refresher-service")}_refresherBlockers=new Set;_logger;disableRefresher(t){const r=`${t}-${Yd()}`;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()}},TB=class{constructor(t,r,n,o){this.connectedDevice=r,this._sessionEventDispatcher=n,this._sendCommandFunction=o,this._logger=t("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async a=>await this.mapEventAction(a))}_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===Pt.REFRESH_NEEDED?await this.ping():null;async mapDevicePingAction(t){if(t===wt.NANO_S){const r=async()=>{const a=await this._sendCommandFunction(new ww,fm);return this._sendCommandFunction(new fz,fm),a},n=new Promise(a=>{setTimeout(()=>a(null),Rg*2+100)}),o=await Promise.race([r(),n]);return o?this._sessionEventDispatcher.dispatch({eventName:Pt.COMMAND_SUCCEEDED,eventData:o}):this._sessionEventDispatcher.dispatch({eventName:Pt.DEVICE_STATE_UPDATE_LOCKED}),o}else{const r=await this._sendCommandFunction(new ww,fm);return this._sessionEventDispatcher.dispatch({eventName:Pt.COMMAND_SUCCEEDED,eventData:r}),r}}unsubscribe(){this._subscription.unsubscribe()}},LB=class{constructor(t,r,n,o){this._sessionEventDispatcher=n,this._refresherOptions=r,this._logger=t("device-session-refresher"),this._connectedDeviceID=o.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(SS(n=>n.eventName===Pt.DEVICE_STATE_UPDATE_BUSY||n.eventName===Pt.NEW_STATE),ai(n=>n.eventName===Pt.DEVICE_STATE_UPDATE_BUSY),uF(!1),sF());this._refresherSubscription=nF(0,t).pipe(dF(r),ES(([n,o])=>{o&&this._logger.debug("Refresh skipped: device is busy")}),SS(([n,o])=>!o),ES(()=>this._sessionEventDispatcher.dispatch({eventName:Pt.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===wt.NANO_S){const o=Rg*2;return n!==void 0&&n<o?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${o}`),o):n??o}else return n!==void 0&&n<hm?(r.warn(`Polling interval of ${n} is too low, setting to minimum as ${hm}`),hm):n??Rg}},IB=class{constructor(t,r,n,o,a){this._sessionEventDispatcher=r,this._connectedDevice=n,this._deviceState=o,this.setDeviceSessionState=a,this._subscription=this._sessionEventDispatcher.listen().subscribe(l=>this.mapEventAction(l)),this._logger=t("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=Ln.BUSY;_updateDeviceState(t){const r=this._parseDeviceStatus(t);if(r){const{sessionStateType:n,deviceStatus:o,currentApp:a}=r,l=this._deviceState.getValue();l.sessionStateType===Ys.Connected?this.setDeviceSessionState({sessionStateType:n,deviceStatus:o,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:a,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...l,sessionStateType:n,deviceStatus:o,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:a})}}mapEventAction=t=>{const{eventName:r}=t;switch(r){case Pt.COMMAND_SUCCEEDED:return this._updateDeviceState(t.eventData);case Pt.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Ln.BUSY});case Pt.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=Ln.LOCKED;return;case Pt.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=Ln.CONNECTED;return;case Pt.NEW_STATE:{const n=this._pendingDeviceStatus;return this._pendingDeviceStatus=Ln.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:n})}case Pt.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:Ln.BUSY});case Pt.REFRESH_NEEDED:return;default:{const n=r;throw new Error(`Unhandled context type ${n}`)}}};_parseDeviceStatus(t){return I5(t)?{sessionStateType:Ys.ReadyWithoutSecureChannel,deviceStatus:Ln.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()}};class OB{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new _B;_bypassIntentQueue=!1;constructor({connectedDevice:t,id:r=Yd()},n,o,a,l,u=d=>new $B(n,d)){this._id=r,this._connectedDevice=t,this._loggerModuleFactory=n,this._logger=n("device-session"),this._managerApiService=o,this._intentQueueService=u(this._sessionEventDispatcher),this._secureChannelService=a,this._refresherOptions={...RB,...l},this._deviceState=new BR({sessionStateType:Ys.Connected,deviceStatus:Ln.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new TB(n,t,this._sessionEventDispatcher,(d,p)=>this.sendCommand(d,p)),this._deviceSessionRefresher=new LB(n,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new IB(n,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,d=>this.setDeviceSessionState(d)),this._refresherService=new AB(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,o=Date.now(),{observable:a,cancel:l}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>Xs((async()=>{const d=Date.now()-o;return await this._unsafeInternalSendApdu(t,{isPolling:r.isPolling,triggersDisconnection:r.triggersDisconnection,abortTimeout:n?n-d:void 0})})())}),u=n?a.pipe(xS({each:n,with:()=>{throw l(),new hF}})):a;return bS(u)}async _unsafeInternalSendApdu(t,r={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(SB(t)),(await this._connectedDevice.sendApdu(t,r.triggersDisconnection,r.abortTimeout)).ifRight(n=>{const{message:o,data:a}=kB(this._id,t,n);this._logger.debug(o,{data:a}),vv.isLockedDeviceResponse(n)?this._sessionEventDispatcher.dispatch({eventName:Pt.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:Pt.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:Pt.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:o,cancel:a}=this._intentQueueService.enqueue({type:"send-command",execute:()=>Xs((async()=>{const u=Date.now()-n;return await this._unsafeInternalSendCommand(t,r?r-u:void 0)})())}),l=r?o.pipe(xS({each:r,with:()=>{throw a(),new mF}})):o;return bS(l)}async _unsafeInternalSendCommand(t,r){const n=t.getApdu();return(await this._unsafeInternalSendApdu(n.getRawApdu(),{isPolling:!1,triggersDisconnection:t.triggersDisconnection??!1,abortTimeout:r})).caseOf({Left:o=>{throw this._logger.error("[sendCommand] error",{data:{err:o}}),o},Right:o=>{const a=t.parseResponse(o,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:a}}),a}})}executeDeviceAction(t){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(t):this._internalExecuteDeviceAction(t)}_internalExecuteDeviceAction(t){let r;const{observable:n,cancel:o}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{const{observable:a,cancel:l}=this._unsafeInternalExecuteDeviceAction(t);return r=l,a}});return{observable:n,cancel:()=>{r?.(),o()}}}_unsafeInternalExecuteDeviceAction(t){const{observable:r,cancel:n}=t._execute({sendApdu:async o=>this._unsafeInternalSendApdu(o),sendCommand:async o=>this._unsafeInternalSendCommand(o),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:o=>(this.setDeviceSessionState(o),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:r,cancel:n}}close(){this._updateDeviceStatus(Ln.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 NB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},Za=(e,t)=>(r,n)=>t(r,n,e);let a1=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(t,r,n,o,a){this._sessionService=r,this._transportService=t,this._loggerFactory=n,this._logger=n("ConnectUseCase"),this._managerApi=o,this._secureChannel=a}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),o="sessionId"in t?t.sessionId:void 0;return He.liftEither(n.toEither(new Nv(new Error("Unknown transport")))).chain(async a=>a.connect({deviceId:t.id,onDisconnect:l=>this.handleDeviceDisconnect(l)})).ifLeft(a=>{this._logger.error("Error connecting to device")}).map(async a=>{const l=new OB({connectedDevice:a,id:o},this._loggerFactory,this._managerApi,this._secureChannel,r);return this._sessionService.addDeviceSession(l),await l.initialiseSession(),l.id}).caseOf({Left:a=>{throw a},Right:a=>a})}};a1=NB([Ke(),Za(0,Ie(Gi.TransportService)),Za(1,Ie(ar.DeviceSessionService)),Za(2,Ie(Ot.LoggerPublisherServiceFactory)),Za(3,Ie(jl.ManagerApiService)),Za(4,Ie(Kd.SecureChannelService))],a1);var PB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},mm=(e,t)=>(r,n)=>t(r,n,e);let l1=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)}}),He(async({liftEither:r})=>{const n=await r(this._sessionService.getDeviceSessionById(t).ifLeft(l=>{this._logger.error("Device session not found",{data:{sessionId:t,error:l}})})),o=n.connectedDevice.transport,a=await r(this._transportService.getTransport(o).toEither(new Nv(new Error("Unknown transport"))));n.close(),this._sessionService.removeDeviceSession(t),await a.disconnect({connectedDevice:n.connectedDevice})}).caseOf({Left:r=>{throw this._logger.error("Error disconnecting from device",{data:{error:r}}),r},Right:()=>{}})}};l1=PB([Ke(),mm(0,Ie(Gi.TransportService)),mm(1,Ie(ar.DeviceSessionService)),mm(2,Ie(Ot.LoggerPublisherServiceFactory))],l1);let Qd=class{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:t,deviceModel:{id:r,productName:n},type:o,transport:a,name:l},sessionId:u}){this.id=t,this.sessionId=u,this.modelId=r,this.name=l??n,this.type=o,this.transport=a}};var DB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},c1=(e,t)=>(r,n)=>t(r,n,e);let u1=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 Qd({sessionId:r.id,transportConnectedDevice:r.connectedDevice}),Left:r=>{throw this._logger.error("Error getting session",{data:{error:r}}),r}})}};u1=DB([Ke(),c1(0,Ie(ar.DeviceSessionService)),c1(1,Ie(Ot.LoggerPublisherServiceFactory))],u1);var jB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},d1=(e,t)=>(r,n)=>t(r,n,e);let f1=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 Qd({transportConnectedDevice:t.connectedDevice,sessionId:t.id}))}};f1=jB([Ke(),d1(0,Ie(ar.DeviceSessionService)),d1(1,Ie(Ot.LoggerPublisherServiceFactory))],f1);var MB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},p1=(e,t)=>(r,n)=>t(r,n,e);let h1=class{_transports;_transportService;_logger;constructor(t,r){this._transports=t.getAllTransports(),this._transportService=t,this._logger=r("ListenToAvailableDevicesUseCase")}mapTransportDiscoveredDeviceToDiscoveredDevice(t){const r=new TR({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"),Xs([[]]);if(!t){this._logger.info("Discovering all available transports");const r=this._transports.map((n,o)=>n.listenToAvailableDevices().pipe(ai(a=>({index:o,arr:a}))));return iF(...r).pipe(cF((n,{index:o,arr:a})=>(n[o]=a,n),{}),ai(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`),i_([])),Just:r=>r.listenToAvailableDevices().pipe(ai(n=>n.map(this.mapTransportDiscoveredDeviceToDiscoveredDevice)))})}};h1=MB([Ke(),p1(0,Ie(Gi.TransportService)),p1(1,Ie(Ot.LoggerPublisherServiceFactory))],h1);var zB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},m1=(e,t)=>(r,n)=>t(r,n,e);let g1=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDevicesUseCase")}_logger;execute(){return this._logger.info("Observe the list of connected devices"),this._sessionService.sessionListObs.pipe(ai(t=>t.map(r=>new Qd({transportConnectedDevice:r.connectedDevice,sessionId:r.id}))))}};g1=zB([Ke(),m1(0,Ie(ar.DeviceSessionService)),m1(1,Ie(Ot.LoggerPublisherServiceFactory))],g1);var FB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},v1=(e,t)=>(r,n)=>t(r,n,e);let y1=class{constructor(t,r){this._sessionService=t,this._logger=r("ListenToConnectedDeviceUseCase")}_logger;execute(){return this._logger.info("Observe connected devices"),this._sessionService.sessionsObs.pipe(ai(t=>new Qd({transportConnectedDevice:t.connectedDevice,sessionId:t.id})))}};y1=FB([Ke(),v1(0,Ie(ar.DeviceSessionService)),v1(1,Ie(Ot.LoggerPublisherServiceFactory))],y1);var BB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},gm=(e,t)=>(r,n)=>t(r,n,e);let b1=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})}};b1=BB([Ke(),gm(0,Ie(MS.ConnectUseCase)),gm(1,Ie(MS.DisconnectUseCase)),gm(2,Ie(Ot.LoggerPublisherServiceFactory))],b1);var UB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},VB=(e,t)=>(r,n)=>t(r,n,e);let x1=class{constructor(t){this._transportService=t}mapDiscoveredDevice(t){const r=new TR({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 i_(...r).pipe(Iv(n=>n.startDiscovering().pipe(ai(o=>this.mapDiscoveredDevice(o)))))}return this._transportService.getTransport(t).caseOf({Just:r=>r.startDiscovering().pipe(ai(n=>this.mapDiscoveredDevice(n))),Nothing:()=>{throw new Nv(new Error("Unknown transport"))}})}};x1=UB([Ke(),VB(0,Ie(Gi.TransportService))],x1);var WB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},w1=(e,t)=>(r,n)=>t(r,n,e);let S1=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()}};S1=WB([Ke(),w1(0,Ie(Gi.TransportService)),w1(1,Ie(Ot.LoggerPublisherServiceFactory))],S1);var nl=(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))(nl||{});let HB=class{format(t){return Array.isArray(t)?t.map(r=>`[${r}]`).join(" "):`[${t}]`}};function _g(e,t){if(typeof e=="bigint")return e.toString();if(Array.isArray(e))return t.has(e)?"[Circular]":(t.add(e),e.map(r=>_g(r,t)));if(e!==null&&typeof e=="object"){if(t.has(e))return"[Circular]";t.add(e);const r={};for(const[n,o]of Object.entries(e))r[n]=_g(o,t);return r}return e}function qB(e){const t=new WeakSet;t.add(e);const r={};for(const[n,o]of Object.entries(e))r[n]=_g(o,t);return r}var GB=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o};let E1=class{subscribers;tag;tagFormatter;constructor(t,r,n=new HB){this.subscribers=t,this.tag=r,this.tagFormatter=n}_log(t,r,n){const o=n?.data?qB(n.data):void 0,a=n?.tag??this.tag,l=this.tagFormatter.format(a);this.subscribers.forEach(u=>{const d={timestamp:n?.timestamp??Date.now(),tag:l,data:o};u.log(t,r,d)})}info(t,r){this._log(nl.Info,t,r)}warn(t,r){this._log(nl.Warning,t,r)}debug(t,r){this._log(nl.Debug,t,r)}error(t,r){this._log(nl.Error,t,r)}};E1=GB([Ke()],E1);let kl=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 XB="application/json";function YB(e,t){if(!t)return e;const r=e.endsWith("/")?e.slice(0,-1):e,n=t.startsWith("/")?t:`/${t}`;return`${r}${n}`}function KB(e){const t=[];for(const[r,n]of Object.entries(e))n!=null&&t.push(`${encodeURIComponent(r)}=${encodeURIComponent(String(n))}`);return t.join("&")}function To(e){const{url:t,params:r,baseUrl:n}=e,o=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:n?YB(n,t):t,a=r?KB(r):"";if(a.length===0)return o;const l=o.includes("?")?"&":"?";return`${o}${l}${a}`}function QB(e,t){const r=t.toLowerCase();return Object.keys(e).some(n=>n.toLowerCase()===r)}function JB(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 ZB(e){const{method:t,body:r,defaultHeaders:n,perRequestHeaders:o}=e,a={...n,...o};return r===void 0||t==="GET"||t==="HEAD"?{body:void 0,headers:a}:JB(r)?{body:r,headers:a}:(QB(a,"content-type")||(a["Content-Type"]=XB),{body:JSON.stringify(r),headers:a})}function e8(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 t8(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 kl({message:"Failed to parse JSON response body",status:e.status,statusText:e.statusText,responseBody:r,cause:n})}}}}async function r8(e){try{return await e.text()}catch{return}}function n8(e){const{cause:t,timeoutMs:r}=e,n=!!(r&&r>0);if(t instanceof Error&&(t.name==="AbortError"||t.name==="TimeoutError")){const o=t.name==="TimeoutError"||n;return new kl({message:o?"Request timed out":"Request aborted",isTimeout:o,cause:t})}return new kl({message:t instanceof Error?t.message:"Network request failed",cause:t})}let d_=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(o=>o.data)}put(t,r,n){return this.request({...n,method:"PUT",url:t,body:r}).then(o=>o.data)}patch(t,r,n){return this.request({...n,method:"PATCH",url:t,body:r}).then(o=>o.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=To({url:t.url,params:t.params,baseUrl:this.baseUrl}),{body:n,headers:o}=ZB({method:t.method,body:t.body,defaultHeaders:this.defaultHeaders,perRequestHeaders:t.headers}),{signal:a,cleanup:l}=e8({timeoutMs:t.timeoutMs}),u=t.throwOnHttpError??!0,d=t.responseType??"json";try{let p;try{p=await this.getFetch()(r,{method:t.method,headers:o,body:n,signal:a})}catch(h){throw n8({cause:h,timeoutMs:t.timeoutMs})}if(!p.ok&&u){const h=await r8(p);throw new kl({message:`HTTP error ${p.status} ${p.statusText}`.trim(),status:p.status,statusText:p.statusText,responseBody:h})}return{data:await t8(p,d),status:p.status,statusText:p.statusText,headers:p.headers,ok:p.ok}}finally{l()}}};var il=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(il||{});const i8=1,o8="0";let xd=class{constructor(t){this.error=t,this.originalError=t}_tag="FetchError";originalError};var ol=(e=>(e.currency="currency",e.plugin="plugin",e.tool="tool",e.swap="swap",e))(ol||{}),s8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},C1=(e,t)=>(r,n)=>t(r,n,e);const Qn=e=>e instanceof kl&&e.cause!==void 0?new xd(e.cause):new xd(e);let k1=class{http;_provider=i8;_firmwareDistributionSalt=o8;_logger;constructor({managerApiUrl:t,provider:r,firmwareDistributionSalt:n},o){this.http=new d_({baseUrl:t}),this._provider=r,this._firmwareDistributionSalt=n,this._logger=o("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 He(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:n}})).chain(o=>this.mapApplicationDtoToApplication(o)).mapLeft(Qn)}getMcuList(){return He(()=>this.http.get("/mcu_versions")).chain(t=>this.mapMcuDtoToMcu(t)).mapLeft(Qn)}getDeviceVersion(t){const{targetId:r}=t;return He(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(n=>this.mapDeviceVersionDto(n)).mapLeft(Qn)}getFirmwareVersion(t){const{deviceId:r,version:n}=t;return He(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(o=>this.mapFinalFirmwareDto(o)).mapLeft(Qn)}getFirmwareVersionById(t){return He(()=>this.http.get(`/firmware_final_versions/${t}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(Qn)}getOsuFirmwareVersion(t){const{deviceId:r,version:n}=t;return He(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:n,provider:this._provider}})).chain(o=>this.mapOsuFirmwareDto(o)).mapLeft(Qn)}getLatestFirmwareVersion(t){const{currentFinalFirmwareId:r,deviceId:n}=t;return He(()=>{const o=this._firmwareDistributionSalt;return this._logger.info("Requesting latest firmware",{data:{salt:o}}),this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:r,device_version:n,provider:this._provider,salt:o}})}).chain(o=>this.mapLatestFirmwareDto(o)).mapLeft(Qn)}getAppsByHash(t){const{hashes:r}=t;return He(()=>this.http.post("/v2/apps/hash",r)).chain(n=>this.mapNullableApplicationDtoToApplication(n)).mapLeft(Qn)}getLanguagePackages(t){const{deviceId:r,currentFinalFirmwareId:n}=t;return He(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:n}})).chain(o=>this.mapLanguagesDtoToLanguages(o)).mapLeft(Qn)}mapAppTypeDtoToAppType(t){if(t===null)return null;switch(t){case ol.currency:return il.currency;case ol.plugin:return il.plugin;case ol.tool:return il.tool;case ol.swap:return il.swap}}mapApplicationDtoToApplication(t){return He(()=>Promise.resolve(t.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(t){return He(()=>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:o,firmware:a,firmwareKey:l,delete:u,deleteKey:d,...p}=t;return{...p,hash:n,perso:o,firmware:a,firmwareKey:l,delete:u,deleteKey:d,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(t){return He(()=>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 He(()=>{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 He(()=>{if(typeof t!="object"||typeof t.id!="number"||typeof t.name!="string"||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,name:t.name,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 He(()=>{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?He(()=>Promise.resolve(ft)):this.mapOsuFirmwareDto(r).map(n=>or(n)))}mapOsuFirmwareDto(t){return He(()=>{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 He(()=>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}}};k1=s8([Ke(),C1(0,Ie(jl.DmkConfig)),C1(1,Ie(Ot.LoggerPublisherServiceFactory))],k1);var a8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},l8=(e,t)=>(r,n)=>t(r,n,e);let R1=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 He(async({fromPromise:n,throwE:o})=>{if(r.hashes.length===0)return[];try{return await n(this.dataSource.getAppsByHash(r))}catch(a){return a instanceof xd?o(a):o(new xd(a))}})}getProvider(){return this.dataSource.getProvider()}};R1=a8([Ke(),l8(0,Ie(jl.ManagerApiDataSource))],R1);var c8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},vm=(e,t)=>(r,n)=>t(r,n,e);let _1=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 o of this.sessionService.getDeviceSessions()){const a=o.getDeviceSessionState();a.sessionStateType!==Ys.Connected&&a.firmwareUpdateContext!==void 0&&(o.setDeviceSessionState({...a,firmwareUpdateContext:void 0}),n++)}this._logger.info("Firmware distribution salt updated",{data:{previousSalt:r,salt:t,invalidatedSessions:n}})}};_1=c8([Ke(),vm(0,Ie(ar.DeviceSessionService)),vm(1,Ie(jl.ManagerApiDataSource)),vm(2,Ie(Ot.LoggerPublisherServiceFactory))],_1);var u8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},$1=(e,t)=>(r,n)=>t(r,n,e);let A1=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!==Ys.Connected&&r.setDeviceSessionState({...n,firmwareUpdateContext:void 0,installedApps:[],appsUpdates:void 0,catalog:void 0})}this.managerApiDataSource.setProvider(t)}};A1=u8([Ke(),$1(0,Ie(ar.DeviceSessionService)),$1(1,Ie(jl.ManagerApiDataSource))],A1);var d8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},f8=(e,t)=>(r,n)=>t(r,n,e);let T1=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=To({baseUrl:this.webSocketBaseUrl,url:"/genuine",params:t});return this._connectWebSocket(r)}installApp(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}listInstalledApps(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/apps/list",params:t});return this._connectWebSocket(r)}uninstallApp(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateFirmware(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/install",params:t});return this._connectWebSocket(r)}updateMcu(t){const r=To({baseUrl:this.webSocketBaseUrl,url:"/mcu",params:t});return this._connectWebSocket(r)}_connectWebSocket(t){try{return Tt(new yF(t))}catch(r){return yt(new CF(r))}}};T1=d8([Ke(),f8(0,Ie(Kd.DmkConfig))],T1);var p8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},h8=(e,t)=>(r,n)=>t(r,n,e);let L1=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:o,firmwareKey:a,hash:l}=r,u={targetId:t.targetId.toString(),perso:n,firmware:o,firmwareKey:a,hash:l};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:o,deleteKey:a,hash:l}=r,u={targetId:t.targetId.toString(),perso:n,firmware:o,firmwareKey:a,hash:l};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)}};L1=p8([Ke(),h8(0,Ie(Kd.SecureChannelDataSource))],L1);var m8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},g8=(e,t)=>(r,n)=>t(r,n,e);let I1=class{constructor(t){this.secureChannelDataSource=t}execute(t){this.secureChannelDataSource.setWebSocketUrl(t)}};I1=m8([Ke(),g8(0,Ie(Kd.SecureChannelDataSource))],I1);var v8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},O1=(e,t)=>(r,n)=>t(r,n,e);let N1=class{_sessionService;_logger;constructor(t,r){this._sessionService=t,this._logger=r("SendApduUseCase")}async execute({sessionId:t,apdu:r,abortTimeout:n,triggersDisconnection:o}){return this._sessionService.getDeviceSessionById(t).caseOf({Right:async a=>(await a.sendApdu(r,{abortTimeout:n,triggersDisconnection:o})).caseOf({Right:l=>l,Left:l=>{throw this._logger.error("Error sending APDU",{data:{sessionId:t,apdu:r,error:l}}),l}}),Left:a=>{throw this._logger.error("Error getting deviceSession",{data:{error:a}}),a}})}};N1=v8([Ke(),O1(0,Ie(ar.DeviceSessionService)),O1(1,Ie(Ot.LoggerPublisherServiceFactory))],N1);var y8=(e,t,r,n)=>{for(var o=t,a=e.length-1,l;a>=0;a--)(l=e[a])&&(o=l(o)||o);return o},ks=(e,t)=>(r,n)=>t(r,n,e);let P1=class{constructor(t,r,n,o,a,l){if(this._config=r,this._loggerModuleFactory=n,this._deviceModelDataSource=o,this._apduSenderServiceFactory=a,this._apduReceiverServiceFactory=l,this._logger=n("TransportService"),t.length===0)throw this._logger.warn("No transports provided, please check your configuration"),new vF("No transports provided, please check your configuration");for(const u of t){const d=this.addTransport(u);if(d.isLeft())throw d.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`),yt(new gF(`Transport ${t.getIdentifier()} already exists, please check your configuration`))):(this._transports.set(t.getIdentifier(),t),Tt(void 0))}getTransport(t){return Ar.fromNullable(this._transports.get(t))}getAllTransports(){return Array.from(this._transports.values())}closeConnection(t){this.getTransport(t.transport).map(r=>r.disconnect({connectedDevice:t}))}};P1=y8([Ke(),ks(0,Ie(Gi.TransportsInput)),ks(1,Ie(Gi.DmkConfig)),ks(2,Ie(Ot.LoggerPublisherServiceFactory)),ks(3,Ie(mB.DeviceModelDataSource)),ks(4,Ie(ar.ApduSenderServiceFactory)),ks(5,Ie(ar.ApduReceiverServiceFactory))],P1);const b8={ADD_LOG:"addLog"};function x8(e){return{startListeningCommand:()=>e.sendMessage(Fi.START_LISTENING_DEVICES,"{}"),stopListeningCommand:()=>e.sendMessage(Fi.STOP_LISTENING_DEVICES,"{}"),startDiscoveringCommand:()=>e.sendMessage(Fi.START_DISCOVERING,"{}"),stopDiscoveringCommand:()=>e.sendMessage(Fi.STOP_DISCOVERING,"{}"),connectDeviceCommand:(t,r)=>e.sendMessage(Fi.CONNECT_DEVICE,JSON.stringify({deviceId:t,sessionRefresherOptions:r}))}}function w8(e){return{getProviderCommand:()=>e.sendMessage(Fi.GET_PROVIDER,"{}"),setProviderCommand:t=>e.sendMessage(Fi.SET_PROVIDER,JSON.stringify({provider:t}))}}let S8=0;function E8(e){return{sendApduCommand:(t,r)=>{const n=`apdu-${++S8}`,o=r.match(/.{1,2}/g)?.map(a=>parseInt(a,16))||[];return e.sendMessage(Fi.SEND_APDU,JSON.stringify({sessionId:t,apdu:o,requestId:n})),n}}}const C8=e=>{try{const t=JSON.parse(e);return typeof t=="string"||t!==null&&typeof t=="object"?t:t===null?{}:JSON.stringify(t)}catch{return e}},k8=new Set(["debug","info","warning","error","fatal"]),R8=e=>{if(e===null||typeof e!="object")return!1;const{timestamp:t,tag:r,verbosity:n,message:o,payloadJSON:a}=e;return typeof t=="string"&&typeof r=="string"&&typeof o=="string"&&typeof n=="string"&&k8.has(n)&&(a===void 0||typeof a=="string")};function _8(e){let t;try{t=JSON.parse(e)}catch{return null}if(!R8(t))return null;const r=t.payloadJSON??"{}";return{timestamp:t.timestamp,tag:t.tag,verbosity:t.verbosity,message:t.message,payloadJSON:r,payload:C8(r)}}function $8(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 A8(e,t){const r=_8(e);return r!==null?(t(r),!0):!1}function T8(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse connectedDevicesUpdate payload",r)}}function L8(e,t){try{const{sessionId:r,state:n}=JSON.parse(e);t(o=>new Map(o).set(r,n))}catch(r){console.error("Failed to parse deviceSessionStateUpdate payload",r)}}function I8(e,t){try{const r=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse discoveredDevicesUpdate payload",r)}}function O8(e,t){try{const{provider:r}=JSON.parse(e);t(r)}catch(r){console.error("Failed to parse providerValue payload",r)}}const N8=e=>{try{const{protocol:t,host:r}=new URL(e);return(t==="http:"||t==="https:")&&r!==""}catch{return!1}};function P8(e){try{const t=JSON.parse(e);if(t===null)return null;if(typeof t!="object")return;const{url:r,sessionToken:n}=t;return typeof r!="string"||!N8(r)||n!==void 0&&typeof n!="string"?void 0:n===void 0?{url:r}:{url:r,sessionToken:n}}catch{return}}function D8(e,t){const r=P8(e);if(r===void 0){console.error("Ignored an invalid mockServerConfig payload");return}t(r)}function j8(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)}}const M8=250;function z8(e){const[t,r]=x.useState([]),[n,o]=x.useState(new Set),[a,l]=x.useState([]),[u,d]=x.useState(new Map),[p,h]=x.useState([]),[m,y]=x.useState(!1),[w,E]=x.useState(!1),[S,C]=x.useState(null),[R,k]=x.useState(new Map),[$,A]=x.useState(null),D=x.useRef([]);x.useEffect(()=>{let H;const O=()=>{H=void 0;const U=D.current;D.current=[],U.length>0&&r(z=>[...z,...U].slice(-2e4))},{unsubscribe:L}=e.listenToMessages((U,z)=>{switch(H??=setTimeout(O,M8),U){case S5:$8(z,o);break;case Es.CONNECTED_DEVICES_UPDATE:T8(z,l);break;case Es.DEVICE_SESSION_STATE_UPDATE:L8(z,d);break;case Es.DISCOVERED_DEVICES_UPDATE:I8(z,h);break;case Es.PROVIDER_VALUE:O8(z,C);break;case Es.APDU_RESPONSE:j8(z,k);break;case Es.MOCK_SERVER_CONFIG:D8(z,A);break;case b8.ADD_LOG:A8(z,T=>D.current.push(T));break}});return()=>{L(),clearTimeout(H),D.current=[]}},[e]);const N=x.useMemo(()=>x8(e),[e]),P=x.useMemo(()=>w8(e),[e]),I=x.useMemo(()=>E8(e),[e]),re=x.useCallback(()=>{y(!0),h([]),N.startListeningCommand()},[N]),Z=x.useCallback(()=>{y(!1),h([]),N.stopListeningCommand()},[N]),ee=x.useCallback(()=>{E(!0),h([]),N.startDiscoveringCommand()},[N]),ne=x.useCallback(()=>{E(!1),h([]),N.stopDiscoveringCommand()},[N]),X=x.useCallback(()=>{D.current=[],r([])},[]),F=n.has(mw.LOGGER),V=n.has(mw.DMK_INSPECTOR);return{logs:t,connectedModules:n,connectedDevices:a,sessionStates:u,discoveredDevices:p,isListening:m,isActivelyDiscovering:w,isLoggerConnected:F,isInspectorConnected:V,providerValue:S,apduResponses:R,mockServer:$,sendMessage:e.sendMessage,clearLogs:X,startListening:re,stopListening:Z,startDiscovering:ee,stopDiscovering:ne,connectDevice:N.connectDeviceCommand,getProvider:P.getProviderCommand,setProvider:P.setProviderCommand,sendApdu:I.sendApduCommand}}const $g=e=>`devtools-panel-width-${e}`,F8=e=>{try{const t=Number(localStorage.getItem($g(e)));return t>0?t:null}catch{return null}},ym=(e,t)=>{try{t===null?localStorage.removeItem($g(e)):localStorage.setItem($g(e),String(t))}catch{}},Dv=({name:e,defaultWidth:t,minWidth:r,maxWidth:n,edge:o,className:a="",children:l})=>{const[u,d]=x.useState(()=>F8(e)??t),p=y=>{y.preventDefault();const w=y.clientX,E=u;let S=E;document.body.style.cursor="col-resize",document.body.style.userSelect="none";const C=k=>{const $=k.clientX-w;S=Math.min(n,Math.max(r,E+(o==="right"?$:-$))),d(S)},R=()=>{document.body.style.cursor="",document.body.style.userSelect="",ym(e,S),window.removeEventListener("mousemove",C),window.removeEventListener("mouseup",R)};window.addEventListener("mousemove",C),window.addEventListener("mouseup",R)},h=y=>{const w=y.key==="ArrowRight"?16:y.key==="ArrowLeft"?-16:0;if(w===0)return;y.preventDefault();const E=Math.min(n,Math.max(r,u+(o==="right"?w:-w)));d(E),ym(e,E)},m=()=>{d(t),ym(e,null)};return v.jsxs("div",{className:`relative flex flex-col ${a}`,style:{flex:`0 1 ${u}px`,minWidth:r},children:[l,v.jsx("span",{role:"separator","aria-orientation":"vertical","aria-label":"Resize the panel","aria-valuenow":u,"aria-valuemin":r,"aria-valuemax":n,tabIndex:0,title:"Drag or use the arrow keys to resize, double-click to reset",onMouseDown:p,onKeyDown:h,onDoubleClick:m,className:`absolute inset-y-0 z-10 w-6 cursor-col-resize border-transparent hover:border-active focus-visible:border-active focus-visible:outline-none ${o==="right"?"-right-3 border-r-2":"-left-3 border-l-2"}`})]})},f_="relative w-320 min-w-160 shrink",Ml="flex h-32 items-center gap-6 overflow-hidden rounded-sm border border-muted-subtle bg-surface px-8 transition-colors hover:border-muted focus-within:border-active",zl="min-w-0 flex-1 bg-transparent font-mono! body-3 text-base outline-none placeholder:text-muted",Lo="flex size-24 shrink-0 cursor-pointer items-center justify-center rounded-xs text-muted transition-colors hover:bg-base-transparent-hover hover:text-base disabled:cursor-default disabled:text-disabled disabled:hover:bg-transparent",p_=/Mac|iPhone|iPad/.test(navigator.userAgent)?"⌘":"Ctrl+",h_="rounded-xs border border-muted px-4 font-mono! body-4 text-muted",B8="body-4-semi-bold text-muted uppercase",U8=e=>{const t=[{title:null,blocks:[]}],r=e.split(`
|
|
40
40
|
`);let n=0;const o=()=>t[t.length-1];for(;n<r.length;){const a=r[n],l=a.match(/^```(\w*)/);if(l){const d=[];for(n++;n<r.length&&!r[n].startsWith("```");)d.push(r[n]),n++;n++,o().blocks.push(l[1]==="sequence"?{kind:"sequence",lines:d.filter(p=>p.trim())}:{kind:"code",text:d.join(`
|
|
41
41
|
`)});continue}const u=a.match(/^#{1,4}\s+(.*)/);if(u)t.push({title:u[1].trim(),blocks:[]});else if(/^\s*[-*]\s+/.test(a)){const d=[];for(;n<r.length&&/^\s*[-*]\s+/.test(r[n]);)d.push(r[n].replace(/^\s*[-*]\s+/,"")),n++;o().blocks.push({kind:"list",items:d});continue}else if(a.trim()){const d=[a];for(;n+1<r.length&&r[n+1].trim()&&!/^(#|```|\s*[-*]\s)/.test(r[n+1]);)n++,d.push(r[n]);o().blocks.push({kind:"paragraph",text:d.join(" ")})}n++}return t.filter(a=>a.title!==null||a.blocks.length>0)},D1=({text:e})=>v.jsx(v.Fragment,{children:e.split(/(\*\*[^*]+\*\*|`[^`]+`|https?:\/\/[^\s)]+)/).map((t,r)=>t.startsWith("http")?v.jsx("a",{href:t,target:"_blank",rel:"noreferrer",className:"text-active underline",children:t},r):t.startsWith("**")&&t.endsWith("**")?v.jsx("strong",{children:t.slice(2,-2)},r):t.startsWith("`")&&t.endsWith("`")?v.jsx("code",{className:"font-mono! body-4",children:t.slice(1,-1)},r):t)}),V8=/\b(?!9000\b)[5-6][0-9a-f]{3}\b/i,W8=({line:e})=>{const t=e.match(/^\s*(App|Device)\s*->\s*(?:App|Device)\s*:\s*(.*)$/i),r=t?.[1]?.toLowerCase()==="app",n=t?.[2]??e;return v.jsxs("li",{className:`flex gap-8 font-mono! body-4 ${r?"":"pl-24"} ${V8.test(n)&&!r?"text-error":""}`,children:[v.jsx("span",{className:"shrink-0 text-muted",children:r?"App →":"← Device"}),v.jsx("span",{className:"min-w-0 break-words",children:n})]})},H8=({block:e})=>{switch(e.kind){case"paragraph":return v.jsx("p",{className:"body-3",children:v.jsx(D1,{text:e.text})});case"list":return v.jsx("ul",{className:"flex list-disc flex-col gap-4 pl-16 body-3",children:e.items.map((t,r)=>v.jsx("li",{children:v.jsx(D1,{text:t})},r))});case"sequence":return v.jsx("ol",{className:"flex flex-col gap-4 rounded-sm bg-muted px-12 py-8",children:e.lines.map((t,r)=>v.jsx(W8,{line:t},r))});case"code":return v.jsx("pre",{className:"overflow-x-auto rounded-sm bg-muted px-12 py-8 font-mono! body-4",children:e.text})}},q8=({markdown:e})=>v.jsx("div",{className:"flex flex-col gap-16",children:U8(e).map((t,r)=>{const n=t.blocks[0]?.kind==="paragraph"?t.blocks[0].text:"",o=t.title?.toLowerCase()==="result",a=/^\**failed/i.test(n);return v.jsxs("section",{className:`flex flex-col gap-8 ${o?"rounded-sm bg-muted px-12 py-10":""}`,children:[t.title&&v.jsxs("h3",{className:`flex items-center gap-8 ${B8}`,children:[o&&v.jsx("span",{className:`size-8 rounded-full ${a?"bg-(--color-light-red-500)":"bg-(--color-light-green-500)"}`}),t.title]}),t.blocks.map((l,u)=>v.jsx(H8,{block:l},u))]},r)})}),Ts="<redacted>",m_=String.raw`\b([A-Za-z0-9_-]*(?:token|secret|password|passphrase|api[_-]?key|private[_-]?key|seed|mnemonic)[A-Za-z0-9_-]*|authorization)`,G8=new RegExp(String.raw`${m_}(\\?["']?\s*[:=]\s*)(\\?["'])`,"gi"),X8=(e,t,r)=>{for(let n=t;n<e.length;n++){if(e.startsWith(r,n))return n;e[n]==="\\"&&n++}return-1},Y8=e=>{let t="",r=0;for(const n of e.matchAll(G8)){const o=n.index+n[0].length;if(n.index<r)continue;const a=X8(e,o,n[3]);a<0||(t+=e.slice(r,o)+Ts,r=a)}return t+e.slice(r)},j1=(e,t)=>Y8(t.reduce((r,n)=>r.replaceAll(n,Ts),e)).replace(/\b(authorization\s*:\s*)(?!<redacted>)[^\r\n"']+/gi,`$1${Ts}`).replace(/\b(bearer\s+)(?!<redacted>)[^\s"',;\\]+/gi,`$1${Ts}`).replace(/\b(basic\s+)(?!<redacted>)[A-Za-z0-9+/]{8,}={0,2}/gi,`$1${Ts}`).replace(new RegExp(String.raw`${m_}(["']?\s*[:=]\s*)(?!<redacted>|\\?["'])[^\s"',;&\\]+`,"gi"),`$1$2${Ts}`),K8=(e,t)=>{switch(e.kind){case"explain":return{...e,context:j1(e.context,t)};case"followUp":return{...e,question:j1(e.question,t)};case"createTicket":return e}},Q8="body-4-semi-bold text-muted uppercase",bm="cursor-pointer rounded-sm bg-muted-transparent px-12 py-6 body-3-semi-bold hover:bg-muted-transparent-hover",Lu="cursor-pointer rounded-sm bg-accent px-12 py-6 body-3-semi-bold text-on-accent hover:bg-accent-hover",M1=({selected:e,disabled:t,onClick:r,children:n})=>v.jsx("button",{type:"button","aria-pressed":e,disabled:t,onClick:r,className:`cursor-pointer rounded-sm px-10 py-4 body-4 disabled:cursor-default disabled:opacity-50 ${e?"bg-active-subtle body-4-semi-bold text-active":"bg-muted-transparent text-muted hover:bg-muted-transparent-hover"}`,children:n}),xm=({title:e,children:t})=>v.jsxs("div",{className:"flex flex-col gap-12 p-16",children:[v.jsx("h3",{className:"heading-5-semi-bold",children:e}),t]}),J8=({turn:e,running:t})=>v.jsxs("div",{className:"flex flex-col gap-12",children:[e.question&&v.jsx("p",{className:"self-end rounded-sm bg-muted px-12 py-8 body-3",children:e.question}),e.steps.length>0&&v.jsx("ul",{className:"flex flex-col gap-4 body-4 text-muted",children:e.steps.map((r,n)=>v.jsxs("li",{className:"flex items-center gap-8",children:[t&&n===e.steps.length-1?v.jsx(yl,{size:12}):v.jsx(Pd,{size:12}),r]},n))}),e.answer!==null?v.jsx(q8,{markdown:e.answer}):e.text&&v.jsx("p",{className:"body-3 whitespace-pre-wrap",children:e.text}),t&&e.steps.length===0&&!e.text&&v.jsxs("p",{className:"flex items-center gap-8 body-3 text-muted",children:[v.jsx(yl,{size:16}),"Starting Claude Code…"]}),e.error&&v.jsxs("div",{className:"flex flex-col gap-4 rounded-sm bg-muted px-12 py-10",children:[v.jsx("span",{className:"body-3-semi-bold text-error",children:"Claude stopped before finishing"}),v.jsx("span",{className:"font-mono! body-4 break-words text-muted",children:e.error})]})]}),Z8=({ai:e,request:t,secrets:r})=>{const[n,o]=x.useState(null),[a,l]=x.useState(!1),[u,d]=x.useState([]),[p,h]=x.useState(null),[m,y]=x.useState(!1),[w,E]=x.useState(""),S=x.useRef(null),C=x.useRef(null),R=x.useCallback((O=!1)=>{e&&(o(null),e.status(O).then(o).catch(L=>o({ready:!1,error:String(L)})))},[e]);x.useEffect(()=>R(),[R]);const k=()=>{e?.status(!0).then(o).catch(()=>{})};x.useEffect(()=>()=>S.current?.(),[]);const $=O=>d(L=>[...L.slice(0,-1),O(L.at(-1))]),A=x.useCallback((O,L,U)=>{if(!e)return;S.current?.();const z={question:L,steps:[],text:"",answer:null,verdict:void 0,ticket:void 0,createsTicket:!1,error:null};d(T=>U?[z]:[...T,z]),U&&h(null),y(!0),C.current={aiRequest:O,turnQuestion:L},S.current=e.analyze(K8(O,r),T=>{switch(T.type){case"step":$(M=>({...M,steps:[...M.steps,T.text],createsTicket:M.createsTicket||T.createsTicket===!0}));break;case"text":$(M=>({...M,text:M.text+T.text}));break;case"done":$(M=>({...M,answer:T.answer,verdict:T.verdict,ticket:T.ticket})),h(T.sessionId),y(!1),S.current=null;break;case"error":$(M=>({...M,error:T.message})),y(!1),S.current=null;break}})},[e,r]),D=x.useRef(null),N=x.useCallback(O=>{D.current=O,A({kind:"explain",context:O.context,summary:O.summary,readCode:a},null,!0)},[A,a]),P=n?.ready===!0;x.useEffect(()=>{t&&P&&D.current?.id!==t.id&&N(t)},[t,P,N]);const I=()=>{const O=C.current;if(!O||O.aiRequest.kind==="explain"){N(D.current);return}d(L=>L.slice(0,-1)),A(O.aiRequest,O.turnQuestion,!1)},re=()=>{S.current?.(),S.current=null,y(!1),$(O=>({...O,error:O.answer===null?"Stopped.":null}))},Z=[...u].reverse().find(O=>O.verdict)?.verdict==="bug",ee=u.find(O=>O.ticket)?.ticket,ne=u.some((O,L)=>O.createsTicket&&O.answer===null&&!(m&&L===u.length-1)),X=n?.ready===!0&&n.canCreateTickets,F=()=>{p&&A({kind:"createTicket",sessionId:p},"Create a Jira ticket",!1)},V=()=>{const O=w.trim();!O||!p||(E(""),A({kind:"followUp",sessionId:p,question:O,readCode:a},O,!1))},H=e?n===null?v.jsxs("p",{className:"flex items-center gap-8 p-16 body-3 text-muted",children:[v.jsx(yl,{size:16}),"Checking Claude Code…"]}):n.ready?u.length===0?v.jsxs(xm,{title:"Select logs or APDUs, then press Explain with AI",children:[v.jsx("p",{className:"body-3 text-muted",children:"Claude explains what happened and why, step by step, and draws the exchange between the app and the device."}),v.jsx("span",{className:Q8,children:"Skills it uses"}),v.jsx("div",{className:"flex flex-wrap gap-6",children:n.skills.map(O=>v.jsx("span",{className:"rounded-sm bg-muted-transparent px-8 py-2 font-mono! body-4 text-muted",children:O},O))})]}):v.jsxs("div",{className:"flex flex-col gap-20 p-16",children:[u.map((O,L)=>v.jsx(J8,{turn:O,running:m&&L===u.length-1},L)),!m&&u.at(-1)?.error&&D.current&&v.jsx("button",{type:"button",className:`self-start ${Lu}`,onClick:I,children:"Retry"})]}):v.jsxs(xm,{title:"Sign in to Claude Code to use AI debugging",children:[v.jsx("p",{className:"body-3 text-muted",children:"The DevTools uses the Claude Code login on this computer. Nothing is sent until you press Explain with AI."}),v.jsx("span",{className:"body-3",children:"1. Install Claude Code"}),v.jsx("code",{className:"rounded-sm bg-muted px-10 py-6 font-mono! body-4",children:"npm install -g @anthropic-ai/claude-code"}),v.jsx("span",{className:"body-3",children:"2. Run it once to sign in"}),v.jsx("code",{className:"rounded-sm bg-muted px-10 py-6 font-mono! body-4",children:"claude"}),v.jsx("span",{className:"font-mono! body-4 break-words text-muted",children:n.error}),v.jsx("button",{type:"button",className:`self-start ${Lu}`,onClick:()=>R(!0),children:"Check again"})]}):v.jsx(xm,{title:"AI debugging needs the DevTools desktop app",children:v.jsx("p",{className:"body-3 text-muted",children:"It runs Claude Code on your computer, which this panel cannot do. Open the same session in the desktop DevTools."})});return v.jsx(Dv,{name:"ai",defaultWidth:400,minWidth:320,maxWidth:800,edge:"left",className:"border-l border-muted-subtle bg-surface",children:v.jsxs("aside",{className:"flex min-h-0 flex-1 flex-col",children:[v.jsxs("div",{className:"flex items-center gap-8 border-b border-muted-subtle px-16 py-12",children:[v.jsx(mv,{size:16,className:"text-active"}),v.jsx("h2",{className:"body-2-semi-bold",children:"AI debugging"}),D.current&&v.jsxs("span",{className:"truncate body-4 text-muted",children:["· ",D.current.summary]}),v.jsx("span",{className:"flex-1"}),m&&v.jsx("button",{type:"button",className:bm,onClick:re,children:"Stop"})]}),P&&v.jsxs("div",{className:"flex items-center gap-6 px-16 pt-12",children:[v.jsx(M1,{selected:!a,disabled:m,onClick:()=>l(!1),children:"Quick"}),n.canReadCode&&v.jsx(vt,{label:"Let Claude read DMK's source code to confirm the cause. Slower.",children:v.jsx(M1,{selected:a,disabled:m,onClick:()=>l(!0),children:"Read the code"})}),v.jsx("span",{className:"flex-1"}),v.jsx("span",{className:"body-4 text-muted",children:n.model})]}),v.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:H}),P&&p&&v.jsxs("div",{className:"flex items-center gap-8 border-t border-muted-subtle px-16 py-12",children:[v.jsx("div",{className:`flex-1 ${Ml}`,children:v.jsx("input",{className:zl,type:"text",placeholder:"Ask a follow-up…","aria-label":"Ask a follow-up question",value:w,disabled:m,onChange:O=>E(O.target.value),onKeyDown:O=>O.key==="Enter"&&V()})}),v.jsx(vt,{label:"Ask",children:v.jsx(sr,{"aria-label":"Ask",icon:fR,size:"xs",appearance:"transparent",className:"rounded-sm [&>svg]:text-active",disabled:m||!w.trim(),onClick:V})}),ee?v.jsxs("a",{href:ee.url,target:"_blank",rel:"noreferrer",className:`whitespace-nowrap ${bm}`,children:[ee.key," ↗"]}):Z?ne?v.jsx("span",{className:"body-4 text-muted",children:"The ticket may already exist: check Jira"}):X?v.jsx("button",{type:"button",className:`whitespace-nowrap ${Lu} disabled:cursor-default disabled:opacity-50`,disabled:m,onClick:F,children:"Create Jira ticket"}):v.jsxs(v.Fragment,{children:[v.jsx(vt,{label:"Connect Atlassian in Claude (claude.ai › Settings › Connectors) to create tickets",children:v.jsx("button",{type:"button",disabled:!0,className:`cursor-default whitespace-nowrap opacity-50 ${Lu}`,children:"Create Jira ticket"})}),v.jsx("button",{type:"button",className:`whitespace-nowrap ${bm}`,onClick:k,children:"Check again"})]}):null]})]})})},g_=({title:e,description:t,codeExample:r})=>v.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-16 overflow-auto p-24",children:[v.jsx(ZD,{appearance:"muted",icon:b5,size:56}),v.jsx("h3",{className:"heading-4-semi-bold",children:e}),v.jsx("p",{className:"max-w-480 text-center body-2 text-muted",children:t}),v.jsx("pre",{className:"max-w-full overflow-auto rounded-md bg-muted p-16 font-mono! body-3",children:r})]}),eU={b001:"getAppAndVersion",b006:"loadCertificate",b010:"editExternalAddressIdentifier / editExternalAddressScope / provideContact / registerIdentity",b0a7:"closeApp"},tU={e001:"getOsVersion",e010:"getBatteryStatus",e02e:"renameContact",e033:"deleteLanguagePack",e034:"listLanguagePack",e060:"createBackgroundImage",e061:"uploadBackgroundImageChunk",e062:"commitBackgroundImage",e063:"deleteBackgroundImage",e064:"getBackgroundImageSize",e065:"fetchBackgroundImageChunk",e066:"getBackgroundImageHash",e06a:"GetAppStorageInfo",e06b:"BackupAppStorage",e06c:"InitRestoreAppStorage",e06d:"RestoreAppStorage",e06e:"CommitRestoreAppStorage",e06f:"RequestMasterConsent",e0d8:"openApp",e0de:"listApps",e0df:"listApps"},rU={Aleo:{e003:"GetAppConfig",e005:"getAddress",e006:"signFeeIntent / signNestedCall / signRootIntent",e007:"getViewKey",e008:"getTvk"},Bitcoin:{e100:"getExtendedPublicKey",e102:"registerWalletAddress",e103:"getWalletAddress",e104:"signPsbt",e105:"getMasterFingerprint",e110:"signMessage",f801:"continue"},"Bitcoin Cash":{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},"Bitcoin Gold":{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},Concordium:{e000:"VerifyAddress",e001:"GetPublicKey",e002:"SignTransfer",e004:"SignCredentialDeployment",e022:"SetTrustedName",e023:"GetChallenge",e027:"SignPlt",e032:"SignTransferWithMemo",e040:"GetAppConfig"},Cosmos:{5500:"GetAppConfig",5502:"SignTransaction",5504:"GetAddress"},Dogecoin:{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},Ethereum:{e002:"getAddress",e004:"signTransaction / startTransaction / storeTransaction",e006:"getAppConfiguration",e008:"signPersonalMessage",e00a:"provideTokenInformation",e00c:"signEIP712",e012:"setExternalPlugin",e014:"provideNFTInformation",e016:"setPlugin",e01a:"sendEIP712StructDefinition",e01c:"sendEIP712StructImplem",e01e:"sendEIP712Filtering",e020:"getChallenge",e022:"provideTrustedName",e024:"provideEnum",e026:"provideTransactionInformation",e028:"provideTransactionFieldDescription",e02a:"provideProxyInfo",e030:"provideNetworkConfiguration",e032:"provideWeb3Check / web3CheckOptIn",e034:"signEIP7702Authorization",e036:"provideSafeAccount",e038:"provideGatedSigning"},Horizen:{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},Hyperliquid:{e002:"sendMetadata",e003:"sendAction",e004:"signActions"},InternetComputer:{1100:"GetVersion",1101:"GetAddress",1102:"SignTransaction",1103:"SignUpdateCall"},"Ledger Sync":{e003:"getAppName / getVersion",e005:"getSeedId",e006:"init",e007:"signBlockSignature / signBlockSingle",e008:"parseBlockSignature / parseSingle",e009:"setTrustedMember"},Litecoin:{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction",e04a:"HashOutputFull / ProvideOutputFullChangePath"},Polkadot:{f901:"GetAddress",f902:"SignTransaction"},Solana:{e004:"getAppConfiguration",e005:"getPubKey",e006:"signTransaction",e007:"signOffChainMessage",e008:"signTransactionPreview",e009:"delayedSignTransaction",e00a:"signMessageGenericPreview",e00b:"promptUiDisplay",e00c:"finalizeGenericClearSign",e016:"ProvideInstructionDescriptor",e020:"getChallenge",e021:"provideTLVDescriptor",e022:"ProvideTLVTransactionInstructionDescriptor",e023:"provideTransactionCheck / transactionCheckOptIn",e024:"provideInstructionInfo",e025:"provideInstructionSubstructure",e026:"provideEnumVariant",e027:"provideTokenAccountState",e028:"provideAltResolution",e029:"provideTrustedName"},Tron:{e002:"GetAddress",e004:"signTransaction",e005:"signTransactionHash",e006:"GetAppConfiguration",e008:"signPersonalMessage",e00a:"GetECDHSecret"},XRP:{e002:"GetAddress",e004:"SignTransaction",e006:"GetAppConfig"},Zcash:{e040:"GetAddress",e042:"GetTrustedInput",e044:"StartUntrustedHashTransactionInput",e048:"SignTransaction / ZcashSaplingOutputCommit",e04a:"HashOutputFull / ProvideOutputFullChangePath",e050:"GetFullViewingKey",e051:"GetShieldedAddress",e052:"PcztHeader",e053:"PcztTransparentInput",e054:"PcztTransparentOutput",e055:"SignPcztTransparent",e056:"PcztOrchardAction",e057:"SignPcztOrchard",e058:"PcztIronwoodAction",e059:"SignPcztIronwood",e0c4:"getAppConfig"}},nU={9e3:"OK",5501:"Refused",5502:"PIN not set",5515:"Locked",6807:"App not found",6985:"Refused","6d00":"INS not supported","6e00":"CLA not supported"},jv=e=>nU[e]??"",z1=e=>e.toLowerCase().match(/.{1,2}/g)??[],v_="OS",F1=e=>String.fromCharCode(...e.map(t=>parseInt(t,16))),iU=(e,t)=>{if(t.startsWith("b0"))return eU[t];if(e!==void 0)return Ov(e)?tU[t]:rU[e]?.[t]},oU=(e,t)=>t.startsWith("b0")||e!==void 0&&Ov(e)?v_:e,sU=(e,t,r,n)=>t==="b001"&&n[0]==="01"?F1(n.slice(2,2+parseInt(n[1]??"0",16))):t==="b0a7"?"BOLOS":t==="e0d8"&&(e===void 0||Ov(e))?F1(r.slice(5)):e,aU=e=>typeof e=="object"&&e!==null&&e.type==="apdu-exchange"&&typeof e.sessionId=="string"&&typeof e.apdu=="string"&&typeof e.response=="string",B1=new WeakMap;let lU=0;const cU=e=>{const t=new Map;return e.flatMap(r=>{if(!aU(r.payload))return[];const n=B1.get(r);if(n)return t.set(n.exchange.sessionId,n.openApp),[n.exchange];const{sessionId:o}=r.payload,a=z1(r.payload.apdu),l=z1(r.payload.response),u=l.slice(-2).join(""),d=a.slice(0,2).join(""),p=t.get(o),h=u==="9000"?sU(p,d,a,l.slice(0,-2)):p;t.set(o,h);const m={id:String(lU++),timestamp:r.timestamp,sessionId:o,layer:oU(p,d),command:iU(p,d)??a.slice(0,2).join(" "),sent:a,received:l,statusWord:u};return B1.set(r,{exchange:m,openApp:h}),[m]})},y_=(e,t,r,n,o)=>{const a=x.useRef(null),l=x.useRef(!1),u=x.useRef(e);u.current=e;const d=x.useRef(t);d.current=t;const p=x.useRef(r);p.current=r;const h=x.useRef(n);h.current=n;const m=x.useRef(o);m.current=o,x.useEffect(()=>{const E=()=>{const C=a.current;C?.moved&&(document.body.style.userSelect="",l.current=!0,m.current(C.last)),a.current=null},S=C=>{l.current&&(l.current=!1,C.stopPropagation(),C.preventDefault())};return window.addEventListener("mouseup",E),window.addEventListener("click",S,!0),()=>{window.removeEventListener("mouseup",E),window.removeEventListener("click",S,!0)}},[]);const y=x.useCallback((E,S)=>{const C=u.current(E);S.button!==0||S.shiftKey||C===void 0||(l.current=!1,a.current={anchor:C,last:C,adding:!p.current.has(C),base:new Set(p.current),moved:!1})},[]),w=x.useCallback(E=>{const S=a.current,C=u.current(E);if(!S||C===void 0||C===S.anchor&&!S.moved)return;const R=d.current(S.anchor);if(R<0)return;S.last=C,S.moved||(S.moved=!0,window.getSelection()?.removeAllRanges(),document.body.style.userSelect="none");const k=new Set(S.base);for(let $=Math.min(R,E);$<=Math.max(R,E);$++){const A=u.current($);A!==void 0&&(S.adding?k.add(A):k.delete(A))}h.current(k)},[]);return{onRowMouseDown:y,onRowMouseEnter:w}};function Mv(e){const t=e.trim();if(!t)return[];const r=[],n=/(-?)\/([^/]+)\/|(\S+)/g;let o;for(;(o=n.exec(t))!==null;)if(o[2]!==void 0){const a=o[1]==="-",l=o[2];try{const u=new RegExp(l,"i");r.push({type:"regex",pattern:u,exclude:a})}catch{const u=o[0],d=u.startsWith("-"),p=d?u.slice(1):u;p&&r.push({type:"keyword",value:p.toLowerCase(),exclude:d})}}else if(o[3]!==void 0){const a=o[3],l=a.startsWith("-"),u=l?a.slice(1):a;u&&r.push({type:"keyword",value:u.toLowerCase(),exclude:l})}return r}function uU(e){if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function dU(e){return[e.tag,e.message,uU(e.payload)].join(" ")}function U1(e,t){return e.type==="keyword"?t.toLowerCase().includes(e.value):e.pattern.test(t)}function b_(e,t){if(t.length===0)return!0;const r=dU(e),n=t.filter(a=>!a.exclude),o=t.filter(a=>a.exclude);for(const a of n)if(!U1(a,r))return!1;for(const a of o)if(U1(a,r))return!1;return!0}const x_=({onClick:e,enabled:t,up:r=!1})=>v.jsx(vt,{label:"Scroll to latest logs",side:"left",className:`absolute right-16 bottom-16 transition-[opacity,visibility] duration-300 ${t?"invisible opacity-0":"visible opacity-100"}`,children:v.jsx(sr,{"aria-label":"Scroll to latest logs",icon:r?fR:p5,appearance:"accent",size:"sm",onClick:e,className:"shadow-md"})}),fU=4,w_=e=>{const t=x.useRef(null),r=x.useRef(null),[n,o]=x.useState(!0),a=x.useRef(!0),l=x.useCallback(p=>{a.current=p,o(p)},[]),u=x.useCallback(()=>{const p=t.current;p&&(p.scrollTop=p.scrollHeight)},[]);x.useLayoutEffect(()=>{e&&u()},[e,u]);const d=x.useCallback(()=>{const p=t.current;if(!p)return;const h=p.scrollHeight-p.clientHeight-p.scrollTop<=fU;h!==a.current&&l(h)},[l]);return x.useEffect(()=>{const p=r.current;if(!p||!e)return;const h=new MutationObserver(()=>{a.current&&u()});return h.observe(p,{childList:!0}),()=>h.disconnect()},[e,u]),{containerRef:t,contentRef:r,onScroll:d,atBottom:n,setAtBottom:l,scrollToBottom:u}},S_=({d:e,size:t=16,className:r})=>v.jsx("svg",{width:t,height:t,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",className:r,"aria-hidden":"true",children:v.jsx("path",{d:e})}),pU=e=>v.jsx(S_,{...e,d:"M5.667 3v10m4.666-10v10"}),hU=e=>v.jsx(S_,{...e,d:"M4.667 2.667v10.666L13 8z"}),E_=({paused:e,onToggle:t})=>v.jsx(vt,{label:e?"Resume incoming logs":"Pause incoming logs",side:"bottom",children:v.jsx(sr,{"aria-label":e?"Resume incoming logs":"Pause incoming logs",icon:e?hU:pU,size:"xs",appearance:"transparent",className:`rounded-sm ${e?"bg-active-subtle hover:bg-active-subtle-hover [&>svg]:text-active":""}`,onClick:t})});function V1(e,t){return e.type==="keyword"?t.toLowerCase().includes(e.value):e.pattern.test(t)}function mU(e,t){if(t.length===0)return!0;const r=t.filter(o=>!o.exclude),n=t.filter(o=>o.exclude);for(const o of r)if(!V1(o,e))return!1;for(const o of n)if(V1(o,e))return!1;return!0}const W1=({text:e,label:t})=>{const[r,n]=x.useState(!1);return v.jsx(vt,{label:t,children:v.jsx(sr,{"aria-label":t,icon:r?Pd:pR,size:"xs",appearance:"no-background",onClick:()=>{navigator.clipboard.writeText(e).then(()=>{n(!0),setTimeout(()=>n(!1),1500)})}})})},H1=5,Ag=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,hour12:!1}),gU=e=>e==="9000"?{bar:"bg-(--color-light-green-500)",text:"text-success"}:e==="5515"?{bar:"bg-(--color-light-yellow-500)",text:"text-warning"}:{bar:"bg-(--color-light-red-500)",text:"text-error"},vU=e=>[e.command,e.layer,e.sent.join(" "),e.sent.join(""),e.received.join(" "),e.received.join(""),jv(e.statusWord)].join(" "),yU=e=>`[${e.timestamp}] [${e.layer??"unknown app"}] ${e.command} | => ${e.sent.join("")} | <= ${e.received.join("")}`,bU=({exchange:e,index:t,open:r,onToggle:n,selected:o,onSelect:a,onRowMouseDown:l,onRowMouseEnter:u})=>{const d=gU(e.statusWord);return v.jsxs("div",{className:`flex gap-8 px-8 py-2 ${o?"bg-active-subtle":""}`,onMouseDown:p=>l(t,p),onMouseEnter:()=>u(t),children:[v.jsx("div",{className:"flex shrink-0 pt-4",children:v.jsx(Jg,{"aria-label":"Select this APDU",checked:o,className:"size-16",onClick:p=>a(t,p.shiftKey)})}),v.jsx("span",{className:`w-4 shrink-0 rounded-full ${d.bar}`}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>n(e.id),className:"flex w-full cursor-pointer items-center gap-12 rounded-xs px-8 py-2 text-left font-mono! body-3 text-base hover:bg-base-transparent-hover",children:[v.jsx(Nd,{size:12,className:`shrink-0 text-muted transition-transform ${r?"rotate-90":""}`}),v.jsx("span",{className:"text-muted",children:Ag(e.timestamp)}),v.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-8",children:[v.jsx(bg,{size:"sm",appearance:e.layer===v_?"accent-subtle":"gray",label:e.layer??"Unknown",className:"max-w-128 shrink-0"}),v.jsx("span",{className:"truncate",children:e.command})]}),v.jsxs("span",{className:"body-4 whitespace-nowrap text-muted",children:[e.sent.length," B → ",e.received.length," B"]}),v.jsxs("span",{className:`w-128 truncate ${d.text}`,children:[e.statusWord," ",jv(e.statusWord)]})]}),r&&v.jsxs("div",{className:"my-4 flex flex-col gap-8 rounded-sm bg-muted px-12 py-8 font-mono! body-3",children:[v.jsxs("div",{className:"flex items-center gap-8",children:[v.jsxs("span",{className:"body-4-semi-bold text-muted uppercase",children:["Sent · ",e.sent.length," B"]}),v.jsx("span",{className:"flex-1"}),v.jsx(W1,{text:e.sent.join(""),label:"Copy sent bytes"})]}),v.jsxs("p",{className:"break-all",children:[e.sent.slice(0,H1).join(" ")," ",v.jsx("span",{className:"text-muted",children:e.sent.slice(H1).join(" ")})]}),v.jsxs("div",{className:"flex items-center gap-8",children:[v.jsxs("span",{className:"body-4-semi-bold text-muted uppercase",children:["Received · ",e.received.length," B"]}),v.jsx("span",{className:"flex-1"}),v.jsx(W1,{text:e.received.join(""),label:"Copy received bytes"})]}),v.jsx("p",{className:"break-all",children:e.received.join(" ")})]})]})]})},xU=Ee.memo(bU,(e,t)=>e.exchange.id===t.exchange.id&&e.index===t.index&&e.open===t.open&&e.onToggle===t.onToggle&&e.selected===t.selected&&e.onSelect===t.onSelect&&e.onRowMouseDown===t.onRowMouseDown&&e.onRowMouseEnter===t.onRowMouseEnter),wU=({exchanges:e,clearedUpTo:t,onClear:r,onExplain:n})=>{const[o,a]=x.useState(""),[l,u]=x.useState(null),[d,p]=x.useState(new Set),h=x.useMemo(()=>{const O=l??e;return t===void 0?O:O.filter(L=>Number(L.id)>t)},[l,e,t]),m=x.useMemo(()=>{const O=Mv(o);return O.length===0?h:h.filter(L=>mU(vU(L),O))},[h,o]),[y,w]=x.useState(new Set),E=x.useRef(m);E.current=m;const S=x.useRef(null),C=x.useCallback((O,L)=>{const U=E.current,z=U[O];if(!z)return;const T=U.findIndex(({id:M})=>M===S.current);S.current=z.id,w(M=>{const te=new Set(M);if(L&&T>=0)for(let le=Math.min(T,O);le<=Math.max(T,O);le++)te.add(U[le].id);else te.delete(z.id)||te.add(z.id);return te})},[]),{onRowMouseDown:R,onRowMouseEnter:k}=y_(O=>E.current[O]?.id,O=>E.current.findIndex(L=>L.id===O),y,w,O=>{S.current=O}),$=()=>{w(new Set),S.current=null},A=h.filter(({id:O})=>y.has(O)),D=()=>{const O=e.at(-1);O&&r(Number(O.id)),u(L=>L&&[])},N=()=>{const O=new Blob([JSON.stringify(m,null,2)],{type:"application/json"}),L=URL.createObjectURL(O),U=document.createElement("a");U.href=L,U.download=`apdu-${new Date().toISOString()}.json`,U.click(),URL.revokeObjectURL(L)},P=l!==null,{containerRef:I,contentRef:re,onScroll:Z,atBottom:ee,setAtBottom:ne,scrollToBottom:X}=w_(!P),F=x.useCallback(O=>{ne(!1),p(L=>{const U=new Set(L);return U.delete(O)||U.add(O),U})},[ne]),V=()=>{ne(!0),X()},H=h.length-m.length;return v.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-8",children:[v.jsxs("div",{className:"flex flex-wrap items-center gap-x-12 gap-y-8",children:[v.jsx("div",{className:f_,children:v.jsx("div",{className:Ml,children:v.jsx("input",{className:zl,type:"text",placeholder:"Filter","aria-label":"Filter APDUs",value:o,onChange:O=>a(O.target.value)})})}),v.jsx("span",{className:"flex-1"}),v.jsxs("span",{className:"font-mono! body-4 whitespace-nowrap text-muted",children:[P&&v.jsx("span",{className:"text-warning",children:"paused · "}),h.length," ",h.length===1?"exchange":"exchanges",H>0&&` · ${H} filtered out`]}),v.jsxs("div",{className:"flex gap-6",children:[v.jsx(E_,{paused:P,onToggle:()=>u(P?null:e)}),v.jsx(vt,{label:"Clear APDUs",side:"bottom",children:v.jsx(sr,{"aria-label":"Clear APDUs",icon:yR,size:"xs",appearance:"transparent",className:"rounded-sm",onClick:D})}),v.jsx(vt,{label:"Export APDUs",side:"bottom",children:v.jsx(sr,{"aria-label":"Export APDUs",icon:hR,size:"xs",appearance:"transparent",className:"rounded-sm",onClick:N})})]})]}),v.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[v.jsx("div",{ref:I,className:"min-h-0 flex-1 overflow-auto",onScroll:Z,children:v.jsxs("div",{ref:re,children:[m.length===0?v.jsx("p",{className:"p-24 text-center body-2 text-muted",children:"No APDU exchanged yet"}):m.map((O,L)=>v.jsx(xU,{exchange:O,index:L,open:d.has(O.id),onToggle:F,selected:y.has(O.id),onSelect:C,onRowMouseDown:R,onRowMouseEnter:k},O.id)),!P&&m.length>0&&v.jsx("div",{className:`flex h-24 items-center justify-center gap-4 ${ee?"":"invisible"}`,"aria-label":ee?"Following new APDUs":void 0,children:["","[animation-delay:200ms]","[animation-delay:400ms]"].map(O=>v.jsx("span",{className:`size-4 animate-pulse rounded-full bg-muted-strong ${O}`},O))})]})}),v.jsx(x_,{enabled:ee,onClick:V})]}),A.length>0&&v.jsx(SR,{label:`${A.length} ${A.length===1?"APDU":"APDUs"} selected`,detail:`${Ag(A[0].timestamp)} → ${Ag(A.at(-1).timestamp)} · shift-click to extend`,onClear:$,onExplain:()=>n({context:A.map(yU).join(`
|
|
42
42
|
`),summary:`${A.length} ${A.length===1?"APDU":"APDUs"}`})})]})},Iu=(e=[])=>e.map(t=>t.toString(16).padStart(2,"0")).join(""),SU=[{label:"Get app & version",apdu:"B001000000"},{label:"Get OS version",apdu:"E001000000"}],EU=({sessionId:e,onSend:t,responses:r})=>{const[n,o]=x.useState(""),[a,l]=x.useState(null),[u,d]=x.useState(null),p=y=>{const w=y.replace(/\s/g,"").toUpperCase();if(!/^[0-9A-F]*$/.test(w)||w.length%2!==0){l("Invalid hex string (e.g., E0C4000000)");return}d(t(e,w))},h=u?r.get(u):null,m=a??(h&&!h.success?h.error:null);return v.jsxs("div",{className:"flex flex-col gap-8",children:[v.jsxs("div",{className:"flex items-center gap-8",children:[v.jsx("span",{className:"flex-1 body-4-semi-bold text-muted uppercase",children:"APDU"}),SU.map(y=>v.jsx("button",{type:"button",onClick:()=>{o(y.apdu),l(null),p(y.apdu)},className:"cursor-pointer rounded-full bg-muted-transparent px-8 py-2 body-4 text-base hover:bg-muted-transparent-hover",children:y.label},y.apdu))]}),v.jsxs("div",{className:"flex gap-8",children:[v.jsx("div",{className:`flex-1 ${Ml}`,children:v.jsx("input",{className:zl,type:"text",placeholder:"APDU hex (e.g., E0C4000000)","aria-label":"APDU to send",value:n,onChange:y=>{o(y.target.value),l(null)},onKeyDown:y=>y.key==="Enter"&&n.trim()&&p(n)})}),v.jsx(vt,{label:"Send APDU",children:v.jsx(sr,{"aria-label":"Send APDU",icon:v5,size:"xs",appearance:"transparent",className:"rounded-sm [&>svg]:text-active",onClick:()=>p(n),disabled:!n.trim()})})]}),m&&v.jsx("p",{className:"body-3 text-error",children:m}),!m&&h?.success&&v.jsxs("p",{className:"flex flex-wrap items-baseline gap-x-8 font-mono! body-3",children:[v.jsxs("span",{className:Iu(h.statusCode)==="9000"?"text-success":"text-error",children:[Iu(h.statusCode)," ",jv(Iu(h.statusCode))]}),h.data&&h.data.length>0&&v.jsx("span",{className:"break-all text-muted",children:Iu(h.data)})]})]})},CU={nanoS:Vu,nanoSP:Vu,nanoX:Vu,stax:vR,flex:mR,apexp:gR},zv=({modelId:e,className:t=""})=>{const r=CU[e]??h5;return v.jsx(r,{size:20,className:`shrink-0 text-muted ${t}`})},Fv="MOCKSERVER",kU=800,C_=e=>e===Fv?"Mock server":e,k_=e=>!e||e.deviceStatus!=="NOT CONNECTED",R_=e=>{const[t,r]=x.useState(e);return x.useEffect(()=>{if(e!=="BUSY"){r(e);return}const n=setTimeout(()=>r(e),kU);return()=>clearTimeout(n)},[e]),t},RU={CONNECTED:"bg-(--color-light-green-500)",LOCKED:"bg-(--color-light-yellow-500)",BUSY:"bg-(--color-light-decorative-blue-500)","NOT CONNECTED":"bg-muted-strong"},_U={CONNECTED:"success",LOCKED:"warning",BUSY:"accent-subtle","NOT CONNECTED":"error"},$U=({device:e,state:t,exchanges:r,onSendApdu:n,apduResponses:o,clearedUpTo:a,onClear:l,onExplain:u})=>{const d=t&&"currentApp"in t?t:void 0,p=R_(t?.deviceStatus??"");return v.jsxs("div",{className:"flex min-w-320 flex-1 flex-col gap-16 p-16",children:[v.jsxs("div",{className:"flex items-center gap-8",children:[v.jsx(zv,{modelId:e.modelId}),v.jsx("h4",{className:"heading-5-semi-bold",children:e.name||e.modelId}),p&&v.jsx(bg,{size:"sm",appearance:_U[p]??"gray",label:p}),v.jsx(bg,{size:"sm",appearance:"gray",label:C_(e.transport)})]}),v.jsxs("dl",{className:"grid grid-cols-[120px_1fr] gap-x-12 gap-y-6 body-3",children:[v.jsx("dt",{className:"text-muted",children:"Session ID"}),v.jsx("dd",{className:"truncate font-mono!",children:e.sessionId}),v.jsx("dt",{className:"text-muted",children:"Model"}),v.jsx("dd",{children:e.modelId}),d?.currentApp&&v.jsxs(v.Fragment,{children:[v.jsx("dt",{className:"text-muted",children:"Current app"}),v.jsxs("dd",{children:[d.currentApp.name," ",v.jsx("span",{className:"font-mono! text-muted",children:d.currentApp.version})]})]}),d?.firmwareVersion&&v.jsxs(v.Fragment,{children:[v.jsx("dt",{className:"text-muted",children:"Firmware"}),v.jsx("dd",{className:"font-mono!",children:d.firmwareVersion.os})]}),d?.batteryStatus&&v.jsxs(v.Fragment,{children:[v.jsx("dt",{className:"text-muted",children:"Battery"}),v.jsxs("dd",{children:[d.batteryStatus.level," %"]})]})]}),k_(t)&&v.jsx(EU,{sessionId:e.sessionId,onSend:n,responses:o},`sender-${e.sessionId}`),v.jsx(wU,{exchanges:r,clearedUpTo:a,onClear:l,onExplain:u},`list-${e.sessionId}`)]})},AU=({device:e,onConnect:t})=>v.jsxs("div",{className:"flex items-center gap-10 rounded-sm px-12 py-8 hover:bg-base-transparent-hover",children:[v.jsx(zv,{modelId:e.deviceModel.model}),v.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[v.jsx("span",{className:"truncate body-3-semi-bold",children:e.name||e.deviceModel.name}),v.jsxs("span",{className:"truncate font-mono! body-4 text-muted",children:[e.transport,e.rssi!==void 0&&e.rssi!==null&&` · ${e.rssi} dBm`]})]}),v.jsx("button",{type:"button",onClick:t,className:"cursor-pointer rounded-sm bg-muted-transparent px-8 py-4 body-4-semi-bold hover:bg-muted-transparent-hover",children:"Connect"})]}),wm="body-4-semi-bold text-muted uppercase",q1="cursor-pointer rounded-sm bg-muted-transparent px-8 py-4 body-4-semi-bold hover:bg-muted-transparent-hover disabled:cursor-default disabled:text-disabled",TU=({device:e,state:t,selected:r,onSelect:n})=>{const o=R_(t?.deviceStatus??"CONNECTED"),a=t&&"currentApp"in t?t.currentApp?.name:void 0;return v.jsxs("button",{type:"button",onClick:n,className:`flex cursor-pointer items-center gap-10 rounded-sm px-12 py-8 text-left ${r?"bg-active-subtle":"hover:bg-base-transparent-hover"} ${k_(t)?"":"opacity-60"}`,children:[v.jsx(zv,{modelId:e.modelId}),v.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[v.jsx("span",{className:"truncate body-3-semi-bold",children:e.name||e.modelId}),v.jsxs("span",{className:"truncate font-mono! body-4 text-muted",children:[C_(e.transport),a&&` · ${a}`]})]}),v.jsx("span",{title:o,className:`size-8 shrink-0 rounded-full ${RU[o]??"bg-muted-strong"}`})]})},LU=({devices:e,sessionStates:t,selectedSessionId:r,onSelect:n,discoveredDevices:o,isListening:a,isActivelyDiscovering:l,startListening:u,stopListening:d,startDiscovering:p,stopDiscovering:h,connectDevice:m,mockServer:y})=>{const w=e.some(E=>E.transport===Fv);return v.jsx(Dv,{name:"sessions",defaultWidth:288,minWidth:200,maxWidth:480,edge:"right",className:"border-r border-muted-subtle",children:v.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-16 overflow-auto p-12",children:[v.jsxs("section",{className:"flex flex-col gap-4",children:[v.jsxs("span",{className:`px-4 pb-4 ${wm}`,children:["Sessions · ",e.length]}),e.length===0&&v.jsx("p",{className:"px-4 body-3 text-muted",children:"No device connected yet."}),e.map(E=>v.jsx(TU,{device:E,state:t.get(E.sessionId),selected:E.sessionId===r,onSelect:()=>n(E.sessionId)},E.sessionId))]}),v.jsxs("section",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex items-center gap-6 px-4 pb-4",children:[v.jsx("span",{className:`flex-1 ${wm}`,children:"Discovered"}),v.jsx("button",{type:"button",className:q1,onClick:a?d:u,disabled:l,children:a?"Stop":"Listen"}),v.jsx("button",{type:"button",className:q1,onClick:l?h:p,disabled:a,children:l?"Stop":"Discover"})]}),(a||l)&&o.length===0&&v.jsxs("p",{className:"flex items-center gap-8 px-4 body-3 text-muted",children:[v.jsx(yl,{size:16}),a?"Listening…":"Discovering…"]}),o.map(E=>v.jsx(AU,{device:E,onConnect:()=>m(E.id)},E.id))]}),w&&v.jsxs("section",{className:"mt-auto flex flex-col gap-6 border-t border-muted-subtle px-4 pt-12",children:[v.jsx("span",{className:wm,children:"Mock server"}),y?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"truncate font-mono! body-3",children:y.url}),v.jsx("span",{className:"truncate font-mono! body-4 text-muted",children:y.sessionToken?`Session ${y.sessionToken.slice(0,8)}…`:"No session token shared"})]}):v.jsxs("p",{className:"body-3 text-muted",children:["Pass ",v.jsx("code",{children:"mockServer"})," to"," ",v.jsx("code",{children:"DevToolsDmkInspector"})," to see the device screens."]})]})]})})},Xu=(e,t)=>({label:e,touch:!1,speculos:!0,screenWidth:128,screenHeight:t,lightScreen:!1}),IU={nanoS:{...Xu("Nano S",32),speculos:!1},nanoSP:Xu("Nano S Plus",64),nanoX:Xu("Nano X",64),stax:{label:"Stax",touch:!0,speculos:!0,screenWidth:400,screenHeight:672,lightScreen:!0},flex:{label:"Flex",touch:!0,speculos:!0,screenWidth:480,screenHeight:600,lightScreen:!0},apexp:{label:"Apex",touch:!0,speculos:!0,screenWidth:300,screenHeight:400,lightScreen:!0}},OU=Xu("Device",64),NU=e=>IU[e]??OU,PU=e=>e?.status===409,DU=(e,t)=>({screenshot:async()=>{try{return await e.getScreenshot(t)}catch(r){if(PU(r))return null;throw r}},idle:async()=>({kind:"os-info",device:await e.getDevice(t)}),pressButton:(r,n)=>e.pressButton(t,r,n),touch:(r,n,o)=>e.touchScreen(t,r,n,o),openApp:async r=>{const n=new TextEncoder().encode(r);if(n.length>255)throw new Error(`App name too long to open: ${r}`);const{response:o}=await e.sendApdu(t,Uint8Array.from([224,216,0,0,n.length,...n])),a=o.slice(-4);if(a!=="9000")throw new Error(`Could not open ${r} (${a})`)}}),jU=150;function __(e){const t=x.useRef(null),r=x.useRef(null),n=x.useRef(e);n.current=e;const o=x.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null)},[]),a=x.useCallback(u=>{if(!n.current||t.current)return!1;const d={target:u,pressed:!1};return t.current=d,r.current=setTimeout(()=>{d.pressed=!0,n.current?.(u,"press")},jU),!0},[]),l=x.useCallback(()=>{const u=t.current;return u?(t.current=null,o(),n.current?.(u.target,u.pressed?"release":"press-and-release"),!0):!1},[o]);return x.useEffect(()=>()=>{const u=t.current;t.current=null,o(),u?.pressed&&n.current?.(u.target,"release")},[o]),x.useMemo(()=>({hold:a,release:l}),[a,l])}const MU=e=>__(e),zU=2e3;function FU(e,t){const[r,n]=x.useState();return x.useEffect(()=>{let o=!1,a;if(n(void 0),!t)return;const l=()=>{e.getDevice(t).then(u=>{o||n(u)},()=>{o||(n(null),a=setTimeout(l,zU))})};return l(),()=>{o=!0,clearTimeout(a)}},[e,t]),r}const BU="BOLOS",UU=1e4,VU=e=>(e.apps??[]).filter(({name:t})=>t!==BU),WU=e=>`https://cdn.live.ledger.com/icons/${e.toLowerCase().replaceAll(" ","_")}.png`;function HU(e){const[t,r]=x.useState(),[n,o]=x.useState(),a=x.useRef(void 0);x.useEffect(()=>()=>clearTimeout(a.current),[]);const l=x.useCallback(u=>{!e||t||(r(u),o(void 0),e(u).then(()=>{a.current=setTimeout(()=>{r(void 0),o(`${u} opened but its screen never showed up`)},UU)},d=>{r(void 0),o(d instanceof Error?d.message:String(d))}))},[e,t]);return{opening:t,error:n,open:l}}const qU=500,GU=2e3,XU=3,YU=e=>e instanceof Error?e.message:String(e);function KU(e,t,r){const[n,o]=x.useState({kind:"loading"}),a=x.useRef(null),l=x.useRef(!1),u=x.useRef(!1);u.current=n.kind==="image";const d=x.useRef(0),p=x.useRef(0),h=x.useCallback(S=>{u.current&&++d.current<=XU||o({kind:"error",message:YU(S)})},[]),m=x.useCallback(()=>{a.current&&(r.releaseImageSource?.(a.current),a.current=null)},[r]),y=x.useRef(()=>{}),w=x.useMemo(()=>{const S=C=>{C.then(()=>y.current()).catch(h)};return{pressButton:(C,R)=>S(e.pressButton(C,R)),touch:(C,R,k)=>S(e.touch(C,R,k))}},[e,h]),E=x.useCallback(async()=>{if(l.current)return;l.current=!0;const S=p.current,C=()=>S!==p.current;try{const R=await e.screenshot();if(C())return;if(d.current=0,R){const k=await r.toImageSource(R);if(C()){r.releaseImageSource?.(k);return}k!==a.current&&(m(),a.current=k),o($=>$.kind==="image"&&$.src===k&&$.input===w?$:{kind:"image",src:k,input:w})}else{const k=await e.idle?.();if(C())return;m(),o(k??{kind:"error",message:"No screen to capture"})}}catch(R){C()||h(R)}finally{l.current=!1}},[e,r,w,h,m]);return y.current=()=>{E()},x.useEffect(()=>{if(!t){m(),o({kind:"loading"});return}let S,C=!1;const R=async()=>{r.isHidden()||await E(),!C&&(S=setTimeout(()=>{R()},u.current?qU:GU))};return R(),()=>{C=!0,clearTimeout(S),p.current++}},[t,r,E,m]),x.useEffect(()=>m,[m]),n}const QU=(e,t,r,n)=>{if(!r.width||!r.height||!n.width||!n.height)return null;const o=(a,l)=>Math.min(Math.max(Math.round(a),0),l-1);return{x:o(e/r.width*n.width,n.width),y:o(t/r.height*n.height,n.height)}};function JU(e){const t=x.useMemo(()=>e&&((r,n)=>e(r.x,r.y,n)),[e]);return __(t)}const ZU={stax:vR,flex:mR,apexp:gR},e7=e=>({...NU(e),icon:ZU[e]??Vu}),Bv=({children:e})=>Ee.createElement("div",{className:"border-muted @container relative overflow-hidden rounded-md border"},e),t7="[&::-webkit-scrollbar]:size-[6px] [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:rounded-full",G1=({name:e})=>{const[t,r]=x.useState(!1);return t?Ee.createElement("span",{className:"text-muted bg-muted flex size-[12.5cqw] items-center justify-center rounded-full text-[length:6cqw] font-semibold"},e.charAt(0)):Ee.createElement("img",{src:WU(e),alt:"",draggable:!1,className:"size-[12.5cqw] rounded-full",onError:()=>r(!0)})},r7=({device:e,model:t,onOpenApp:r})=>{const n=VU(e),{opening:o,error:a,open:l}=HU(r),u=t.lightScreen?{background:"bg-white",text:"text-black",scrollbar:"[&::-webkit-scrollbar-thumb]:bg-black/30",overlay:"bg-white/70"}:{background:"bg-black",text:"text-white",scrollbar:"[&::-webkit-scrollbar-thumb]:bg-white/30",overlay:"bg-black/70"},d=t.touch?{scroll:"overflow-y-auto",list:"grid grid-cols-3 gap-[1.5cqw]",tile:"min-w-0 py-[3cqw]",opening:"flex-col"}:{scroll:"flex items-center overflow-x-auto",list:"flex gap-[2.5cqw]",tile:"w-[28cqw] shrink-0 py-[1.5cqw]",opening:"flex-row"};return Ee.createElement("div",{className:"flex flex-col gap-8","data-testid":"container_device-os-info"},Ee.createElement(Bv,null,Ee.createElement("div",{className:`${u.background} ${d.scroll} ${t7} ${u.scrollbar} p-[3cqw]`,style:{aspectRatio:t.screenWidth/t.screenHeight},"data-testid":"list_device-apps"},n.length===0?Ee.createElement("p",{className:`text-[length:5.5cqw] ${u.text} flex h-full w-full items-center justify-center opacity-60`},"No apps installed"):Ee.createElement("div",{className:d.list},n.map(p=>Ee.createElement("button",{key:p.name,type:"button",title:`${p.name} ${p.version}`,disabled:!r||o!==void 0,onClick:()=>l(p.name),className:`${u.text} ${d.tile} flex flex-col items-center gap-[1.5cqw] border-0 bg-transparent px-[1.5cqw] disabled:cursor-default enabled:cursor-pointer`,"data-testid":`button_open-app-${p.name}`},Ee.createElement(G1,{name:p.name}),Ee.createElement("span",{className:"w-full truncate text-center text-[length:4.7cqw] leading-[1.3]"},p.name))))),o!==void 0?Ee.createElement("div",{className:`${u.text} ${u.overlay} ${d.opening} pointer-events-none absolute inset-0 flex items-center justify-center gap-[3cqw] backdrop-blur-[1cqw]`,"data-testid":"spinner_opening-app-screen"},Ee.createElement("div",{className:"relative flex size-[18cqw] shrink-0 items-center justify-center"},Ee.createElement("span",{className:"absolute inset-0 rounded-full border-[0.8cqw] border-current opacity-15"}),Ee.createElement("span",{className:"absolute inset-0 animate-spin rounded-full border-[0.8cqw] border-transparent border-t-current"}),Ee.createElement(G1,{name:o})),Ee.createElement("span",{className:"animate-pulse text-[length:4.7cqw] font-semibold"},"Opening ",o)):null),a?Ee.createElement("p",{className:"body-4 text-error text-center"},a):null)},n7=[{button:"left",label:"Left"},{button:"both",label:"Both"},{button:"right",label:"Right"}],X1=e=>e===" "||e==="Enter",i7=({onPress:e})=>{const{hold:t,release:r}=MU(e);return Ee.createElement("div",{className:"flex gap-8"},n7.map(({button:n,label:o})=>Ee.createElement("button",{key:n,type:"button","aria-label":`${o} button`,onPointerDown:a=>{a.button===0&&(a.currentTarget.setPointerCapture(a.pointerId),t(n))},onPointerUp:r,onPointerCancel:r,onKeyDown:a=>{X1(a.key)&&(a.preventDefault(),t(n))},onKeyUp:a=>X1(a.key)&&r(),className:"border-muted body-3 text-base bg-muted hover:bg-muted-pressed active:bg-active flex-1 rounded-md border py-8 select-none",style:{touchAction:"none"},"data-testid":`button_device-screen-${n}`},o)))},o7=({src:e,onTouch:t})=>{const r=x.useRef(null),[n,o]=x.useState(!1),a=JU(t);x.useEffect(()=>o(!1),[e]);const l=p=>{const h=r.current;if(!t||!h||p.button!==0)return;const m=h.getBoundingClientRect(),y=QU(p.clientX-m.left,p.clientY-m.top,m,{width:h.naturalWidth,height:h.naturalHeight});y&&a.hold(y)&&h.setPointerCapture(p.pointerId)},u=p=>{a.release()&&r.current?.releasePointerCapture(p.pointerId)},d=x.useCallback(()=>o(!0),[]);return n?Ee.createElement("p",{className:"body-4 text-error text-center","data-testid":"text_device-screen-undecodable"},"Screenshot could not be decoded"):Ee.createElement(Bv,null,Ee.createElement("img",{ref:r,src:e,alt:"Device screen",draggable:!1,onError:d,onPointerDown:l,onPointerUp:u,onPointerCancel:u,className:`block w-full bg-black select-none ${t?"cursor-pointer":""}`,style:{imageRendering:"pixelated",touchAction:"none"},"data-testid":"image_device-screen"}))},s7={toImageSource:e=>Promise.resolve(URL.createObjectURL(e)),releaseImageSource:e=>URL.revokeObjectURL(e),isHidden:()=>document.hidden},Sm=16,a7=224,l7=200,Y1=(e,t,r)=>{const n=(o,a)=>Math.min(Math.max(o,0),Math.max(a,0));return{left:n(e,window.innerWidth-r.width),top:n(t,window.innerHeight-r.height)}},c7=(e,t)=>t?`${e} - ${t}`:e,u7=({api:e,deviceType:t,firmwareVersion:r,floating:n=!1,defaultCollapsed:o=!1})=>{const a=e7(t),[l,u]=x.useState(o),d=KU(e,!n||!l,s7);return n?Ee.createElement(d7,{title:c7(a.label,r),model:a,collapsed:l,onToggle:()=>u(p=>!p)},K1(d,a,e)):Ee.createElement("div",{className:"mx-auto flex w-full max-w-[420px] flex-col gap-8","data-testid":"container_device-screen"},K1(d,a,e))},d7=({title:e,model:t,collapsed:r,onToggle:n,children:o})=>{const a=x.useRef(null),[l,u]=x.useState(),[d,p]=x.useState(a7),h=x.useRef(null),m=x.useRef(null);x.useEffect(()=>{const k=()=>{const $=a.current?.getBoundingClientRect();$&&u(A=>A&&Y1(A.left,A.top,$))};return window.addEventListener("resize",k),()=>window.removeEventListener("resize",k)},[]);const y=k=>{const $=a.current?.getBoundingClientRect();!$||k.button!==0||k.target.closest("button")||(k.currentTarget.setPointerCapture(k.pointerId),h.current={dx:k.clientX-$.left,dy:k.clientY-$.top})},w=k=>{const $=a.current?.getBoundingClientRect();!h.current||!$||u(Y1(k.clientX-h.current.dx,k.clientY-h.current.dy,$))},E=()=>{h.current=null},S=k=>{const $=a.current?.getBoundingClientRect();!$||k.button!==0||(k.currentTarget.setPointerCapture(k.pointerId),u({left:$.left,top:$.top}),m.current={x:k.clientX,width:$.width})},C=k=>{const $=a.current?.getBoundingClientRect();if(!m.current||!$)return;const A=m.current.width+k.clientX-m.current.x,D=window.innerWidth-$.left-Sm;p(Math.max(l7,Math.min(A,D)))},R=()=>{m.current=null};return Ee.createElement("div",{ref:a,className:"bg-base border-muted fixed flex max-w-[calc(100vw-32px)] flex-col rounded-lg border shadow-lg",style:{zIndex:1e3,width:d,...l??{right:Sm,bottom:Sm}},"data-testid":"container_device-screen"},Ee.createElement("div",{className:"flex cursor-move items-center gap-8 px-12 py-8 select-none",style:{touchAction:"none"},onPointerDown:y,onPointerMove:w,onPointerUp:E,onPointerCancel:E},Ee.createElement(t.icon,{size:16}),Ee.createElement("span",{className:"body-3-semi-bold text-base flex-1"},e),Ee.createElement(sr,{appearance:"no-background",size:"xs",icon:r?Od:zs,"aria-label":r?"Expand device screen":"Collapse device screen",onClick:n,"data-testid":"button_toggle-device-screen"})),r?null:Ee.createElement(Ee.Fragment,null,Ee.createElement("div",{className:"flex flex-col gap-8 px-12 pb-12"},o),Ee.createElement("div",{className:"group absolute top-0 right-[-6px] bottom-0 flex w-[12px] cursor-ew-resize items-center justify-center",style:{touchAction:"none"},onPointerDown:S,onPointerMove:C,onPointerUp:R,onPointerCancel:R,"aria-hidden":!0,"data-testid":"handle_resize-device-screen"},Ee.createElement("span",{className:"border-muted bg-base group-hover:bg-muted group-active:bg-muted h-40 w-[6px] rounded-full border transition-colors"}))))};function K1(e,t,r){switch(e.kind){case"loading":return Ee.createElement(Bv,null,Ee.createElement("div",{className:`${t.lightScreen?"bg-white text-black":"bg-black text-white"} flex items-center justify-center`,style:{aspectRatio:t.screenWidth/t.screenHeight},"data-testid":"placeholder_device-screen-loading"},Ee.createElement("span",{className:"animate-pulse opacity-60"},Ee.createElement(t.icon,{size:32}))));case"error":return Ee.createElement(ig,{appearance:"error",title:"Screen unavailable",description:e.message});case"os-info":return Ee.createElement(Ee.Fragment,null,Ee.createElement(r7,{device:e.device,model:t,onOpenApp:t.speculos?r.openApp:void 0}),t.speculos?null:Ee.createElement(ig,{appearance:"info",title:"No screen to capture",description:`Speculos has no emulator for the ${t.label}, so this device is mocked all the way through and has no screen.`,"data-testid":"banner_device-screen-no-emulator"}));case"image":return Ee.createElement(Ee.Fragment,null,Ee.createElement(o7,{src:e.src,onTouch:t.touch?e.input.touch:void 0}),t.touch?null:Ee.createElement(i7,{onPress:e.input.pressButton}))}}const Em=Bt.interface({id:at,prefix:at,responses:Yr(at)}),f7=Bt.interface({prefix:at,response:zt(at),responses:zt(Yr(at))}),$_=Bt.interface({name:at,version:at,hash:zt(at)}),p7=Bt.interface({hash:at,name:at,version:at}),Is=Bt.interface({id:at,name:at,device_type:at,connectivity_type:at,firmware_version:zt(at),apps:zt(Yr($_)),masks:zt(Yr(Mo)),connected:zt(vd),onboarded:zt(vd),language:zt(at)}),h7=Bt.interface({id:zt(at),name:zt(at),device_type:zt(at),connectivity_type:zt(at),firmware_version:zt(at),apps:zt(Yr($_)),masks:zt(Yr(Mo)),mocks:zt(Yr(f7)),catalog:zt(Yr(p7)),onboarded:zt(vd),language:zt(at)}),m7=Bt.interface({token:at,expires_at:Mo}),g7=Bt.interface({device:Is,connected:vd}),v7=Bt.interface({response:at}),y7=Bt.interface({status:at,sessions:Mo}),b7=Bt.interface({id:at,created_at:Mo,expires_at:Mo,devices:Yr(Is)}),Q1=Bt.interface({devices:Yr(h7)}),x7=Bt.interface({run_id:at,speculos_url:at,model:at});let w7=class{client;timeoutMs;token;authPromise;constructor(t,r={}){this.client=r.httpClient??new d_({baseUrl:this.normalizeUrl(t)}),this.token=r.token,this.timeoutMs=r.timeoutMs}async getHealth(){const t=await this.client.get("health",this.requestConfig());return this.decode(y7,t)}async authenticate(){const t=await this.client.post("auth",{},this.requestConfig()),r=this.decode(m7,t).token;return this.token=r,r}getToken(){return this.token}async listDevices(){const t=await this.client.get("devices",await this.authRequestConfig());return this.decode(Yr(Is),t)}async addDevice(t={}){const r=await this.client.post("devices",t,await this.authRequestConfig());return this.decode(Is,r)}async getDevice(t){const r=await this.client.get(`devices/${t}`,await this.authRequestConfig());return this.decode(Is,r)}async editDevice(t,r){const n=await this.client.patch(`devices/${t}`,r,await this.authRequestConfig());return this.decode(Is,n)}async deleteDevice(t){return await this.client.delete(`devices/${t}`,await this.authRequestConfig()),!0}async connect(t){const r=await this.client.post(`devices/${t}/connect`,{},await this.authRequestConfig());return this.decode(g7,r)}async disconnect(t){return await this.client.post(`devices/${t}/disconnect`,{},await this.authRequestConfig()),!0}async disconnectAll(){const t=await this.listDevices();return await Promise.all(t.filter(r=>r.connected).map(r=>this.disconnect(r.id))),!0}async sendApdu(t,r){const n=typeof r=="string"?r:si(r,!1),o=await this.client.post(`devices/${t}/apdu`,{apdu:n},await this.authRequestConfig());return this.decode(v7,o)}async listMocks(t){const r=await this.client.get(`devices/${t}/mocks`,await this.authRequestConfig());return this.decode(Yr(Em),r)}async addMock(t,r){const n=await this.client.post(`devices/${t}/mocks`,r,await this.authRequestConfig());return this.decode(Em,n)}async editMock(t,r,n){const o=await this.client.patch(`devices/${t}/mocks/${r}`,n,await this.authRequestConfig());return this.decode(Em,o)}async deleteMock(t,r){return await this.client.delete(`devices/${t}/mocks/${r}`,await this.authRequestConfig()),!0}async clearMocks(t){return await this.client.delete(`devices/${t}/mocks`,await this.authRequestConfig()),!0}async getSpeculos(t){const r=await this.client.get(`devices/${t}/speculos`,await this.authRequestConfig());return this.decode(x7,r)}async getScreenshot(t){return await this.client.get(`devices/${t}/speculos/screenshot`,{...await this.authRequestConfig(),responseType:"blob"})}async pressButton(t,r,n="press-and-release"){await this.client.post(`devices/${t}/speculos/button/${r}`,{action:n},await this.authRequestConfig())}async touchScreen(t,r,n,o="press-and-release"){await this.client.post(`devices/${t}/speculos/finger`,{action:o,x:r,y:n},await this.authRequestConfig())}async getSession(){const t=await this.client.get("sessions/current",await this.authRequestConfig());return this.decode(b7,t)}async setSeed(t){await this.client.put("sessions/current/seed",{seed:t},await this.authRequestConfig())}async disposeSession(){return await this.client.delete("sessions/current",await this.authRequestConfig()),this.token=void 0,this.authPromise=void 0,!0}async exportSession(){const t=await this.client.get("export",await this.authRequestConfig());return this.decode(Q1,t)}async importSession(t){const r=await this.client.post("import",t,await this.authRequestConfig());return this.decode(Q1,r)}decode(t,r){return t.decode(r).caseOf({Left:n=>{throw new Error(`MockClient: invalid server response (${n})`)},Right:n=>n})}requestConfig(){return{timeoutMs:this.timeoutMs}}async authRequestConfig(){const t=await this.ensureToken();return{...this.requestConfig(),headers:{Authorization:`Bearer ${t}`}}}ensureToken(){return this.token?Promise.resolve(this.token):(this.authPromise||(this.authPromise=this.authenticate()),this.authPromise)}normalizeUrl(t){return t.endsWith("/")?t:`${t}/`}};const S7=({url:e,token:t,deviceId:r,...n})=>{const o=x.useMemo(()=>new w7(e,{token:t}),[e,t]),a=x.useMemo(()=>DU(o,r),[o,r]),l=FU(o,r);return l===void 0?null:Ee.createElement(u7,{api:a,deviceType:l?.device_type??"",firmwareVersion:l?.firmware_version,...n})},E7=({mockServer:e,rewriteUrl:t,deviceId:r})=>v.jsx(Dv,{name:"live-screen",defaultWidth:320,minWidth:240,maxWidth:640,edge:"left",className:"border-l border-muted-subtle bg-surface",children:v.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-16 overflow-auto p-16",children:[v.jsx("span",{className:"body-4-semi-bold text-muted uppercase",children:"Live screen"}),e?.sessionToken?v.jsx(S7,{url:t?t(e.url):e.url,token:e.sessionToken,deviceId:r}):v.jsx("p",{className:"rounded-lg border border-dashed border-muted-subtle p-24 text-center body-3 text-muted",children:e?"The app shares its mock server without a session token, so the device screen cannot be reached.":"Pass mockServer to DevToolsDmkInspector to see the device screen."})]})}),C7=`import { DevToolsDmkInspector } from "@ledgerhq/device-management-kit-devtools-core";
|
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-20261119133251","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-20261119133251"
|
|
6
6
|
},
|
|
7
7
|
"description": "Inspect and debug your integration of the Device Management Kit",
|
|
8
8
|
"devDependencies": {
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"tailwindcss": "^4.1.17",
|
|
19
19
|
"typescript": "5.9.2",
|
|
20
20
|
"vite": "7.3.7",
|
|
21
|
-
"@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-
|
|
21
|
+
"@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-20261119133251"
|
|
22
22
|
},
|
|
23
23
|
"files": [
|
|
24
24
|
"./dist"
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"peerDependencies": {
|
|
31
31
|
"react": "*",
|
|
32
32
|
"react-native": "*",
|
|
33
|
-
"@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-
|
|
33
|
+
"@ledgerhq/device-management-kit-devtools-core": "0.0.0-develop-20261119133251"
|
|
34
34
|
},
|
|
35
35
|
"private": false,
|
|
36
36
|
"repository": {
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
},
|
|
40
40
|
"type": "module",
|
|
41
41
|
"types": "./dist/react-native.d.ts",
|
|
42
|
-
"version": "0.0.0-develop-
|
|
42
|
+
"version": "0.0.0-develop-20261119133251",
|
|
43
43
|
"scripts": {
|
|
44
44
|
"build": "rozenite build",
|
|
45
45
|
"dev": "rozenite dev"
|