@ledgerhq/device-management-kit 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/README.md +114 -0
  2. package/lib/cjs/package.json +1 -1
  3. package/lib/cjs/src/api/DeviceManagementKit.js +1 -1
  4. package/lib/cjs/src/api/DeviceManagementKit.js.map +2 -2
  5. package/lib/cjs/src/api/command/os/GetBackgroundImageSizeCommand.js +2 -0
  6. package/lib/cjs/src/api/command/os/GetBackgroundImageSizeCommand.js.map +7 -0
  7. package/lib/cjs/src/api/command/os/GetBackgroundImageSizeCommand.test.js +2 -0
  8. package/lib/cjs/src/api/command/os/GetBackgroundImageSizeCommand.test.js.map +7 -0
  9. package/lib/cjs/src/api/device-action/DeviceAction.js +1 -1
  10. package/lib/cjs/src/api/device-action/DeviceAction.js.map +1 -1
  11. package/lib/cjs/src/api/device-action/__test-utils__/makeInternalApi.js +1 -1
  12. package/lib/cjs/src/api/device-action/__test-utils__/makeInternalApi.js.map +3 -3
  13. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js +1 -1
  14. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  15. package/lib/cjs/src/api/device-action/task/GetFirmwareMetadataTask.js +1 -1
  16. package/lib/cjs/src/api/device-action/task/GetFirmwareMetadataTask.js.map +3 -3
  17. package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
  18. package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +3 -3
  19. package/lib/cjs/src/api/index.js +1 -1
  20. package/lib/cjs/src/api/index.js.map +3 -3
  21. package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.js +2 -0
  22. package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.js.map +7 -0
  23. package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.test.js +2 -0
  24. package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.test.js.map +7 -0
  25. package/lib/cjs/src/api/logger-subscriber/model/LogSubscriberOptions.js +1 -1
  26. package/lib/cjs/src/api/logger-subscriber/model/LogSubscriberOptions.js.map +1 -1
  27. package/lib/cjs/src/api/logger-subscriber/service/ConsoleLogger.js +1 -1
  28. package/lib/cjs/src/api/logger-subscriber/service/ConsoleLogger.js.map +2 -2
  29. package/lib/cjs/src/api/logger-subscriber/service/ConsoleLogger.test.js +1 -1
  30. package/lib/cjs/src/api/logger-subscriber/service/ConsoleLogger.test.js.map +2 -2
  31. package/lib/cjs/src/api/logger-subscriber/service/DefaultLogTagFormatter.js +2 -0
  32. package/lib/cjs/src/api/logger-subscriber/service/DefaultLogTagFormatter.js.map +7 -0
  33. package/lib/cjs/src/api/logger-subscriber/service/DefaultLogTagFormatter.test.js +2 -0
  34. package/lib/cjs/src/api/logger-subscriber/service/DefaultLogTagFormatter.test.js.map +7 -0
  35. package/lib/cjs/src/api/logger-subscriber/service/LogTagFormatter.js +2 -0
  36. package/lib/cjs/src/api/logger-subscriber/service/LogTagFormatter.js.map +7 -0
  37. package/lib/cjs/src/api/logger-subscriber/service/WebLogsExporterLogger.test.js +1 -1
  38. package/lib/cjs/src/api/logger-subscriber/service/WebLogsExporterLogger.test.js.map +2 -2
  39. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  40. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
  41. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  42. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js.map +3 -3
  43. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.test.js +1 -1
  44. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.test.js.map +3 -3
  45. package/lib/cjs/src/api/transport/model/Errors.js +1 -1
  46. package/lib/cjs/src/api/transport/model/Errors.js.map +3 -3
  47. package/lib/cjs/src/internal/device-session/di/deviceSessionModule.js +1 -1
  48. package/lib/cjs/src/internal/device-session/di/deviceSessionModule.js.map +3 -3
  49. package/lib/cjs/src/internal/device-session/di/deviceSessionTypes.js +1 -1
  50. package/lib/cjs/src/internal/device-session/di/deviceSessionTypes.js.map +2 -2
  51. package/lib/cjs/src/internal/device-session/model/DevicePinger.js +1 -1
  52. package/lib/cjs/src/internal/device-session/model/DevicePinger.js.map +2 -2
  53. package/lib/cjs/src/internal/device-session/model/DevicePinger.test.js +1 -1
  54. package/lib/cjs/src/internal/device-session/model/DevicePinger.test.js.map +2 -2
  55. package/lib/cjs/src/internal/device-session/model/DeviceSession.js +1 -1
  56. package/lib/cjs/src/internal/device-session/model/DeviceSession.js.map +3 -3
  57. package/lib/cjs/src/internal/device-session/model/DeviceSession.test.js +2 -0
  58. package/lib/cjs/src/internal/device-session/model/DeviceSession.test.js.map +7 -0
  59. package/lib/cjs/src/internal/device-session/model/DeviceSessionEventDispatcher.js +1 -1
  60. package/lib/cjs/src/internal/device-session/model/DeviceSessionEventDispatcher.js.map +2 -2
  61. package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.js +1 -1
  62. package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.js.map +3 -3
  63. package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.test.js +1 -1
  64. package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.test.js.map +2 -2
  65. package/lib/cjs/src/internal/device-session/model/DeviceSessionStateHandler.js +1 -1
  66. package/lib/cjs/src/internal/device-session/model/DeviceSessionStateHandler.js.map +3 -3
  67. package/lib/cjs/src/internal/device-session/model/DeviceSessionStateHandler.test.js +1 -1
  68. package/lib/cjs/src/internal/device-session/model/DeviceSessionStateHandler.test.js.map +2 -2
  69. package/lib/cjs/src/internal/device-session/service/IntentQueueService.js +2 -0
  70. package/lib/cjs/src/internal/device-session/service/IntentQueueService.js.map +7 -0
  71. package/lib/cjs/src/internal/device-session/service/IntentQueueService.test.js +2 -0
  72. package/lib/cjs/src/internal/device-session/service/IntentQueueService.test.js.map +7 -0
  73. package/lib/cjs/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.js +2 -0
  74. package/lib/cjs/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.js.map +7 -0
  75. package/lib/cjs/src/internal/discovery/use-case/ConnectUseCase.js +1 -1
  76. package/lib/cjs/src/internal/discovery/use-case/ConnectUseCase.js.map +3 -3
  77. package/lib/cjs/src/internal/discovery/use-case/ConnectUseCase.test.js +1 -1
  78. package/lib/cjs/src/internal/discovery/use-case/ConnectUseCase.test.js.map +3 -3
  79. package/lib/cjs/src/internal/logger-publisher/service/DefaultLoggerPublisherService.js +1 -1
  80. package/lib/cjs/src/internal/logger-publisher/service/DefaultLoggerPublisherService.js.map +3 -3
  81. package/lib/cjs/src/internal/logger-publisher/service/DefaultLoggerPublisherService.test.js +1 -1
  82. package/lib/cjs/src/internal/logger-publisher/service/DefaultLoggerPublisherService.test.js.map +3 -3
  83. package/lib/cjs/src/internal/logger-publisher/service/sanitiseData.js +2 -0
  84. package/lib/cjs/src/internal/logger-publisher/service/sanitiseData.js.map +7 -0
  85. package/lib/cjs/src/internal/logger-publisher/service/sanitiseData.test.js +2 -0
  86. package/lib/cjs/src/internal/logger-publisher/service/sanitiseData.test.js.map +7 -0
  87. package/lib/cjs/src/internal/send/use-case/SendApduUseCase.test.js +1 -1
  88. package/lib/cjs/src/internal/send/use-case/SendApduUseCase.test.js.map +3 -3
  89. package/lib/esm/package.json +1 -1
  90. package/lib/esm/src/api/DeviceManagementKit.js +1 -1
  91. package/lib/esm/src/api/DeviceManagementKit.js.map +2 -2
  92. package/lib/esm/src/api/command/os/GetBackgroundImageSizeCommand.js +2 -0
  93. package/lib/esm/src/api/command/os/GetBackgroundImageSizeCommand.js.map +7 -0
  94. package/lib/esm/src/api/command/os/GetBackgroundImageSizeCommand.test.js +2 -0
  95. package/lib/esm/src/api/command/os/GetBackgroundImageSizeCommand.test.js.map +7 -0
  96. package/lib/esm/src/api/device-action/__test-utils__/makeInternalApi.js +1 -1
  97. package/lib/esm/src/api/device-action/__test-utils__/makeInternalApi.js.map +3 -3
  98. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js +1 -1
  99. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  100. package/lib/esm/src/api/device-action/task/GetFirmwareMetadataTask.js +1 -1
  101. package/lib/esm/src/api/device-action/task/GetFirmwareMetadataTask.js.map +3 -3
  102. package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
  103. package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +3 -3
  104. package/lib/esm/src/api/index.js +1 -1
  105. package/lib/esm/src/api/index.js.map +3 -3
  106. package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.js +2 -0
  107. package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.js.map +7 -0
  108. package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.test.js +2 -0
  109. package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.test.js.map +7 -0
  110. package/lib/esm/src/api/logger-subscriber/service/ConsoleLogger.js +1 -1
  111. package/lib/esm/src/api/logger-subscriber/service/ConsoleLogger.js.map +2 -2
  112. package/lib/esm/src/api/logger-subscriber/service/ConsoleLogger.test.js +1 -1
  113. package/lib/esm/src/api/logger-subscriber/service/ConsoleLogger.test.js.map +2 -2
  114. package/lib/esm/src/api/logger-subscriber/service/DefaultLogTagFormatter.js +2 -0
  115. package/lib/esm/src/api/logger-subscriber/service/DefaultLogTagFormatter.js.map +7 -0
  116. package/lib/esm/src/api/logger-subscriber/service/DefaultLogTagFormatter.test.js +2 -0
  117. package/lib/esm/src/api/logger-subscriber/service/DefaultLogTagFormatter.test.js.map +7 -0
  118. package/lib/esm/src/api/logger-subscriber/service/LogTagFormatter.js +1 -0
  119. package/lib/esm/src/api/logger-subscriber/service/LogTagFormatter.js.map +7 -0
  120. package/lib/esm/src/api/logger-subscriber/service/WebLogsExporterLogger.test.js +1 -1
  121. package/lib/esm/src/api/logger-subscriber/service/WebLogsExporterLogger.test.js.map +3 -3
  122. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  123. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
  124. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  125. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js.map +3 -3
  126. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.test.js +1 -1
  127. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.test.js.map +3 -3
  128. package/lib/esm/src/api/transport/model/Errors.js +1 -1
  129. package/lib/esm/src/api/transport/model/Errors.js.map +3 -3
  130. package/lib/esm/src/internal/device-session/di/deviceSessionModule.js +1 -1
  131. package/lib/esm/src/internal/device-session/di/deviceSessionModule.js.map +3 -3
  132. package/lib/esm/src/internal/device-session/di/deviceSessionTypes.js +1 -1
  133. package/lib/esm/src/internal/device-session/di/deviceSessionTypes.js.map +2 -2
  134. package/lib/esm/src/internal/device-session/model/DevicePinger.js +1 -1
  135. package/lib/esm/src/internal/device-session/model/DevicePinger.js.map +2 -2
  136. package/lib/esm/src/internal/device-session/model/DevicePinger.test.js +1 -1
  137. package/lib/esm/src/internal/device-session/model/DevicePinger.test.js.map +2 -2
  138. package/lib/esm/src/internal/device-session/model/DeviceSession.js +1 -1
  139. package/lib/esm/src/internal/device-session/model/DeviceSession.js.map +3 -3
  140. package/lib/esm/src/internal/device-session/model/DeviceSession.test.js +2 -0
  141. package/lib/esm/src/internal/device-session/model/DeviceSession.test.js.map +7 -0
  142. package/lib/esm/src/internal/device-session/model/DeviceSessionEventDispatcher.js +1 -1
  143. package/lib/esm/src/internal/device-session/model/DeviceSessionEventDispatcher.js.map +2 -2
  144. package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.js +1 -1
  145. package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.js.map +3 -3
  146. package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.test.js +1 -1
  147. package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.test.js.map +2 -2
  148. package/lib/esm/src/internal/device-session/model/DeviceSessionStateHandler.js +1 -1
  149. package/lib/esm/src/internal/device-session/model/DeviceSessionStateHandler.js.map +3 -3
  150. package/lib/esm/src/internal/device-session/model/DeviceSessionStateHandler.test.js +1 -1
  151. package/lib/esm/src/internal/device-session/model/DeviceSessionStateHandler.test.js.map +2 -2
  152. package/lib/esm/src/internal/device-session/service/IntentQueueService.js +2 -0
  153. package/lib/esm/src/internal/device-session/service/IntentQueueService.js.map +7 -0
  154. package/lib/esm/src/internal/device-session/service/IntentQueueService.test.js +2 -0
  155. package/lib/esm/src/internal/device-session/service/IntentQueueService.test.js.map +7 -0
  156. package/lib/esm/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.js +2 -0
  157. package/lib/esm/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.js.map +7 -0
  158. package/lib/esm/src/internal/discovery/use-case/ConnectUseCase.js +1 -1
  159. package/lib/esm/src/internal/discovery/use-case/ConnectUseCase.js.map +3 -3
  160. package/lib/esm/src/internal/discovery/use-case/ConnectUseCase.test.js +1 -1
  161. package/lib/esm/src/internal/discovery/use-case/ConnectUseCase.test.js.map +3 -3
  162. package/lib/esm/src/internal/logger-publisher/service/DefaultLoggerPublisherService.js +1 -1
  163. package/lib/esm/src/internal/logger-publisher/service/DefaultLoggerPublisherService.js.map +3 -3
  164. package/lib/esm/src/internal/logger-publisher/service/DefaultLoggerPublisherService.test.js +1 -1
  165. package/lib/esm/src/internal/logger-publisher/service/DefaultLoggerPublisherService.test.js.map +3 -3
  166. package/lib/esm/src/internal/logger-publisher/service/sanitiseData.js +2 -0
  167. package/lib/esm/src/internal/logger-publisher/service/sanitiseData.js.map +7 -0
  168. package/lib/esm/src/internal/logger-publisher/service/sanitiseData.test.js +2 -0
  169. package/lib/esm/src/internal/logger-publisher/service/sanitiseData.test.js.map +7 -0
  170. package/lib/esm/src/internal/send/use-case/SendApduUseCase.test.js +1 -1
  171. package/lib/esm/src/internal/send/use-case/SendApduUseCase.test.js.map +3 -3
  172. package/lib/types/src/api/DeviceManagementKit.d.ts +10 -0
  173. package/lib/types/src/api/DeviceManagementKit.d.ts.map +1 -1
  174. package/lib/types/src/api/command/os/GetBackgroundImageSizeCommand.d.ts +17 -0
  175. package/lib/types/src/api/command/os/GetBackgroundImageSizeCommand.d.ts.map +1 -0
  176. package/lib/types/src/api/command/os/GetBackgroundImageSizeCommand.test.d.ts +2 -0
  177. package/lib/types/src/api/command/os/GetBackgroundImageSizeCommand.test.d.ts.map +1 -0
  178. package/lib/types/src/api/device-action/DeviceAction.d.ts +2 -1
  179. package/lib/types/src/api/device-action/DeviceAction.d.ts.map +1 -1
  180. package/lib/types/src/api/device-action/__test-utils__/makeInternalApi.d.ts.map +1 -1
  181. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts +4 -1
  182. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts.map +1 -1
  183. package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts +13 -0
  184. package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts.map +1 -1
  185. package/lib/types/src/api/index.d.ts +9 -2
  186. package/lib/types/src/api/index.d.ts.map +1 -1
  187. package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.d.ts +12 -0
  188. package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.d.ts.map +1 -0
  189. package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.test.d.ts +2 -0
  190. package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.test.d.ts.map +1 -0
  191. package/lib/types/src/api/logger-subscriber/model/LogSubscriberOptions.d.ts +1 -0
  192. package/lib/types/src/api/logger-subscriber/model/LogSubscriberOptions.d.ts.map +1 -1
  193. package/lib/types/src/api/logger-subscriber/service/DefaultLogTagFormatter.d.ts +10 -0
  194. package/lib/types/src/api/logger-subscriber/service/DefaultLogTagFormatter.d.ts.map +1 -0
  195. package/lib/types/src/api/logger-subscriber/service/DefaultLogTagFormatter.test.d.ts +2 -0
  196. package/lib/types/src/api/logger-subscriber/service/DefaultLogTagFormatter.test.d.ts.map +1 -0
  197. package/lib/types/src/api/logger-subscriber/service/LogTagFormatter.d.ts +9 -0
  198. package/lib/types/src/api/logger-subscriber/service/LogTagFormatter.d.ts.map +1 -0
  199. package/lib/types/src/api/secure-channel/task/ConnectToSecureChannelTask.d.ts.map +1 -1
  200. package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.d.ts +1 -0
  201. package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.d.ts.map +1 -1
  202. package/lib/types/src/api/transport/model/Errors.d.ts +5 -0
  203. package/lib/types/src/api/transport/model/Errors.d.ts.map +1 -1
  204. package/lib/types/src/internal/device-session/di/deviceSessionModule.d.ts.map +1 -1
  205. package/lib/types/src/internal/device-session/di/deviceSessionTypes.d.ts +1 -0
  206. package/lib/types/src/internal/device-session/di/deviceSessionTypes.d.ts.map +1 -1
  207. package/lib/types/src/internal/device-session/model/DeviceSession.d.ts +13 -2
  208. package/lib/types/src/internal/device-session/model/DeviceSession.d.ts.map +1 -1
  209. package/lib/types/src/internal/device-session/model/DeviceSession.test.d.ts +2 -0
  210. package/lib/types/src/internal/device-session/model/DeviceSession.test.d.ts.map +1 -0
  211. package/lib/types/src/internal/device-session/model/DeviceSessionEventDispatcher.d.ts +3 -1
  212. package/lib/types/src/internal/device-session/model/DeviceSessionEventDispatcher.d.ts.map +1 -1
  213. package/lib/types/src/internal/device-session/model/DeviceSessionRefresher.d.ts +0 -1
  214. package/lib/types/src/internal/device-session/model/DeviceSessionRefresher.d.ts.map +1 -1
  215. package/lib/types/src/internal/device-session/model/DeviceSessionStateHandler.d.ts +1 -0
  216. package/lib/types/src/internal/device-session/model/DeviceSessionStateHandler.d.ts.map +1 -1
  217. package/lib/types/src/internal/device-session/service/IntentQueueService.d.ts +101 -0
  218. package/lib/types/src/internal/device-session/service/IntentQueueService.d.ts.map +1 -0
  219. package/lib/types/src/internal/device-session/service/IntentQueueService.test.d.ts +2 -0
  220. package/lib/types/src/internal/device-session/service/IntentQueueService.test.d.ts.map +1 -0
  221. package/lib/types/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.d.ts +19 -0
  222. package/lib/types/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.d.ts.map +1 -0
  223. package/lib/types/src/internal/discovery/use-case/ConnectUseCase.d.ts.map +1 -1
  224. package/lib/types/src/internal/logger-publisher/service/DefaultLoggerPublisherService.d.ts +5 -2
  225. package/lib/types/src/internal/logger-publisher/service/DefaultLoggerPublisherService.d.ts.map +1 -1
  226. package/lib/types/src/internal/logger-publisher/service/sanitiseData.d.ts +6 -0
  227. package/lib/types/src/internal/logger-publisher/service/sanitiseData.d.ts.map +1 -0
  228. package/lib/types/src/internal/logger-publisher/service/sanitiseData.test.d.ts +2 -0
  229. package/lib/types/src/internal/logger-publisher/service/sanitiseData.test.d.ts.map +1 -0
  230. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  231. package/package.json +4 -4
  232. package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.js +0 -2
  233. package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.js.map +0 -7
  234. package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.test.js +0 -2
  235. package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.test.js.map +0 -7
  236. package/lib/cjs/src/internal/device-session/service/MutexService.js +0 -2
  237. package/lib/cjs/src/internal/device-session/service/MutexService.js.map +0 -7
  238. package/lib/cjs/src/internal/device-session/service/MutexService.test.js +0 -2
  239. package/lib/cjs/src/internal/device-session/service/MutexService.test.js.map +0 -7
  240. package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.js +0 -2
  241. package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.js.map +0 -7
  242. package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.test.js +0 -2
  243. package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.test.js.map +0 -7
  244. package/lib/esm/src/internal/device-session/service/MutexService.js +0 -2
  245. package/lib/esm/src/internal/device-session/service/MutexService.js.map +0 -7
  246. package/lib/esm/src/internal/device-session/service/MutexService.test.js +0 -2
  247. package/lib/esm/src/internal/device-session/service/MutexService.test.js.map +0 -7
  248. package/lib/types/src/api/command/os/GetCustomImageSizeCommand.d.ts +0 -17
  249. package/lib/types/src/api/command/os/GetCustomImageSizeCommand.d.ts.map +0 -1
  250. package/lib/types/src/api/command/os/GetCustomImageSizeCommand.test.d.ts +0 -2
  251. package/lib/types/src/api/command/os/GetCustomImageSizeCommand.test.d.ts.map +0 -1
  252. package/lib/types/src/internal/device-session/service/MutexService.d.ts +0 -6
  253. package/lib/types/src/internal/device-session/service/MutexService.d.ts.map +0 -1
  254. package/lib/types/src/internal/device-session/service/MutexService.test.d.ts +0 -2
  255. package/lib/types/src/internal/device-session/service/MutexService.test.d.ts.map +0 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/logger-subscriber/service/ConsoleLogger.test.ts"],
4
- "sourcesContent": ["import { LogLevel } from \"@api/logger-subscriber/model/LogLevel\";\nimport { type LogSubscriberOptions } from \"@api/logger-subscriber/model/LogSubscriberOptions\";\n\nimport { ConsoleLogger } from \"./ConsoleLogger\";\n\nconst warn = vi.spyOn(console, \"warn\").mockImplementation(vi.fn());\nconst info = vi.spyOn(console, \"info\").mockImplementation(vi.fn());\nconst debug = vi.spyOn(console, \"debug\").mockImplementation(vi.fn());\nconst error = vi.spyOn(console, \"error\").mockImplementation(vi.fn());\nconst log = vi.spyOn(console, \"log\").mockImplementation(vi.fn());\n\nlet logger: ConsoleLogger;\nconst options: LogSubscriberOptions = {\n data: { key: \"value\" },\n timestamp: 1,\n tag: \"tag\",\n};\nconst message = \"message\";\n\ndescribe(\"ConsoleLogger\", () => {\n afterAll(() => {\n vi.restoreAllMocks();\n });\n\n describe(\"default level (LogLevel.DEBUG)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger();\n });\n\n describe(\"log\", () => {\n it(\"should log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Info level with a custom tag\", () => {\n const tag = \"custom-tag\";\n logger.log(LogLevel.Info, message, { ...options, tag });\n expect(info).toHaveBeenCalledWith(`[${tag}]`, message, options.data);\n });\n\n it(\"should log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should default to Log level if none present\", () => {\n logger.log(null, message, options);\n expect(log).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Error level\", () => {\n logger.log(LogLevel.Error, message, options);\n expect(error).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n });\n });\n\n describe(\"custom level (LogLevel.Info)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger(LogLevel.Info);\n });\n\n describe(\"log\", () => {\n it(\"should log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Info level with a custom tag\", () => {\n const tag = \"custom-tag\";\n logger.log(LogLevel.Info, message, { ...options, tag });\n expect(info).toHaveBeenCalledWith(`[${tag}]`, message, options.data);\n });\n\n it(\"should log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should not log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).not.toHaveBeenCalled();\n });\n\n it(\"should default to Log level if none present\", () => {\n logger.log(null, message, options);\n expect(log).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Error level\", () => {\n logger.log(LogLevel.Error, message, options);\n expect(error).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n });\n });\n\n describe(\"custom level (LogLevel.Warning)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger(LogLevel.Warning);\n });\n\n describe(\"log\", () => {\n it(\"should not log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).not.toHaveBeenCalled();\n });\n\n it(\"should log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should not log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).not.toHaveBeenCalled();\n });\n\n it(\"should default to Log level if none present\", () => {\n logger.log(null, message, options);\n expect(log).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Error level\", () => {\n logger.log(LogLevel.Error, message, options);\n expect(error).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n });\n });\n\n describe(\"custom level (LogLevel.Error)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger(LogLevel.Error);\n });\n\n describe(\"log\", () => {\n it(\"should not log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).not.toHaveBeenCalled();\n });\n\n it(\"should not log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).not.toHaveBeenCalled();\n });\n\n it(\"should not log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).not.toHaveBeenCalled();\n });\n\n it(\"should default to Log level if none present\", () => {\n logger.log(null, message, options);\n expect(log).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Error level\", () => {\n logger.log(LogLevel.Error, message, options);\n expect(error).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n });\n });\n\n describe(\"custom level (LogLevel.Fatal)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger(LogLevel.Fatal);\n });\n\n describe(\"log\", () => {\n it(\"should not log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).not.toHaveBeenCalled();\n });\n\n it(\"should not log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).not.toHaveBeenCalled();\n });\n\n it(\"should not log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).not.toHaveBeenCalled();\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(\n `[${options.tag}]`,\n message,\n options.data,\n );\n });\n });\n });\n});\n"],
5
- "mappings": "AAAA,OAAS,YAAAA,MAAgB,wCAGzB,OAAS,iBAAAC,MAAqB,kBAE9B,MAAMC,EAAO,GAAG,MAAM,QAAS,MAAM,E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yBAA0B,IAAM,CACjCD,EAAO,IAAIP,EAAS,MAAOS,EAASD,CAAO,EAC3C,OAAOH,CAAK,EAAE,qBACZ,IAAIG,EAAQ,GAAG,IACfC,EACAD,EAAQ,IACV,CACF,CAAC,CACH,CAAC,CACH,CAAC,EAED,SAAS,gCAAiC,IAAM,CAC9C,WAAW,IAAM,CACf,GAAG,cAAc,EACjBD,EAAS,IAAIN,EAAcD,EAAS,KAAK,CAC3C,CAAC,EAED,SAAS,MAAO,IAAM,CACpB,GAAG,4BAA6B,IAAM,CACpCO,EAAO,IAAIP,EAAS,KAAMS,EAASD,CAAO,EAC1C,OAAOL,CAAI,EAAE,IAAI,iBAAiB,CACpC,CAAC,EAED,GAAG,4BAA6B,IAAM,CACpCI,EAAO,IAAIP,EAAS,QAASS,EAASD,CAAO,EAC7C,OAAON,CAAI,EAAE,IAAI,iBAAiB,CACpC,CAAC,EAED,GAAG,6BAA8B,IAAM,CACrCK,EAAO,IAAIP,EAAS,MAAOS,EAASD,CAAO,EAC3C,OAAOJ,CAAK,EAAE,IAAI,iBAAiB,CACrC,CAAC,EAED,GAAG,yBAA0B,IAAM,CACjCG,EAAO,IAAIP,EAAS,MAAOS,EAASD,CAAO,EAC3C,OAAOH,CAAK,EAAE,qBACZ,IAAIG,EAAQ,GAAG,IACfC,EACAD,EAAQ,IACV,CACF,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
4
+ "sourcesContent": ["import { LogLevel } from \"@api/logger-subscriber/model/LogLevel\";\nimport { type LogSubscriberOptions } from \"@api/logger-subscriber/model/LogSubscriberOptions\";\n\nimport { ConsoleLogger } from \"./ConsoleLogger\";\n\nconst warn = vi.spyOn(console, \"warn\").mockImplementation(vi.fn());\nconst info = vi.spyOn(console, \"info\").mockImplementation(vi.fn());\nconst debug = vi.spyOn(console, \"debug\").mockImplementation(vi.fn());\nconst error = vi.spyOn(console, \"error\").mockImplementation(vi.fn());\nconst log = vi.spyOn(console, \"log\").mockImplementation(vi.fn());\n\nlet logger: ConsoleLogger;\n// Tags are pre-formatted by the publisher before reaching subscribers\nconst options: LogSubscriberOptions = {\n data: { key: \"value\" },\n timestamp: 1,\n tag: \"[tag]\",\n};\nconst message = \"message\";\n\ndescribe(\"ConsoleLogger\", () => {\n afterAll(() => {\n vi.restoreAllMocks();\n });\n\n describe(\"default level (LogLevel.DEBUG)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger();\n });\n\n describe(\"log\", () => {\n it(\"should log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Info level with a custom tag\", () => {\n const tag = \"[custom-tag]\";\n logger.log(LogLevel.Info, message, { ...options, tag });\n expect(info).toHaveBeenCalledWith(tag, message, options.data);\n });\n\n it(\"should log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should default to Log level if none present\", () => {\n logger.log(null, message, options);\n expect(log).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Error level\", () => {\n logger.log(LogLevel.Error, message, options);\n expect(error).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n });\n });\n\n describe(\"custom level (LogLevel.Info)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger(LogLevel.Info);\n });\n\n describe(\"log\", () => {\n it(\"should log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Info level with a custom tag\", () => {\n const tag = \"[custom-tag]\";\n logger.log(LogLevel.Info, message, { ...options, tag });\n expect(info).toHaveBeenCalledWith(tag, message, options.data);\n });\n\n it(\"should log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should not log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).not.toHaveBeenCalled();\n });\n\n it(\"should default to Log level if none present\", () => {\n logger.log(null, message, options);\n expect(log).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Error level\", () => {\n logger.log(LogLevel.Error, message, options);\n expect(error).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n });\n });\n\n describe(\"custom level (LogLevel.Warning)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger(LogLevel.Warning);\n });\n\n describe(\"log\", () => {\n it(\"should not log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).not.toHaveBeenCalled();\n });\n\n it(\"should log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should not log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).not.toHaveBeenCalled();\n });\n\n it(\"should default to Log level if none present\", () => {\n logger.log(null, message, options);\n expect(log).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Error level\", () => {\n logger.log(LogLevel.Error, message, options);\n expect(error).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n });\n });\n\n describe(\"custom level (LogLevel.Error)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger(LogLevel.Error);\n });\n\n describe(\"log\", () => {\n it(\"should not log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).not.toHaveBeenCalled();\n });\n\n it(\"should not log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).not.toHaveBeenCalled();\n });\n\n it(\"should not log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).not.toHaveBeenCalled();\n });\n\n it(\"should default to Log level if none present\", () => {\n logger.log(null, message, options);\n expect(log).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Error level\", () => {\n logger.log(LogLevel.Error, message, options);\n expect(error).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n });\n });\n\n describe(\"custom level (LogLevel.Fatal)\", () => {\n beforeEach(() => {\n vi.clearAllMocks();\n logger = new ConsoleLogger(LogLevel.Fatal);\n });\n\n describe(\"log\", () => {\n it(\"should not log Info level\", () => {\n logger.log(LogLevel.Info, message, options);\n expect(info).not.toHaveBeenCalled();\n });\n\n it(\"should not log Warn level\", () => {\n logger.log(LogLevel.Warning, message, options);\n expect(warn).not.toHaveBeenCalled();\n });\n\n it(\"should not log Debug level\", () => {\n logger.log(LogLevel.Debug, message, options);\n expect(debug).not.toHaveBeenCalled();\n });\n\n it(\"should log Fatal level\", () => {\n logger.log(LogLevel.Fatal, message, options);\n expect(error).toHaveBeenCalledWith(options.tag, message, options.data);\n });\n });\n });\n});\n"],
5
+ "mappings": "AAAA,OAAS,YAAAA,MAAgB,wCAGzB,OAAS,iBAAAC,MAAqB,kBAE9B,MAAMC,EAAO,GAAG,MAAM,QAAS,MAAM,EAAE,mBAAmB,GAAG,GAAG,CAAC,EAC3DC,EAAO,GAAG,MAAM,QAAS,MAAM,EAAE,mBAAmB,GAAG,GAAG,CAAC,EAC3DC,EAAQ,GAAG,MAAM,QAAS,OAAO,EAAE,mBAAmB,GAAG,GAAG,CAAC,EAC7DC,EAAQ,GAA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M,CACpCO,EAAO,IAAIP,EAAS,KAAMS,EAASD,CAAO,EAC1C,OAAOL,CAAI,EAAE,IAAI,iBAAiB,CACpC,CAAC,EAED,GAAG,4BAA6B,IAAM,CACpCI,EAAO,IAAIP,EAAS,QAASS,EAASD,CAAO,EAC7C,OAAON,CAAI,EAAE,IAAI,iBAAiB,CACpC,CAAC,EAED,GAAG,6BAA8B,IAAM,CACrCK,EAAO,IAAIP,EAAS,MAAOS,EAASD,CAAO,EAC3C,OAAOJ,CAAK,EAAE,IAAI,iBAAiB,CACrC,CAAC,EAED,GAAG,yBAA0B,IAAM,CACjCG,EAAO,IAAIP,EAAS,MAAOS,EAASD,CAAO,EAC3C,OAAOH,CAAK,EAAE,qBAAqBG,EAAQ,IAAKC,EAASD,EAAQ,IAAI,CACvE,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["LogLevel", "ConsoleLogger", "warn", "info", "debug", "error", "log", "logger", "options", "message", "tag"]
7
7
  }
@@ -0,0 +1,2 @@
1
+ class a{format(r){return Array.isArray(r)?r.map(o=>`[${o}]`).join(" "):`[${r}]`}}export{a as DefaultLogTagFormatter};
2
+ //# sourceMappingURL=DefaultLogTagFormatter.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/api/logger-subscriber/service/DefaultLogTagFormatter.ts"],
4
+ "sourcesContent": ["import { type LogTag } from \"@api/logger-subscriber/model/LogSubscriberOptions\";\n\nimport { type LogTagFormatter } from \"./LogTagFormatter\";\n\n/**\n * Default implementation of LogTagFormatter.\n * Formats tags as \"[tag1] [tag2] [tag3]\" for arrays, or \"[tag]\" for strings.\n */\nexport class DefaultLogTagFormatter implements LogTagFormatter {\n format(tag: LogTag): string {\n if (Array.isArray(tag)) {\n return tag.map((t) => `[${t}]`).join(\" \");\n }\n return `[${tag}]`;\n }\n}\n"],
5
+ "mappings": "AAQO,MAAMA,CAAkD,CAC7D,OAAOC,EAAqB,CAC1B,OAAI,MAAM,QAAQA,CAAG,EACZA,EAAI,IAAKC,GAAM,IAAIA,CAAC,GAAG,EAAE,KAAK,GAAG,EAEnC,IAAID,CAAG,GAChB,CACF",
6
+ "names": ["DefaultLogTagFormatter", "tag", "t"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{describe as r,expect as a,it as e}from"vitest";import{DefaultLogTagFormatter as o}from"./DefaultLogTagFormatter";r("DefaultLogTagFormatter",()=>{const t=new o;r("format",()=>{e("should format a single string tag with brackets",()=>{a(t.format("myTag")).toBe("[myTag]")}),e("should format an empty string tag with brackets",()=>{a(t.format("")).toBe("[]")}),e("should format a single element array with brackets",()=>{a(t.format(["myTag"])).toBe("[myTag]")}),e("should format multiple tags with brackets separated by spaces",()=>{a(t.format(["tag1","tag2","tag3"])).toBe("[tag1] [tag2] [tag3]")}),e("should format an empty array as empty string",()=>{a(t.format([])).toBe("")}),e("should handle tags with special characters",()=>{a(t.format(["SignerEth","ContextModule","loader"])).toBe("[SignerEth] [ContextModule] [loader]")})})});
2
+ //# sourceMappingURL=DefaultLogTagFormatter.test.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/api/logger-subscriber/service/DefaultLogTagFormatter.test.ts"],
4
+ "sourcesContent": ["import { describe, expect, it } from \"vitest\";\n\nimport { DefaultLogTagFormatter } from \"./DefaultLogTagFormatter\";\n\ndescribe(\"DefaultLogTagFormatter\", () => {\n const formatter = new DefaultLogTagFormatter();\n\n describe(\"format\", () => {\n it(\"should format a single string tag with brackets\", () => {\n expect(formatter.format(\"myTag\")).toBe(\"[myTag]\");\n });\n\n it(\"should format an empty string tag with brackets\", () => {\n expect(formatter.format(\"\")).toBe(\"[]\");\n });\n\n it(\"should format a single element array with brackets\", () => {\n expect(formatter.format([\"myTag\"])).toBe(\"[myTag]\");\n });\n\n it(\"should format multiple tags with brackets separated by spaces\", () => {\n expect(formatter.format([\"tag1\", \"tag2\", \"tag3\"])).toBe(\n \"[tag1] [tag2] [tag3]\",\n );\n });\n\n it(\"should format an empty array as empty string\", () => {\n expect(formatter.format([])).toBe(\"\");\n });\n\n it(\"should handle tags with special characters\", () => {\n expect(formatter.format([\"SignerEth\", \"ContextModule\", \"loader\"])).toBe(\n \"[SignerEth] [ContextModule] [loader]\",\n );\n });\n });\n});\n"],
5
+ "mappings": "AAAA,OAAS,YAAAA,EAAU,UAAAC,EAAQ,MAAAC,MAAU,SAErC,OAAS,0BAAAC,MAA8B,2BAEvCH,EAAS,yBAA0B,IAAM,CACvC,MAAMI,EAAY,IAAID,EAEtBH,EAAS,SAAU,IAAM,CACvBE,EAAG,kDAAmD,IAAM,CAC1DD,EAAOG,EAAU,OAAO,OAAO,CAAC,EAAE,KAAK,SAAS,CAClD,CAAC,EAEDF,EAAG,kDAAmD,IAAM,CAC1DD,EAAOG,EAAU,OAAO,EAAE,CAAC,EAAE,KAAK,IAAI,CACxC,CAAC,EAEDF,EAAG,qDAAsD,IAAM,CAC7DD,EAAOG,EAAU,OAAO,CAAC,OAAO,CAAC,CAAC,EAAE,KAAK,SAAS,CACpD,CAAC,EAEDF,EAAG,gEAAiE,IAAM,CACxED,EAAOG,EAAU,OAAO,CAAC,OAAQ,OAAQ,MAAM,CAAC,CAAC,EAAE,KACjD,sBACF,CACF,CAAC,EAEDF,EAAG,+CAAgD,IAAM,CACvDD,EAAOG,EAAU,OAAO,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CACtC,CAAC,EAEDF,EAAG,6CAA8C,IAAM,CACrDD,EAAOG,EAAU,OAAO,CAAC,YAAa,gBAAiB,QAAQ,CAAC,CAAC,EAAE,KACjE,sCACF,CACF,CAAC,CACH,CAAC,CACH,CAAC",
6
+ "names": ["describe", "expect", "it", "DefaultLogTagFormatter", "formatter"]
7
+ }
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=LogTagFormatter.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": [],
4
+ "sourcesContent": [],
5
+ "mappings": "",
6
+ "names": []
7
+ }
@@ -1,2 +1,2 @@
1
- import{deviceModelStubBuilder as n}from"../../device-model/model/DeviceModel.stub";import{DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS as a}from"../../../internal/device-session/data/DeviceSessionRefresherConst";import{DeviceSession as l}from"../../../internal/device-session/model/DeviceSession";import{getJSONStringifyReplacer as c}from"./WebLogsExporterLogger";describe("getJSONStringifyReplacer",()=>{it("should return a function that replaces Uint8Array correctly",()=>{const e=c(),t=new Uint8Array([1,2,3]),r=e("key",t);expect(r).toEqual({hex:"0x010203",readableHex:"01 02 03",value:"1,2,3"})}),it("should return a function that replaces DeviceSession",()=>{const e=n(),t=c(),r={deviceModel:n(),type:"USB",id:"mockedDeviceId",sendApdu:vi.fn(),transport:"USB"},i=new l({connectedDevice:r,id:"mockedSessionId"},vi.fn(),{},{},a),o=JSON.stringify(i,t),s=`{"id":"mockedSessionId","connectedDevice":{"deviceModel":${JSON.stringify(e)},"type":"USB","id":"mockedDeviceId"}}`;i.close(),expect(o).toEqual(s)}),it("should return a function that replaces circular references",()=>{const e={name:"Alice"};e.self=e;const t='{"name":"Alice","self":"[Circular]"}',r=JSON.stringify(e,c());expect(r).toEqual(t)})});
1
+ import{deviceModelStubBuilder as n}from"../../device-model/model/DeviceModel.stub";import{DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS as a}from"../../../internal/device-session/data/DeviceSessionRefresherConst";import{deviceSessionStubBuilder as l}from"../../../internal/device-session/model/DeviceSession.stub";import{getJSONStringifyReplacer as c}from"./WebLogsExporterLogger";describe("getJSONStringifyReplacer",()=>{it("should return a function that replaces Uint8Array correctly",()=>{const e=c(),t=new Uint8Array([1,2,3]),r=e("key",t);expect(r).toEqual({hex:"0x010203",readableHex:"01 02 03",value:"1,2,3"})}),it("should return a function that replaces DeviceSession",()=>{const e=n(),t=c(),r={deviceModel:n(),type:"USB",id:"mockedDeviceId",sendApdu:vi.fn(),transport:"USB"},i=l({connectedDevice:r,id:"mockedSessionId"},vi.fn(),{},{},a),o=JSON.stringify(i,t),s=`{"id":"mockedSessionId","connectedDevice":{"deviceModel":${JSON.stringify(e)},"type":"USB","id":"mockedDeviceId"}}`;i.close(),expect(o).toEqual(s)}),it("should return a function that replaces circular references",()=>{const e={name:"Alice"};e.self=e;const t='{"name":"Alice","self":"[Circular]"}',r=JSON.stringify(e,c());expect(r).toEqual(t)})});
2
2
  //# sourceMappingURL=WebLogsExporterLogger.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/logger-subscriber/service/WebLogsExporterLogger.test.ts"],
4
- "sourcesContent": ["import { deviceModelStubBuilder } from \"@api/device-model/model/DeviceModel.stub\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { DeviceSession } from \"@internal/device-session/model/DeviceSession\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { getJSONStringifyReplacer } from \"./WebLogsExporterLogger\";\n\ndescribe(\"getJSONStringifyReplacer\", () => {\n it(\"should return a function that replaces Uint8Array correctly\", () => {\n const replacer = getJSONStringifyReplacer();\n const value = new Uint8Array([1, 2, 3]);\n const result = replacer(\"key\", value);\n expect(result).toEqual({\n hex: \"0x010203\",\n readableHex: \"01 02 03\",\n value: \"1,2,3\",\n });\n });\n\n it(\"should return a function that replaces DeviceSession\", () => {\n const stubDeviceModel = deviceModelStubBuilder();\n const replacer = getJSONStringifyReplacer();\n\n const connectedDevice: TransportConnectedDevice = {\n deviceModel: deviceModelStubBuilder(),\n type: \"USB\",\n id: \"mockedDeviceId\",\n sendApdu: vi.fn(),\n transport: \"USB\",\n };\n\n const value = new DeviceSession(\n {\n connectedDevice,\n id: \"mockedSessionId\",\n },\n vi.fn(),\n {} as ManagerApiService,\n {} as SecureChannelService,\n DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n );\n const result = JSON.stringify(value, replacer);\n const expected = `{\"id\":\"mockedSessionId\",\"connectedDevice\":{\"deviceModel\":${JSON.stringify(\n stubDeviceModel,\n )},\"type\":\"USB\",\"id\":\"mockedDeviceId\"}}`;\n value.close();\n expect(result).toEqual(expected);\n });\n\n it(\"should return a function that replaces circular references\", () => {\n interface CircularObject {\n name: string;\n self?: CircularObject;\n }\n\n const obj: CircularObject = { name: \"Alice\" };\n obj.self = obj;\n\n const expected = '{\"name\":\"Alice\",\"self\":\"[Circular]\"}';\n const result = JSON.stringify(obj, getJSONStringifyReplacer());\n expect(result).toEqual(expected);\n });\n});\n"],
5
- "mappings": "AAAA,OAAS,0BAAAA,MAA8B,2CAEvC,OAAS,4CAAAC,MAAgD,4DACzD,OAAS,iBAAAC,MAAqB,+CAI9B,OAAS,4BAAAC,MAAgC,0BAEzC,SAAS,2BAA4B,IAAM,CACzC,GAAG,8DAA+D,IAAM,CACtE,MAAMC,EAAWD,EAAyB,EACpCE,EAAQ,IAAI,WAAW,CAAC,EAAG,EAAG,CAAC,CAAC,EAChCC,EAASF,EAAS,MAAOC,CAAK,EACpC,OAAOC,CAAM,EAAE,QAAQ,CACrB,IAAK,WACL,YAAa,WACb,MAAO,OACT,CAAC,CACH,CAAC,EAED,GAAG,uDAAwD,IAAM,CAC/D,MAAMC,EAAkBP,EAAuB,EACzCI,EAAWD,EAAyB,EAEpCK,EAA4C,CAChD,YAAaR,EAAuB,EACpC,KAAM,MACN,GAAI,iBACJ,SAAU,GAAG,GAAG,EAChB,UAAW,KACb,EAEMK,EAAQ,IAAIH,EAChB,CACE,gBAAAM,EACA,GAAI,iBACN,EACA,GAAG,GAAG,EACN,CAAC,EACD,CAAC,EACDP,CACF,EACMK,EAAS,KAAK,UAAUD,EAAOD,CAAQ,EACvCK,EAAW,4DAA4D,KAAK,UAChFF,CACF,CAAC,wCACDF,EAAM,MAAM,EACZ,OAAOC,CAAM,EAAE,QAAQG,CAAQ,CACjC,CAAC,EAED,GAAG,6DAA8D,IAAM,CAMrE,MAAMC,EAAsB,CAAE,KAAM,OAAQ,EAC5CA,EAAI,KAAOA,EAEX,MAAMD,EAAW,uCACXH,EAAS,KAAK,UAAUI,EAAKP,EAAyB,CAAC,EAC7D,OAAOG,CAAM,EAAE,QAAQG,CAAQ,CACjC,CAAC,CACH,CAAC",
6
- "names": ["deviceModelStubBuilder", "DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS", "DeviceSession", "getJSONStringifyReplacer", "replacer", "value", "result", "stubDeviceModel", "connectedDevice", "expected", "obj"]
4
+ "sourcesContent": ["import { deviceModelStubBuilder } from \"@api/device-model/model/DeviceModel.stub\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { deviceSessionStubBuilder } from \"@internal/device-session/model/DeviceSession.stub\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { getJSONStringifyReplacer } from \"./WebLogsExporterLogger\";\n\ndescribe(\"getJSONStringifyReplacer\", () => {\n it(\"should return a function that replaces Uint8Array correctly\", () => {\n const replacer = getJSONStringifyReplacer();\n const value = new Uint8Array([1, 2, 3]);\n const result = replacer(\"key\", value);\n expect(result).toEqual({\n hex: \"0x010203\",\n readableHex: \"01 02 03\",\n value: \"1,2,3\",\n });\n });\n\n it(\"should return a function that replaces DeviceSession\", () => {\n const stubDeviceModel = deviceModelStubBuilder();\n const replacer = getJSONStringifyReplacer();\n\n const connectedDevice: TransportConnectedDevice = {\n deviceModel: deviceModelStubBuilder(),\n type: \"USB\",\n id: \"mockedDeviceId\",\n sendApdu: vi.fn(),\n transport: \"USB\",\n };\n\n const value = deviceSessionStubBuilder(\n {\n connectedDevice,\n id: \"mockedSessionId\",\n },\n vi.fn(),\n {} as ManagerApiService,\n {} as SecureChannelService,\n DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n );\n const result = JSON.stringify(value, replacer);\n const expected = `{\"id\":\"mockedSessionId\",\"connectedDevice\":{\"deviceModel\":${JSON.stringify(\n stubDeviceModel,\n )},\"type\":\"USB\",\"id\":\"mockedDeviceId\"}}`;\n value.close();\n expect(result).toEqual(expected);\n });\n\n it(\"should return a function that replaces circular references\", () => {\n interface CircularObject {\n name: string;\n self?: CircularObject;\n }\n\n const obj: CircularObject = { name: \"Alice\" };\n obj.self = obj;\n\n const expected = '{\"name\":\"Alice\",\"self\":\"[Circular]\"}';\n const result = JSON.stringify(obj, getJSONStringifyReplacer());\n expect(result).toEqual(expected);\n });\n});\n"],
5
+ "mappings": "AAAA,OAAS,0BAAAA,MAA8B,2CAEvC,OAAS,4CAAAC,MAAgD,4DACzD,OAAS,4BAAAC,MAAgC,oDAIzC,OAAS,4BAAAC,MAAgC,0BAEzC,SAAS,2BAA4B,IAAM,CACzC,GAAG,8DAA+D,IAAM,CACtE,MAAMC,EAAWD,EAAyB,EACpCE,EAAQ,IAAI,WAAW,CAAC,EAAG,EAAG,CAAC,CAAC,EAChCC,EAASF,EAAS,MAAOC,CAAK,EACpC,OAAOC,CAAM,EAAE,QAAQ,CACrB,IAAK,WACL,YAAa,WACb,MAAO,OACT,CAAC,CACH,CAAC,EAED,GAAG,uDAAwD,IAAM,CAC/D,MAAMC,EAAkBP,EAAuB,EACzCI,EAAWD,EAAyB,EAEpCK,EAA4C,CAChD,YAAaR,EAAuB,EACpC,KAAM,MACN,GAAI,iBACJ,SAAU,GAAG,GAAG,EAChB,UAAW,KACb,EAEMK,EAAQH,EACZ,CACE,gBAAAM,EACA,GAAI,iBACN,EACA,GAAG,GAAG,EACN,CAAC,EACD,CAAC,EACDP,CACF,EACMK,EAAS,KAAK,UAAUD,EAAOD,CAAQ,EACvCK,EAAW,4DAA4D,KAAK,UAChFF,CACF,CAAC,wCACDF,EAAM,MAAM,EACZ,OAAOC,CAAM,EAAE,QAAQG,CAAQ,CACjC,CAAC,EAED,GAAG,6DAA8D,IAAM,CAMrE,MAAMC,EAAsB,CAAE,KAAM,OAAQ,EAC5CA,EAAI,KAAOA,EAEX,MAAMD,EAAW,uCACXH,EAAS,KAAK,UAAUI,EAAKP,EAAyB,CAAC,EAC7D,OAAOG,CAAM,EAAE,QAAQG,CAAQ,CACjC,CAAC,CACH,CAAC",
6
+ "names": ["deviceModelStubBuilder", "DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS", "deviceSessionStubBuilder", "getJSONStringifyReplacer", "replacer", "value", "result", "stubDeviceModel", "connectedDevice", "expected", "obj"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import I from"isomorphic-ws";import{Observable as T}from"rxjs";import{CommandUtils as h}from"../../command/utils/CommandUtils";import{InMessageQueryEnum as y,OutMessageResponseEnum as w,SecureChannelEventType as i}from"../../secure-channel/task/types";import{extractPublicKey as O,isGetCertificateApdu as R,willRequestPermission as D}from"../../secure-channel/utils";import{bufferToHexaString as x,hexaStringToBuffer as A}from"../../utils/HexaString";import{NobleCryptoService as N}from"../../../internal/crypto/NobleCryptoService";import{SecureChannelError as r,SecureChannelErrorType as S}from"../../../internal/secure-channel/model/Errors";class j{constructor(n,c){this._api=n;this._args=c;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new r(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`);this._cryptoService=this._args.cryptoService??new N}_connection;_cryptoService;_deviceIdCaptured=!1;run(){const n=this._api.disableRefresher("connectToSecureChannel");return new T(t=>{let g=!1,l=!1,v=!1;const a=f=>{t.next({type:i.Error,error:f}),t.complete(),l=!0};return this._connection.onopen=()=>{t.next({type:i.Opened})},this._connection.onerror=f=>{l||(t.next({type:i.Error,error:new r({url:this._connection.url,errorMessage:f.message})}),t.complete())},this._connection.onclose=()=>{l||(v?t.next({type:i.Closed}):t.next({type:i.Error,error:new r({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),t.complete())},this._connection.onmessage=async f=>{if(g)return;let o;try{const e=JSON.parse(String(f.data));if(this.isInMessageType(e))o=e;else throw new Error("Data does not match InMessageType")}catch{a(new r({url:this._connection.url,errorMessage:`Invalid message received: ${String(f.data)}`}));return}switch(o.query){case y.EXCHANGE:{const{nonce:e,data:p}=o;if(typeof p!="string"){a(new r(`${y.EXCHANGE} data type should be an APDU`));return}const s=A(p);if(s===null||s.length<5){a(new r(`Received invalid APDU data: ${p}`));return}t.next({type:i.PreExchange,payload:{nonce:e,apdu:s}});let u=!1;D(s)&&!this.isSecureConnectionAllowed()&&(u=!0,t.next({type:i.PermissionRequested}));const m=await this._api.sendApdu(s);if(g)return;m.caseOf({Left:d=>{a(new r(d))},Right:d=>{let C;const E=this.mapDeviceError(d);if(E===null){if(C=w.SUCCESS,!this._deviceIdCaptured&&R(s)){this._deviceIdCaptured=!0;const _=O(d);if(_){const k=this._cryptoService.sha3_256(_);t.next({type:i.DeviceId,payload:{deviceId:k}})}}t.next({type:i.Exchange,payload:{nonce:e,apdu:s,data:d.data,status:d.statusCode}}),u&&t.next({type:i.PermissionGranted})}else C=w.ERROR,a(E);const M={nonce:e,response:C,data:x(d.data,!1)};this._connection.send(JSON.stringify(M))}});break}case y.BULK:{if(l=!0,this._connection.close(),!Array.isArray(o.data)||o.data.length===0||!o.data.every(e=>typeof e=="string")){a(new r("Invalid bulk data received"));return}for(let e=0,p=o.data.length;e<p;e++){const s=A(o.data[e]);if(s===null||s.length<5){a(new r(`Received invalid APDU bulk data: ${o.data[e]}`));return}const u=await this._api.sendApdu(s);if(g)return;if(u.isLeft()){a(new r(u.extract()));return}else if(u.isRight()){const m=this.mapDeviceError(u.extract());if(m===null)t.next({type:i.Progress,payload:{progress:+Number((e+1)/p).toFixed(2),index:e,total:p}});else{a(m);return}}}v=!0,t.complete();break}case y.SUCCESS:{if(l)break;const e=o.result??o.data;e&&t.next({type:i.Result,payload:e??""}),v=!0,t.complete();break}case y.WARNING:{if(l)break;t.next({type:i.Warning,payload:{message:String(o.data)}});break}case y.ERROR:{if(l)break;a(new r({url:this._connection.url,errorMessage:String(o.data)}))}}},()=>{n(),g=!0,this._connection.readyState===I.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){const n=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in n&&n.isSecureConnectionAllowed}isInMessageType(n){if(typeof n!="object"||!n)return!1;const c=n;return typeof c.uuid=="string"&&typeof c.session=="string"&&typeof c.query=="string"&&Object.values(y).includes(c.query)&&typeof c.nonce=="number"}mapDeviceError(n){return h.isSuccessResponse(n)?null:h.isLockedDeviceResponse(n)?new r({url:this._connection.url,errorMessage:"Device is locked"},S.DeviceLocked):h.isRefusedByUser(n)?new r({url:this._connection.url,errorMessage:"User refused on the device"},S.RefusedByUser):h.isAppAlreadyInstalled(n)?new r({url:this._connection.url,errorMessage:"App already installed"},S.AppAlreadyInstalled):h.isOutOfMemory(n)?new r({url:this._connection.url,errorMessage:"Out of memory"},S.OutOfMemory):new r({url:this._connection.url,errorMessage:`Invalid status code: ${x(n.statusCode)}`})}}export{j as ConnectToSecureChannelTask};
1
+ import k from"isomorphic-ws";import{Observable as I}from"rxjs";import{CommandUtils as f}from"../../command/utils/CommandUtils";import{InMessageQueryEnum as d,OutMessageResponseEnum as _,SecureChannelEventType as i}from"../../secure-channel/task/types";import{extractPublicKey as O,isGetCertificateApdu as T,willRequestPermission as R}from"../../secure-channel/utils";import{bufferToHexaString as w,hexaStringToBuffer as x}from"../../utils/HexaString";import{NobleCryptoService as D}from"../../../internal/crypto/NobleCryptoService";import{SecureChannelError as n,SecureChannelErrorType as m}from"../../../internal/secure-channel/model/Errors";class j{constructor(r,e){this._api=r;this._args=e;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new n(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`);this._cryptoService=this._args.cryptoService??new D}_connection;_cryptoService;_deviceIdCaptured=!1;run(){return new I(e=>{let h=!1,c=!1,S=!1;const a=y=>{e.next({type:i.Error,error:y}),e.complete(),c=!0};return this._connection.onopen=()=>{e.next({type:i.Opened})},this._connection.onerror=y=>{c||(e.next({type:i.Error,error:new n({url:this._connection.url,errorMessage:y.message})}),e.complete())},this._connection.onclose=()=>{c||(S?e.next({type:i.Closed}):e.next({type:i.Error,error:new n({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),e.complete())},this._connection.onmessage=async y=>{if(h)return;let o;try{const t=JSON.parse(String(y.data));if(this.isInMessageType(t))o=t;else throw new Error("Data does not match InMessageType")}catch{a(new n({url:this._connection.url,errorMessage:`Invalid message received: ${String(y.data)}`}));return}switch(o.query){case d.EXCHANGE:{const{nonce:t,data:l}=o;if(typeof l!="string"){a(new n(`${d.EXCHANGE} data type should be an APDU`));return}const s=x(l);if(s===null||s.length<5){a(new n(`Received invalid APDU data: ${l}`));return}e.next({type:i.PreExchange,payload:{nonce:t,apdu:s}});let p=!1;R(s)&&!this.isSecureConnectionAllowed()&&(p=!0,e.next({type:i.PermissionRequested}));const g=await this._api.sendApdu(s);if(h)return;g.caseOf({Left:u=>{a(new n(u))},Right:u=>{let v;const C=this.mapDeviceError(u);if(C===null){if(v=_.SUCCESS,!this._deviceIdCaptured&&T(s)){this._deviceIdCaptured=!0;const E=O(u);if(E){const M=this._cryptoService.sha3_256(E);e.next({type:i.DeviceId,payload:{deviceId:M}})}}e.next({type:i.Exchange,payload:{nonce:t,apdu:s,data:u.data,status:u.statusCode}}),p&&e.next({type:i.PermissionGranted})}else v=_.ERROR,a(C);const A={nonce:t,response:v,data:w(u.data,!1)};this._connection.send(JSON.stringify(A))}});break}case d.BULK:{if(c=!0,this._connection.close(),!Array.isArray(o.data)||o.data.length===0||!o.data.every(t=>typeof t=="string")){a(new n("Invalid bulk data received"));return}for(let t=0,l=o.data.length;t<l;t++){const s=x(o.data[t]);if(s===null||s.length<5){a(new n(`Received invalid APDU bulk data: ${o.data[t]}`));return}const p=await this._api.sendApdu(s);if(h)return;if(p.isLeft()){a(new n(p.extract()));return}else if(p.isRight()){const g=this.mapDeviceError(p.extract());if(g===null)e.next({type:i.Progress,payload:{progress:+Number((t+1)/l).toFixed(2),index:t,total:l}});else{a(g);return}}}S=!0,e.complete();break}case d.SUCCESS:{if(c)break;const t=o.result??o.data;t&&e.next({type:i.Result,payload:t??""}),S=!0,e.complete();break}case d.WARNING:{if(c)break;e.next({type:i.Warning,payload:{message:String(o.data)}});break}case d.ERROR:{if(c)break;a(new n({url:this._connection.url,errorMessage:String(o.data)}))}}},()=>{h=!0,this._connection.readyState===k.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){const r=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in r&&r.isSecureConnectionAllowed}isInMessageType(r){if(typeof r!="object"||!r)return!1;const e=r;return typeof e.uuid=="string"&&typeof e.session=="string"&&typeof e.query=="string"&&Object.values(d).includes(e.query)&&typeof e.nonce=="number"}mapDeviceError(r){return f.isSuccessResponse(r)?null:f.isLockedDeviceResponse(r)?new n({url:this._connection.url,errorMessage:"Device is locked"},m.DeviceLocked):f.isRefusedByUser(r)?new n({url:this._connection.url,errorMessage:"User refused on the device"},m.RefusedByUser):f.isAppAlreadyInstalled(r)?new n({url:this._connection.url,errorMessage:"App already installed"},m.AppAlreadyInstalled):f.isOutOfMemory(r)?new n({url:this._connection.url,errorMessage:"Out of memory"},m.OutOfMemory):new n({url:this._connection.url,errorMessage:`Invalid status code: ${w(r.statusCode)}`})}}export{j as ConnectToSecureChannelTask};
2
2
  //# sourceMappingURL=ConnectToSecureChannelTask.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/secure-channel/task/ConnectToSecureChannelTask.ts"],
4
- "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport {\n extractPublicKey,\n isGetCertificateApdu,\n willRequestPermission,\n} from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport { type CryptoService } from \"@internal/crypto/CryptoService\";\nimport { NobleCryptoService } from \"@internal/crypto/NobleCryptoService\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n cryptoService?: CryptoService;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n private readonly _cryptoService: CryptoService;\n private _deviceIdCaptured: boolean = false;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n this._cryptoService = this._args.cryptoService ?? new NobleCryptoService();\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Check if this is the first GetCertificate call\n if (!this._deviceIdCaptured && isGetCertificateApdu(apdu)) {\n this._deviceIdCaptured = true;\n const publicKey = extractPublicKey(apduResponse);\n if (publicKey) {\n // Compute SHA3-256 hash of the public key to get the device ID\n const deviceId = this._cryptoService.sha3_256(publicKey);\n subscriber.next({\n type: SecureChannelEventType.DeviceId,\n payload: { deviceId },\n });\n }\n }\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data, false),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
5
- "mappings": "AAAA,OAAOA,MAAe,gBAEtB,OAAS,cAAAC,MAAkB,OAE3B,OAAS,gBAAAC,MAAoB,kCAG7B,OACE,sBAAAC,EAEA,0BAAAC,EAGA,0BAAAC,MACK,iCACP,OACE,oBAAAC,EACA,wBAAAC,EACA,yBAAAC,MACK,4BACP,OAAS,sBAAAC,EAAoB,sBAAAC,MAA0B,wBAEvD,OAAS,sBAAAC,MAA0B,sCACnC,OACE,sBAAAC,EACA,0BAAAC,MAEK,wCAOA,MAAMC,CAA2B,CAItC,YACmBC,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,M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E7B,CAEA,eAAeL,EAAuD,CACpE,OAAI9B,EAAa,kBAAkB8B,CAAY,EACtC,KAIL9B,EAAa,uBAAuB8B,CAAY,EAC3C,IAAIpB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,kBAChB,EACAC,EAAuB,YACzB,EAIEX,EAAa,gBAAgB8B,CAAY,EACpC,IAAIpB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,4BAChB,EACAC,EAAuB,aACzB,EAIEX,EAAa,sBAAsB8B,CAAY,EAC1C,IAAIpB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,uBAChB,EACAC,EAAuB,mBACzB,EAIEX,EAAa,cAAc8B,CAAY,EAClC,IAAIpB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,eAChB,EACAC,EAAuB,WACzB,EAGK,IAAID,EAAmB,CAC5B,IAAK,KAAK,YAAY,IACtB,aAAc,wBAAwBH,EACpCuB,EAAa,UACf,CAAC,EACH,CAAC,CACH,CACF",
6
- "names": ["WebSocket", "Observable", "CommandUtils", "InMessageQueryEnum", "OutMessageResponseEnum", "SecureChannelEventType", "extractPublicKey", "isGetCertificateApdu", "willRequestPermission", "bufferToHexaString", "hexaStringToBuffer", "NobleCryptoService", "SecureChannelError", "SecureChannelErrorType", "ConnectToSecureChannelTask", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "ignoreNetworkEvents", "communicationFinished", "notifyError", "error", "event", "input", "jsonData", "nonce", "data", "apdu", "permissionRequested", "response", "apduResponse", "outMessageResponse", "deviceError", "publicKey", "deviceId", "message", "i", "len", "payload", "deviceSessionState"]
4
+ "sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport {\n extractPublicKey,\n isGetCertificateApdu,\n willRequestPermission,\n} from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport { type CryptoService } from \"@internal/crypto/CryptoService\";\nimport { NobleCryptoService } from \"@internal/crypto/NobleCryptoService\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n cryptoService?: CryptoService;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n private readonly _cryptoService: CryptoService;\n private _deviceIdCaptured: boolean = false;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n this._cryptoService = this._args.cryptoService ?? new NobleCryptoService();\n }\n\n run(): Observable<SecureChannelEvent> {\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Check if this is the first GetCertificate call\n if (!this._deviceIdCaptured && isGetCertificateApdu(apdu)) {\n this._deviceIdCaptured = true;\n const publicKey = extractPublicKey(apduResponse);\n if (publicKey) {\n // Compute SHA3-256 hash of the public key to get the device ID\n const deviceId = this._cryptoService.sha3_256(publicKey);\n subscriber.next({\n type: SecureChannelEventType.DeviceId,\n payload: { deviceId },\n });\n }\n }\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data, false),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
5
+ "mappings": "AAAA,OAAOA,MAAe,gBAEtB,OAAS,cAAAC,MAAkB,OAE3B,OAAS,gBAAAC,MAAoB,kCAG7B,OACE,sBAAAC,EAEA,0BAAAC,EAGA,0BAAAC,MACK,iCACP,OACE,oBAAAC,EACA,wBAAAC,EACA,yBAAAC,MACK,4BACP,OAAS,sBAAAC,EAAoB,sBAAAC,MAA0B,wBAEvD,OAAS,sBAAAC,MAA0B,sCACnC,OACE,sBAAAC,EACA,0BAAAC,MAEK,wCAOA,MAAMC,CAA2B,CAItC,YACmBC,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,MAEjD,OAAM,IAAIJ,EACR,iCAAiC,OAAO,KAAK,MAAM,WAAW,QAAQ,CAAC,CAAC,EAC1E,EAEF,KAAK,eAAiB,KAAK,MAAM,eAAiB,IAAID,CACxD,CAfiB,YACA,eACT,kBAA6B,GAerC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pC,IAAInB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,4BAChB,EACAC,EAAuB,aACzB,EAIEX,EAAa,sBAAsB6B,CAAY,EAC1C,IAAInB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,uBAChB,EACAC,EAAuB,mBACzB,EAIEX,EAAa,cAAc6B,CAAY,EAClC,IAAInB,EACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,eAChB,EACAC,EAAuB,WACzB,EAGK,IAAID,EAAmB,CAC5B,IAAK,KAAK,YAAY,IACtB,aAAc,wBAAwBH,EACpCsB,EAAa,UACf,CAAC,EACH,CAAC,CACH,CACF",
6
+ "names": ["WebSocket", "Observable", "CommandUtils", "InMessageQueryEnum", "OutMessageResponseEnum", "SecureChannelEventType", "extractPublicKey", "isGetCertificateApdu", "willRequestPermission", "bufferToHexaString", "hexaStringToBuffer", "NobleCryptoService", "SecureChannelError", "SecureChannelErrorType", "ConnectToSecureChannelTask", "_api", "_args", "subscriber", "unsubscribed", "ignoreNetworkEvents", "communicationFinished", "notifyError", "error", "event", "input", "jsonData", "nonce", "data", "apdu", "permissionRequested", "response", "apduResponse", "outMessageResponse", "deviceError", "publicKey", "deviceId", "message", "i", "len", "payload", "deviceSessionState"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{Left as o,Maybe as l,Nothing as a,Right as g}from"purify-ts";import{assign as p,createActor as y,emit as v,setup as h}from"xstate";import{GetAppAndVersionCommand as T}from"../../command/os/GetAppAndVersionCommand";import{CommandUtils as D}from"../../command/utils/CommandUtils";import{UnknownDeviceExchangeError as C}from"../../Error";import{AlreadySendingApduError as m,DeviceDisconnectedBeforeSendingApdu as S,DeviceDisconnectedWhileSendingError as A}from"./Errors";class W{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(n){this.deviceId=n.deviceId,this.deviceAdpuSender=n.deviceApduSender,this.timeoutDuration=n.timeoutDuration,this.machineActor=y(b({sendApduFn:(r,s,t)=>this.sendApduToDeviceConnection(r,s,t),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},tryToReconnect:()=>{n.tryToReconnect(this.timeoutDuration)},onTerminated:n.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(n,r,s){this.deviceAdpuSender.sendApdu(n,r,s).then(t=>{t.caseOf({Left:c=>{this.machineActor.send({type:"ApduSendingError",error:c})},Right:c=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:c})}})}).catch(t=>{this.machineActor.send({type:"ApduSendingError",error:new C(t)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(n){this.deviceAdpuSender.setDependencies(n)}getDeviceId(){return this.deviceId}sendApdu(n,r,s){return new Promise(t=>{this.machineActor.send({type:"SendApduCalled",apdu:n,triggersDisconnection:!!r,abortTimeout:s,responseCallback:t})})}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceConnected(){this.machineActor.send({type:"DeviceConnected"})}eventDeviceDisconnected(){this.machineActor.send({type:"DeviceDisconnected"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function b({sendApduFn:u,startReconnectionTimeout:n,cancelReconnectionTimeout:r,tryToReconnect:s,onTerminated:t,closeConnection:c}){return h({types:{},actions:{startTimer:()=>{n()},cancelTimer:()=>{r()},reconnectionTimeoutEvent:v({type:"ReconnectionTimedOut"}),sendApdu:({context:e})=>{e.apduInProgress.map(({apdu:i,abortTimeout:d})=>{u(i,!1,d)})},sendApduResponse:({context:e},i)=>{e.apduInProgress.map(({responseCallback:d})=>d(i.response))},sendGetAppAndVersion:()=>{u(new T().getApdu().getRawApdu(),!1)},tryToReconnect:()=>{s()},clearApduInProgress:p({apduInProgress:a}),clearApduResponse:p({apduResponse:a}),signalTermination:()=>{t()},closeConnection:()=>{c()}},guards:{isApduThatTriggersDisconnection:({context:e,event:i})=>i.type!=="ApduResponseReceived"?!1:e.apduInProgress.caseOf({Just:({triggersDisconnection:d,apdu:R})=>(d||D.isApduThatTriggersDisconnection(R))&&D.isSuccessResponse(i.apduResponse),Nothing:()=>!1}),isSendApduBusyError:({event:e})=>e.type!=="ApduResponseReceived"?!1:e.apduResponse.statusCode[0]===102&&e.apduResponse.statusCode[1]===1}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:a,apduResponse:a},states:{Connected:{on:{DeviceDisconnected:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:p({apduInProgress:({event:e})=>l.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:"isApduThatTriggersDisconnection",target:"WaitingForDisconnection",actions:[p({apduResponse:({event:e})=>l.of(e.apduResponse)})]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:g(e.apduResponse)})},{type:"clearApduInProgress"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:o(e.error)})},"clearApduInProgress"]},DeviceDisconnected:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:o(new A)}},"clearApduInProgress"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:o(new A)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback(o(new m))}}}},WaitingForDisconnection:{entry:["sendGetAppAndVersion"],exit:[{type:"sendApduResponse",params:({context:e})=>({response:e.apduResponse.caseOf({Just:i=>g(i),Nothing:()=>o(new C)})})},{type:"clearApduInProgress"},{type:"clearApduResponse"}],on:{ApduResponseReceived:[{guard:"isSendApduBusyError",actions:["sendGetAppAndVersion"],target:"WaitingForDisconnection"},{target:"Connected"}],ApduSendingError:[{target:"WaitingForReconnection"}],SendApduCalled:{actions:({event:e})=>{e.responseCallback(o(new m))}},DeviceDisconnected:{target:"WaitingForReconnection"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnection:{entry:["startTimer","tryToReconnect"],on:{DeviceConnected:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:p({apduInProgress:({event:e})=>l.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceConnected:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:o(new S)}},{type:"clearApduInProgress"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:o(new A)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback(o(new m))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}export{W as DeviceConnectionStateMachine};
1
+ import{Left as i,Maybe as m,Nothing as a,Right as g}from"purify-ts";import{assign as p,createActor as C,emit as y,setup as h}from"xstate";import{GetAppAndVersionCommand as T}from"../../command/os/GetAppAndVersionCommand";import{CommandUtils as D}from"../../command/utils/CommandUtils";import{UnknownDeviceExchangeError as R}from"../../Error";import{AlreadySendingApduError as l,DeviceDisconnectedBeforeSendingApdu as S,DeviceDisconnectedWhileSendingError as A}from"./Errors";const b=1e4;class F{deviceId;deviceAdpuSender;machineActor;timeoutDuration;timeout=null;previousSendApduPromise=null;startReconnectionTimeout(){this.timeout=setTimeout(()=>{this.machineActor.send({type:"ReconnectionTimedOut"})},this.timeoutDuration)}constructor(n){this.deviceId=n.deviceId,this.deviceAdpuSender=n.deviceApduSender,this.timeoutDuration=n.timeoutDuration,this.machineActor=C(E({sendApduFn:(s,c,t)=>this.sendApduToDeviceConnection(s,c,t),startReconnectionTimeout:()=>this.startReconnectionTimeout(),cancelReconnectionTimeout:()=>{this.timeout&&(clearTimeout(this.timeout),this.timeout=null)},tryToReconnect:()=>{n.tryToReconnect(this.timeoutDuration)},onTerminated:n.onTerminated,closeConnection:()=>{this.deviceAdpuSender.closeConnection()}})),this.machineActor.start()}sendApduToDeviceConnection(n,s,c){this.deviceAdpuSender.sendApdu(n,s,c).then(t=>{t.caseOf({Left:o=>{this.machineActor.send({type:"ApduSendingError",error:o})},Right:o=>{this.machineActor.send({type:"ApduResponseReceived",apduResponse:o})}})}).catch(t=>{this.machineActor.send({type:"ApduSendingError",error:new R(t)})})}getDependencies(){return this.deviceAdpuSender.getDependencies()}setDependencies(n){this.deviceAdpuSender.setDependencies(n)}getDeviceId(){return this.deviceId}async sendApdu(n,s,c){this.machineActor.getSnapshot().context.apduInProgress.isJust()&&await Promise.race([new Promise(o=>setTimeout(o,b)),this.previousSendApduPromise]);const t=new Promise(o=>{this.machineActor.send({type:"SendApduCalled",apdu:n,triggersDisconnection:!!s,abortTimeout:c,responseCallback:o})});return this.previousSendApduPromise=t,t.finally(()=>{this.previousSendApduPromise===t&&(this.previousSendApduPromise=null)}),t}async setupConnection(){await this.deviceAdpuSender.setupConnection()}eventDeviceConnected(){this.machineActor.send({type:"DeviceConnected"})}eventDeviceDisconnected(){this.machineActor.send({type:"DeviceDisconnected"})}closeConnection(){this.machineActor.send({type:"CloseConnectionCalled"})}}function E({sendApduFn:u,startReconnectionTimeout:n,cancelReconnectionTimeout:s,tryToReconnect:c,onTerminated:t,closeConnection:o}){return h({types:{},actions:{startTimer:()=>{n()},cancelTimer:()=>{s()},reconnectionTimeoutEvent:y({type:"ReconnectionTimedOut"}),sendApdu:({context:e})=>{e.apduInProgress.map(({apdu:r,abortTimeout:d})=>{u(r,!1,d)})},sendApduResponse:({context:e},r)=>{e.apduInProgress.map(({responseCallback:d})=>d(r.response))},sendGetAppAndVersion:()=>{u(new T().getApdu().getRawApdu(),!1)},tryToReconnect:()=>{c()},clearApduInProgress:p({apduInProgress:a}),clearApduResponse:p({apduResponse:a}),signalTermination:()=>{t()},closeConnection:()=>{o()}},guards:{isApduThatTriggersDisconnection:({context:e,event:r})=>r.type!=="ApduResponseReceived"?!1:e.apduInProgress.caseOf({Just:({triggersDisconnection:d,apdu:v})=>(d||D.isApduThatTriggersDisconnection(v))&&D.isSuccessResponse(r.apduResponse),Nothing:()=>!1}),isSendApduBusyError:({event:e})=>e.type!=="ApduResponseReceived"?!1:e.apduResponse.statusCode[0]===102&&e.apduResponse.statusCode[1]===1}}).createMachine({id:"deviceConnection",initial:"Connected",context:{apduInProgress:a,apduResponse:a},states:{Connected:{on:{DeviceDisconnected:{target:"WaitingForReconnection"},SendApduCalled:{target:"SendingApdu",actions:p({apduInProgress:({event:e})=>m.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},CloseConnectionCalled:{target:"Terminated"}}},SendingApdu:{entry:"sendApdu",on:{ApduResponseReceived:[{guard:"isApduThatTriggersDisconnection",target:"WaitingForDisconnection",actions:[p({apduResponse:({event:e})=>m.of(e.apduResponse)})]},{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:g(e.apduResponse)})},{type:"clearApduInProgress"}]}],ApduSendingError:{target:"Connected",actions:[{type:"sendApduResponse",params:({event:e})=>({response:i(e.error)})},"clearApduInProgress"]},DeviceDisconnected:{target:"WaitingForReconnection",actions:[{type:"sendApduResponse",params:{response:i(new A)}},"clearApduInProgress"]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:i(new A)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback(i(new l))}}}},WaitingForDisconnection:{entry:["sendGetAppAndVersion"],exit:[{type:"sendApduResponse",params:({context:e})=>({response:e.apduResponse.caseOf({Just:r=>g(r),Nothing:()=>i(new R)})})},{type:"clearApduInProgress"},{type:"clearApduResponse"}],on:{ApduResponseReceived:[{guard:"isSendApduBusyError",actions:["sendGetAppAndVersion"],target:"WaitingForDisconnection"},{target:"Connected"}],ApduSendingError:[{target:"WaitingForReconnection"}],SendApduCalled:{actions:({event:e})=>{e.responseCallback(i(new l))}},DeviceDisconnected:{target:"WaitingForReconnection"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnection:{entry:["startTimer","tryToReconnect"],on:{DeviceConnected:{target:"Connected",actions:"cancelTimer"},SendApduCalled:{target:"WaitingForReconnectionWithQueuedSendApdu",actions:p({apduInProgress:({event:e})=>m.of({apdu:e.apdu,triggersDisconnection:e.triggersDisconnection,abortTimeout:e.abortTimeout,responseCallback:e.responseCallback})})},ReconnectionTimedOut:{target:"Terminated"},CloseConnectionCalled:{target:"Terminated"}}},WaitingForReconnectionWithQueuedSendApdu:{on:{DeviceConnected:{target:"SendingApdu",actions:"cancelTimer"},ReconnectionTimedOut:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:i(new S)}},{type:"clearApduInProgress"}]},CloseConnectionCalled:{target:"Terminated",actions:[{type:"sendApduResponse",params:{response:i(new A)}},"clearApduInProgress"]},SendApduCalled:{actions:({event:e})=>{e.responseCallback(i(new l))}}}},Terminated:{entry:["signalTermination","closeConnection"],type:"final"}}})}export{F as DeviceConnectionStateMachine};
2
2
  //# sourceMappingURL=DeviceConnectionStateMachine.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/transport/model/DeviceConnectionStateMachine.ts"],
4
- "sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { type Actor, assign, createActor, emit, setup } from \"xstate\";\n\nimport { GetAppAndVersionCommand } from \"@api/command/os/GetAppAndVersionCommand\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError, UnknownDeviceExchangeError } from \"@api/Error\";\nimport { type DeviceId } from \"@api/types\";\n\nimport { type DeviceApduSender } from \"./DeviceApduSender\";\nimport {\n AlreadySendingApduError,\n DeviceDisconnectedBeforeSendingApdu,\n DeviceDisconnectedWhileSendingError,\n} from \"./Errors\";\n\n// const { inspect } = createBrowserInspector();\n\ntype DeviceDisconnectedEvent = {\n type: \"DeviceDisconnected\";\n};\n\ntype DeviceConnectedEvent = {\n type: \"DeviceConnected\";\n};\n\ntype ApduResponseReceived = {\n type: \"ApduResponseReceived\";\n apduResponse: ApduResponse;\n};\n\ntype ApduSendingError = {\n type: \"ApduSendingError\";\n error: DmkError;\n};\n\ntype SendApduCalled = {\n type: \"SendApduCalled\";\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n};\n\ntype ReconnectionTimedOut = {\n type: \"ReconnectionTimedOut\";\n};\n\ntype CloseConnectionCalled = {\n type: \"CloseConnectionCalled\";\n};\n\nexport type Events =\n | DeviceDisconnectedEvent\n | DeviceConnectedEvent\n | ApduResponseReceived\n | ApduSendingError\n | SendApduCalled\n | CloseConnectionCalled\n | ReconnectionTimedOut;\n\nexport type DeviceConnectionStateMachineParams<Dependencies> = {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n tryToReconnect: (timeoutDuration: number) => void;\n onTerminated: () => void;\n};\n\nexport class DeviceConnectionStateMachine<Dependencies> {\n private deviceId: DeviceId;\n private deviceAdpuSender: DeviceApduSender<Dependencies>;\n\n private machineActor: Actor<ReturnType<typeof makeStateMachine>>;\n\n private timeoutDuration: number;\n private timeout: ReturnType<typeof setTimeout> | null = null;\n\n startReconnectionTimeout() {\n this.timeout = setTimeout(() => {\n this.machineActor.send({ type: \"ReconnectionTimedOut\" });\n }, this.timeoutDuration);\n }\n\n constructor(params: DeviceConnectionStateMachineParams<Dependencies>) {\n this.deviceId = params.deviceId;\n this.deviceAdpuSender = params.deviceApduSender;\n this.timeoutDuration = params.timeoutDuration;\n this.machineActor = createActor(\n makeStateMachine({\n sendApduFn: (apdu, triggersDisconnection, abortTimeout) =>\n this.sendApduToDeviceConnection(\n apdu,\n triggersDisconnection,\n abortTimeout,\n ),\n startReconnectionTimeout: () => this.startReconnectionTimeout(),\n cancelReconnectionTimeout: () => {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n },\n tryToReconnect: () => {\n params.tryToReconnect(this.timeoutDuration);\n },\n onTerminated: params.onTerminated,\n closeConnection: () => {\n this.deviceAdpuSender.closeConnection();\n },\n }),\n // {\n // // inspect,\n // },\n );\n this.machineActor.start();\n }\n\n private sendApduToDeviceConnection(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ) {\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection, abortTimeout)\n .then((response) => {\n response.caseOf({\n Left: (error) => {\n this.machineActor.send({ type: \"ApduSendingError\", error });\n },\n Right: (apduResponse) => {\n this.machineActor.send({\n type: \"ApduResponseReceived\",\n apduResponse,\n });\n },\n });\n })\n .catch((error) => {\n this.machineActor.send({\n type: \"ApduSendingError\",\n error: new UnknownDeviceExchangeError(error),\n });\n });\n }\n\n /**\n * Called by the transport\n */\n\n public getDependencies(): Dependencies {\n return this.deviceAdpuSender.getDependencies();\n }\n\n public setDependencies(dependencies: Dependencies) {\n this.deviceAdpuSender.setDependencies(dependencies);\n }\n\n public getDeviceId() {\n return this.deviceId;\n }\n\n public sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n return new Promise((responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\n abortTimeout,\n responseCallback,\n });\n });\n }\n\n public async setupConnection() {\n await this.deviceAdpuSender.setupConnection();\n }\n\n // State Machine Events\n\n public eventDeviceConnected() {\n this.machineActor.send({ type: \"DeviceConnected\" });\n }\n\n public eventDeviceDisconnected() {\n this.machineActor.send({ type: \"DeviceDisconnected\" });\n }\n\n public closeConnection() {\n this.machineActor.send({ type: \"CloseConnectionCalled\" });\n }\n}\n\nfunction makeStateMachine({\n sendApduFn,\n startReconnectionTimeout,\n cancelReconnectionTimeout,\n tryToReconnect,\n onTerminated,\n closeConnection,\n}: {\n sendApduFn: (\n apdu: Uint8Array,\n triggersDisconnection: boolean,\n abortTimeout?: number,\n ) => void;\n startReconnectionTimeout: () => void;\n cancelReconnectionTimeout: () => void;\n tryToReconnect: () => void;\n onTerminated: () => void;\n closeConnection: () => void;\n}) {\n return setup({\n types: {} as {\n context: {\n apduInProgress: Maybe<{\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n }>;\n apduResponse: Maybe<ApduResponse>;\n };\n events: Events;\n },\n actions: {\n // event transitions\n startTimer: () => {\n startReconnectionTimeout();\n },\n cancelTimer: () => {\n cancelReconnectionTimeout();\n },\n reconnectionTimeoutEvent: emit({ type: \"ReconnectionTimedOut\" }),\n sendApdu: ({ context }) => {\n context.apduInProgress.map(({ apdu, abortTimeout }) => {\n sendApduFn(apdu, false, abortTimeout);\n });\n },\n sendApduResponse: (\n { context },\n params: { response: Either<DmkError, ApduResponse> },\n ) => {\n context.apduInProgress.map(({ responseCallback }) =>\n responseCallback(params.response),\n );\n },\n sendGetAppAndVersion: () => {\n sendApduFn(new GetAppAndVersionCommand().getApdu().getRawApdu(), false);\n },\n tryToReconnect: () => {\n tryToReconnect();\n },\n clearApduInProgress: assign({\n apduInProgress: Nothing,\n }),\n clearApduResponse: assign({\n apduResponse: Nothing,\n }),\n signalTermination: () => {\n onTerminated();\n },\n closeConnection: () => {\n closeConnection(); // ASK: how do we handle errors ?\n },\n },\n guards: {\n isApduThatTriggersDisconnection: ({ context, event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return context.apduInProgress.caseOf({\n /**\n * If the apdu is known as one that triggers a disconnection,\n * and if it's a success response,\n * then will trigger a disconnection (on Ledger OS prior to the IO revamp).\n */\n Just: ({ triggersDisconnection, apdu }) =>\n (triggersDisconnection ||\n CommandUtils.isApduThatTriggersDisconnection(apdu)) &&\n CommandUtils.isSuccessResponse(event.apduResponse),\n Nothing: () => false,\n });\n },\n isSendApduBusyError: ({ event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return (\n event.apduResponse.statusCode[0] === 0x66 &&\n event.apduResponse.statusCode[1] === 0x01\n );\n },\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QTANwJYGMwGED2AdgWJgC7qEB0+RJpkAxACJpZgukCGmAFpANoAGALqJQABzyx05QmJAAPRAA4A7AGZKywQEYAnAFYATMoAsBg6fUA2ADQgAnolUnKBjUdXXVpnUb0aAL6B9igY2DTEZBQE1IRR9BAMAMpgBBAAguIQAK44nAA2BQIi8pLSsgTySgjW6oKU6uo61kbWyh06Vsr2TgjqAZR6HUaWXcrqBmrBoawR8XQxcbRkjDgFUrgL0YT5RSWiSCDlMjHVKnrWjaO6ev6qlnp6vYim1qaN9YLqGuPKOjpVDMQGE2JFFlRUul0AQoFlcgx4TkAEpwSQEWBgVHYdCoA5lKSnORHGpNVSUPwGXQDQSmNTDF4IZTWPRDJotUw+HwAnTA0HzFaVShQiAwuHZHKIiWo2DozHYsC4gQ6Q4SQmVc79TxDIzqG6eJq+VSM94NPQ6CYuUzmQGCax8uZbQVLEVipFS3Ku2EAUQATr68L6hKrjuqziTEJNNHrTG1dIIDE8jLTGVTlJQboI2i56QZeSEQY7wTtYl7xQiWOF2GAuLx8UcThqIwh-OmdBZPF0qQCBoydIJlAZKK0jP4bHntBaHVXi0Ky+71ptZzE9sUIMGCRVw6Aau2dJQ6WZlMM-D9+89HIh++mbndVHpdNYLAnp2DtnO0qLYe6RUjV-W1S3Ykd0QABac1KFpbx3kHCxumNS9ak5SDTHNax0NUDRfFMV8BQSJYAHVOFOWEADFA2xd8YmYR0MlIWs+HXUoGzDYDFEQQx90mVozABJ9BAvPo6iuFpRgtQRdDUWNcKdfCqCIkioHI31KOdQgUk-P9CjXDcWKAqpmx0dR-gpCTaXNUxvh7RkvCHWlaWM9RfC6dCZOXeTiPIMiKJIKj1NUuSCAAFXQABbSAAHkclIXTAKJAyQIQLpBHJAEXB8AS1HvdRGT0a0D2ZZpBxjSc3L82IFK8pSfMwcqGEXTF3IIf8mJDRtt3YpLLPJZMWkmTtzJyxD+1UBofifVQOm8YyWjKtSKs8sVlICiECAImQeAARRyMAdogX8JRoqs6IYgDQ30zUjJ8CkWQmYZbOsFLGWzUyzE5bssx8ObAsoSqlpq8r1tILadr2g6ERWksQvCiAopi5i4qbRKjH7Bo4N1dsvFjOxEIeIwUPQ9o9AGSYvG+1bfsW7yVN8+agZB3bIHByUGtk1aWti874s1FGJOHYy6gTLo3lMVN7wPBNVAtbRRg0IEC35NmS0pxTltpwL6e2xn9s0w7mY5hGuaRzrAWZIYBJpc0pd1E18tNMZLOMAwnOCAsCDwFB4CORWms3bnm1AozWSgrHYMsYyEL6FGKXcDleMMO5rXJ5XZ0gP3jZqB4evaLwXEeqwnJNKYDypWlzHePwcIVotyuFT83QldOOpqWNU30A8rEmrMjPcAJk6FP7qch432rY3dxnN1onlaZ9idy5NILuCxl+UEwrH7wiqeqmnarpjatbB3Xcibser3eckfmd3xOkrnpce0DMjHMeoAgLjeqCCsBfVCmFOESE+EqdSfnmNwLJjBPBSs0QwuV3CQWPN3AwT4LTtldoEIAA */\n id: \"deviceConnection\",\n initial: \"Connected\",\n context: {\n apduInProgress: Nothing,\n apduResponse: Nothing,\n },\n states: {\n Connected: {\n on: {\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n SendApduCalled: {\n target: \"SendingApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n SendingApdu: {\n entry: \"sendApdu\",\n on: {\n ApduResponseReceived: [\n {\n guard: \"isApduThatTriggersDisconnection\",\n target: \"WaitingForDisconnection\",\n actions: [\n assign({\n apduResponse: ({ event }) => Maybe.of(event.apduResponse),\n }),\n ],\n },\n {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n ],\n },\n ],\n ApduSendingError: {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Left(event.error),\n };\n },\n },\n \"clearApduInProgress\",\n ],\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n WaitingForDisconnection: {\n entry: [\"sendGetAppAndVersion\"],\n exit: [\n {\n type: \"sendApduResponse\",\n params: ({ context }) => {\n return {\n response: context.apduResponse.caseOf({\n Just: (apduResponse) => Right(apduResponse),\n Nothing: () => Left(new UnknownDeviceExchangeError()),\n }),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n { type: \"clearApduResponse\" },\n ],\n on: {\n ApduResponseReceived: [\n {\n guard: \"isSendApduBusyError\",\n actions: [\"sendGetAppAndVersion\"],\n target: \"WaitingForDisconnection\",\n },\n {\n target: \"Connected\",\n },\n ],\n ApduSendingError: [\n {\n target: \"WaitingForReconnection\",\n },\n ],\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnection: {\n entry: [\"startTimer\", \"tryToReconnect\"],\n on: {\n DeviceConnected: {\n target: \"Connected\",\n actions: \"cancelTimer\",\n },\n SendApduCalled: {\n target: \"WaitingForReconnectionWithQueuedSendApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnectionWithQueuedSendApdu: {\n on: {\n DeviceConnected: {\n target: \"SendingApdu\",\n actions: \"cancelTimer\",\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedBeforeSendingApdu()),\n },\n },\n {\n type: \"clearApduInProgress\",\n },\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n // TODO: ADD INACTIVE STATE\n Terminated: {\n entry: [\"signalTermination\", \"closeConnection\"],\n type: \"final\",\n },\n },\n });\n}\n"],
5
- "mappings": "AACA,OAAsB,QAAAA,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAA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AqB,iBAAiB,EAC9C,KAAM,OACR,CACF,CACF,CAAC,CACH",
6
- "names": ["Left", "Maybe", "Nothing", "Right", "assign", "createActor", "emit", "setup", "GetAppAndVersionCommand", "CommandUtils", "UnknownDeviceExchangeError", "AlreadySendingApduError", "DeviceDisconnectedBeforeSendingApdu", "DeviceDisconnectedWhileSendingError", "DeviceConnectionStateMachine", "params", "makeStateMachine", "apdu", "triggersDisconnection", "abortTimeout", "response", "error", "apduResponse", "dependencies", "responseCallback", "sendApduFn", "startReconnectionTimeout", "cancelReconnectionTimeout", "tryToReconnect", "onTerminated", "closeConnection", "context", "event"]
4
+ "sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { type Either, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { type Actor, assign, createActor, emit, setup } from \"xstate\";\n\nimport { GetAppAndVersionCommand } from \"@api/command/os/GetAppAndVersionCommand\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { type DmkError, UnknownDeviceExchangeError } from \"@api/Error\";\nimport { type DeviceId } from \"@api/types\";\n\nimport { type DeviceApduSender } from \"./DeviceApduSender\";\nimport {\n AlreadySendingApduError,\n DeviceDisconnectedBeforeSendingApdu,\n DeviceDisconnectedWhileSendingError,\n} from \"./Errors\";\n\n// const { inspect } = createBrowserInspector();\n\nconst TRANSPORT_BUSY_WAIT_TIME = 10000; // 10 seconds\n\ntype DeviceDisconnectedEvent = {\n type: \"DeviceDisconnected\";\n};\n\ntype DeviceConnectedEvent = {\n type: \"DeviceConnected\";\n};\n\ntype ApduResponseReceived = {\n type: \"ApduResponseReceived\";\n apduResponse: ApduResponse;\n};\n\ntype ApduSendingError = {\n type: \"ApduSendingError\";\n error: DmkError;\n};\n\ntype SendApduCalled = {\n type: \"SendApduCalled\";\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n};\n\ntype ReconnectionTimedOut = {\n type: \"ReconnectionTimedOut\";\n};\n\ntype CloseConnectionCalled = {\n type: \"CloseConnectionCalled\";\n};\n\nexport type Events =\n | DeviceDisconnectedEvent\n | DeviceConnectedEvent\n | ApduResponseReceived\n | ApduSendingError\n | SendApduCalled\n | CloseConnectionCalled\n | ReconnectionTimedOut;\n\nexport type DeviceConnectionStateMachineParams<Dependencies> = {\n deviceId: DeviceId;\n deviceApduSender: DeviceApduSender<Dependencies>;\n timeoutDuration: number;\n tryToReconnect: (timeoutDuration: number) => void;\n onTerminated: () => void;\n};\n\nexport class DeviceConnectionStateMachine<Dependencies> {\n private deviceId: DeviceId;\n private deviceAdpuSender: DeviceApduSender<Dependencies>;\n\n private machineActor: Actor<ReturnType<typeof makeStateMachine>>;\n\n private timeoutDuration: number;\n private timeout: ReturnType<typeof setTimeout> | null = null;\n private previousSendApduPromise: Promise<\n Either<DmkError, ApduResponse>\n > | null = null;\n\n startReconnectionTimeout() {\n this.timeout = setTimeout(() => {\n this.machineActor.send({ type: \"ReconnectionTimedOut\" });\n }, this.timeoutDuration);\n }\n\n constructor(params: DeviceConnectionStateMachineParams<Dependencies>) {\n this.deviceId = params.deviceId;\n this.deviceAdpuSender = params.deviceApduSender;\n this.timeoutDuration = params.timeoutDuration;\n this.machineActor = createActor(\n makeStateMachine({\n sendApduFn: (apdu, triggersDisconnection, abortTimeout) =>\n this.sendApduToDeviceConnection(\n apdu,\n triggersDisconnection,\n abortTimeout,\n ),\n startReconnectionTimeout: () => this.startReconnectionTimeout(),\n cancelReconnectionTimeout: () => {\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n },\n tryToReconnect: () => {\n params.tryToReconnect(this.timeoutDuration);\n },\n onTerminated: params.onTerminated,\n closeConnection: () => {\n this.deviceAdpuSender.closeConnection();\n },\n }),\n // {\n // // inspect,\n // },\n );\n this.machineActor.start();\n }\n\n private sendApduToDeviceConnection(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ) {\n this.deviceAdpuSender\n .sendApdu(apdu, triggersDisconnection, abortTimeout)\n .then((response) => {\n response.caseOf({\n Left: (error) => {\n this.machineActor.send({ type: \"ApduSendingError\", error });\n },\n Right: (apduResponse) => {\n this.machineActor.send({\n type: \"ApduResponseReceived\",\n apduResponse,\n });\n },\n });\n })\n .catch((error) => {\n this.machineActor.send({\n type: \"ApduSendingError\",\n error: new UnknownDeviceExchangeError(error),\n });\n });\n }\n\n /**\n * Called by the transport\n */\n\n public getDependencies(): Dependencies {\n return this.deviceAdpuSender.getDependencies();\n }\n\n public setDependencies(dependencies: Dependencies) {\n this.deviceAdpuSender.setDependencies(dependencies);\n }\n\n public getDeviceId() {\n return this.deviceId;\n }\n\n public async sendApdu(\n apdu: Uint8Array,\n triggersDisconnection?: boolean,\n abortTimeout?: number,\n ): Promise<Either<DmkError, ApduResponse>> {\n if (this.machineActor.getSnapshot().context.apduInProgress.isJust()) {\n await Promise.race([\n new Promise((resolve) => setTimeout(resolve, TRANSPORT_BUSY_WAIT_TIME)),\n this.previousSendApduPromise,\n ]);\n }\n\n const promise = new Promise<Either<DmkError, ApduResponse>>(\n (responseCallback) => {\n this.machineActor.send({\n type: \"SendApduCalled\",\n apdu,\n triggersDisconnection: !!triggersDisconnection,\n abortTimeout,\n responseCallback,\n });\n },\n );\n this.previousSendApduPromise = promise;\n void promise.finally(() => {\n if (this.previousSendApduPromise === promise) {\n this.previousSendApduPromise = null;\n }\n });\n return promise;\n }\n\n public async setupConnection() {\n await this.deviceAdpuSender.setupConnection();\n }\n\n // State Machine Events\n\n public eventDeviceConnected() {\n this.machineActor.send({ type: \"DeviceConnected\" });\n }\n\n public eventDeviceDisconnected() {\n this.machineActor.send({ type: \"DeviceDisconnected\" });\n }\n\n public closeConnection() {\n this.machineActor.send({ type: \"CloseConnectionCalled\" });\n }\n}\n\nfunction makeStateMachine({\n sendApduFn,\n startReconnectionTimeout,\n cancelReconnectionTimeout,\n tryToReconnect,\n onTerminated,\n closeConnection,\n}: {\n sendApduFn: (\n apdu: Uint8Array,\n triggersDisconnection: boolean,\n abortTimeout?: number,\n ) => void;\n startReconnectionTimeout: () => void;\n cancelReconnectionTimeout: () => void;\n tryToReconnect: () => void;\n onTerminated: () => void;\n closeConnection: () => void;\n}) {\n return setup({\n types: {} as {\n context: {\n apduInProgress: Maybe<{\n apdu: Uint8Array;\n triggersDisconnection: boolean;\n abortTimeout?: number;\n responseCallback: (response: Either<DmkError, ApduResponse>) => void;\n }>;\n apduResponse: Maybe<ApduResponse>;\n };\n events: Events;\n },\n actions: {\n // event transitions\n startTimer: () => {\n startReconnectionTimeout();\n },\n cancelTimer: () => {\n cancelReconnectionTimeout();\n },\n reconnectionTimeoutEvent: emit({ type: \"ReconnectionTimedOut\" }),\n sendApdu: ({ context }) => {\n context.apduInProgress.map(({ apdu, abortTimeout }) => {\n sendApduFn(apdu, false, abortTimeout);\n });\n },\n sendApduResponse: (\n { context },\n params: { response: Either<DmkError, ApduResponse> },\n ) => {\n context.apduInProgress.map(({ responseCallback }) =>\n responseCallback(params.response),\n );\n },\n sendGetAppAndVersion: () => {\n sendApduFn(new GetAppAndVersionCommand().getApdu().getRawApdu(), false);\n },\n tryToReconnect: () => {\n tryToReconnect();\n },\n clearApduInProgress: assign({\n apduInProgress: Nothing,\n }),\n clearApduResponse: assign({\n apduResponse: Nothing,\n }),\n signalTermination: () => {\n onTerminated();\n },\n closeConnection: () => {\n closeConnection(); // ASK: how do we handle errors ?\n },\n },\n guards: {\n isApduThatTriggersDisconnection: ({ context, event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return context.apduInProgress.caseOf({\n /**\n * If the apdu is known as one that triggers a disconnection,\n * and if it's a success response,\n * then will trigger a disconnection (on Ledger OS prior to the IO revamp).\n */\n Just: ({ triggersDisconnection, apdu }) =>\n (triggersDisconnection ||\n CommandUtils.isApduThatTriggersDisconnection(apdu)) &&\n CommandUtils.isSuccessResponse(event.apduResponse),\n Nothing: () => false,\n });\n },\n isSendApduBusyError: ({ event }) => {\n if (event.type !== \"ApduResponseReceived\") {\n return false;\n }\n return (\n event.apduResponse.statusCode[0] === 0x66 &&\n event.apduResponse.statusCode[1] === 0x01\n );\n },\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QTANwJYGMwGED2AdgWJgC7qEB0+RJpkAxACJpZgukCGmAFpANoAGALqJQABzyx05QmJAAPRAA4A7AGZKywQEYAnAFYATMoAsBg6fUA2ADQgAnolUnKBjUdXXVpnUb0aAL6B9igY2DTEZBQE1IRR9BAMAMpgBBAAguIQAK44nAA2BQIi8pLSsgTySgjW6oKU6uo61kbWyh06Vsr2TgjqAZR6HUaWXcrqBmrBoawR8XQxcbRkjDgFUrgL0YT5RSWiSCDlMjHVKnrWjaO6ev6qlnp6vYim1qaN9YLqGuPKOjpVDMQGE2JFFlRUul0AQoFlcgx4TkAEpwSQEWBgVHYdCoA5lKSnORHGpNVSUPwGXQDQSmNTDF4IZTWPRDJotUw+HwAnTA0HzFaVShQiAwuHZHKIiWo2DozHYsC4gQ6Q4SQmVc79TxDIzqG6eJq+VSM94NPQ6CYuUzmQGCax8uZbQVLEVipFS3Ku2EAUQATr68L6hKrjuqziTEJNNHrTG1dIIDE8jLTGVTlJQboI2i56QZeSEQY7wTtYl7xQiWOF2GAuLx8UcThqIwh-OmdBZPF0qQCBoydIJlAZKK0jP4bHntBaHVXi0Ky+71ptZzE9sUIMGCRVw6Aau2dJQ6WZlMM-D9+89HIh++mbndVHpdNYLAnp2DtnO0qLYe6RUjV-W1S3Ykd0QABac1KFpbx3kHCxumNS9ak5SDTHNax0NUDRfFMV8BQSJYAHVOFOWEADFA2xd8YmYR0MlIWs+HXUoGzDYDFEQQx90mVozABJ9BAvPo6iuFpRgtQRdDUWNcKdfCqCIkioHI31KOdQgUk-P9CjXDcWKAqpmx0dR-gpCTaXNUxvh7RkvCHWlaWM9RfC6dCZOXeTiPIMiKJIKj1NUuSCAAFXQABbSAAHkclIXTAKJAyQIQLpBHJAEXB8AS1HvdRGT0a0D2ZZpBxjSc3L82IFK8pSfMwcqGEXTF3IIf8mJDRtt3YpLLPJZMWkmTtzJyxD+1UBofifVQOm8YyWjKtSKs8sVlICiECAImQeAARRyMAdogX8JRoqs6IYgDQ30zUjJ8CkWQmYZbOsFLGWzUyzE5bssx8ObAsoSqlpq8r1tILadr2g6ERWksQvCiAopi5i4qbRKjH7Bo4N1dsvFjOxEIeIwUPQ9o9AGSYvG+1bfsW7yVN8+agZB3bIHByUGtk1aWti874s1FGJOHYy6gTLo3lMVN7wPBNVAtbRRg0IEC35NmS0pxTltpwL6e2xn9s0w7mY5hGuaRzrAWZIYBJpc0pd1E18tNMZLOMAwnOCAsCDwFB4CORWms3bnm1AozWSgrHYMsYyEL6FGKXcDleMMO5rXJ5XZ0gP3jZqB4evaLwXEeqwnJNKYDypWlzHePwcIVotyuFT83QldOOpqWNU30A8rEmrMjPcAJk6FP7qch432rY3dxnN1onlaZ9idy5NILuCxl+UEwrH7wiqeqmnarpjatbB3Xcibser3eckfmd3xOkrnpce0DMjHMeoAgLjeqCCsBfVCmFOESE+EqdSfnmNwLJjBPBSs0QwuV3CQWPN3AwT4LTtldoEIAA */\n id: \"deviceConnection\",\n initial: \"Connected\",\n context: {\n apduInProgress: Nothing,\n apduResponse: Nothing,\n },\n states: {\n Connected: {\n on: {\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n SendApduCalled: {\n target: \"SendingApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n SendingApdu: {\n entry: \"sendApdu\",\n on: {\n ApduResponseReceived: [\n {\n guard: \"isApduThatTriggersDisconnection\",\n target: \"WaitingForDisconnection\",\n actions: [\n assign({\n apduResponse: ({ event }) => Maybe.of(event.apduResponse),\n }),\n ],\n },\n {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Right(event.apduResponse),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n ],\n },\n ],\n ApduSendingError: {\n target: \"Connected\",\n actions: [\n {\n type: \"sendApduResponse\",\n // https://stately.ai/docs/actions#dynamic-action-parameters\n params: ({ event }) => {\n return {\n response: Left(event.error),\n };\n },\n },\n \"clearApduInProgress\",\n ],\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n WaitingForDisconnection: {\n entry: [\"sendGetAppAndVersion\"],\n exit: [\n {\n type: \"sendApduResponse\",\n params: ({ context }) => {\n return {\n response: context.apduResponse.caseOf({\n Just: (apduResponse) => Right(apduResponse),\n Nothing: () => Left(new UnknownDeviceExchangeError()),\n }),\n };\n },\n },\n { type: \"clearApduInProgress\" },\n { type: \"clearApduResponse\" },\n ],\n on: {\n ApduResponseReceived: [\n {\n guard: \"isSendApduBusyError\",\n actions: [\"sendGetAppAndVersion\"],\n target: \"WaitingForDisconnection\",\n },\n {\n target: \"Connected\",\n },\n ],\n ApduSendingError: [\n {\n target: \"WaitingForReconnection\",\n },\n ],\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n DeviceDisconnected: {\n target: \"WaitingForReconnection\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnection: {\n entry: [\"startTimer\", \"tryToReconnect\"],\n on: {\n DeviceConnected: {\n target: \"Connected\",\n actions: \"cancelTimer\",\n },\n SendApduCalled: {\n target: \"WaitingForReconnectionWithQueuedSendApdu\",\n actions: assign({\n apduInProgress: ({ event }) => {\n return Maybe.of({\n apdu: event.apdu,\n triggersDisconnection: event.triggersDisconnection,\n abortTimeout: event.abortTimeout,\n responseCallback: event.responseCallback,\n });\n },\n }),\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n },\n },\n },\n WaitingForReconnectionWithQueuedSendApdu: {\n on: {\n DeviceConnected: {\n target: \"SendingApdu\",\n actions: \"cancelTimer\",\n },\n ReconnectionTimedOut: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedBeforeSendingApdu()),\n },\n },\n {\n type: \"clearApduInProgress\",\n },\n ],\n },\n CloseConnectionCalled: {\n target: \"Terminated\",\n actions: [\n {\n type: \"sendApduResponse\",\n params: {\n response: Left(new DeviceDisconnectedWhileSendingError()),\n },\n },\n \"clearApduInProgress\",\n ],\n },\n SendApduCalled: {\n actions: ({ event }) => {\n event.responseCallback(Left(new AlreadySendingApduError()));\n },\n },\n },\n },\n // TODO: ADD INACTIVE STATE\n Terminated: {\n entry: [\"signalTermination\", \"closeConnection\"],\n type: \"final\",\n },\n },\n });\n}\n"],
5
+ "mappings": "AACA,OAAsB,QAAAA,EAAM,SAAAC,EAAO,WAAAC,EAAS,SAAAC,MAAa,YACzD,OAAqB,UAAAC,EAAQ,eAAAC,EAAa,QAAAC,EAAM,SAAAC,MAAa,SAE7D,OAAS,2BAAAC,MAA+B,0CACxC,OAAS,gBAAAC,MAAoB,kCAE7B,OAAwB,8BAAAC,MAAkC,aAI1D,OACE,2BAAAC,EACA,uCAAAC,EACA,uCAAAC,MACK,WAIP,MAAMC,EAA2B,IAqD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,CAAyB,CAAC,CAC5D,CACF,CACF,CACF,EAEA,WAAY,CACV,MAAO,CAAC,oBAAqB,iBAAiB,EAC9C,KAAM,OACR,CACF,CACF,CAAC,CACH",
6
+ "names": ["Left", "Maybe", "Nothing", "Right", "assign", "createActor", "emit", "setup", "GetAppAndVersionCommand", "CommandUtils", "UnknownDeviceExchangeError", "AlreadySendingApduError", "DeviceDisconnectedBeforeSendingApdu", "DeviceDisconnectedWhileSendingError", "TRANSPORT_BUSY_WAIT_TIME", "DeviceConnectionStateMachine", "params", "makeStateMachine", "apdu", "triggersDisconnection", "abortTimeout", "response", "error", "apduResponse", "dependencies", "resolve", "promise", "responseCallback", "sendApduFn", "startReconnectionTimeout", "cancelReconnectionTimeout", "tryToReconnect", "onTerminated", "closeConnection", "context", "event"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{Left as p,Right as n}from"purify-ts/Either";import{afterEach as U,beforeEach as w,describe as m,expect as e,it as c,vi as i}from"vitest";import{ApduResponse as x}from"../../device-session/ApduResponse";import{DeviceConnectionStateMachine as D}from"./DeviceConnectionStateMachine";import{AlreadySendingApduError as y,DeviceDisconnectedWhileSendingError as f}from"./Errors";m("DeviceConnectionStateMachine",()=>{let d;const s={sendApdu:i.fn(),getDependencies:i.fn(),setDependencies:i.fn(),closeConnection:i.fn(),setupConnection:i.fn()},t=new x({statusCode:Uint8Array.from([144,0]),data:new Uint8Array}),v=new x({statusCode:Uint8Array.from([102,1]),data:new Uint8Array});w(()=>{i.useFakeTimers(),d=new D({deviceId:"deviceId",deviceApduSender:s,timeoutDuration:1e3,tryToReconnect:i.fn(),onTerminated:i.fn()})}),U(()=>{i.useRealTimers(),i.restoreAllMocks()}),m("Send APDUs",()=>{c("should send APDU successfully",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const a=await d.sendApdu(o);e(s.sendApdu).toHaveBeenCalledTimes(1),e(a).toStrictEqual(n(t))}),c("should send several APDUs successfully",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const r=await d.sendApdu(o),u=await d.sendApdu(a);e(s.sendApdu).toHaveBeenCalledTimes(2),e(r).toStrictEqual(n(t)),e(u).toStrictEqual(n(t))}),c("should not send several APDUs in parallel",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const r=d.sendApdu(o),u=await d.sendApdu(a),l=await r;e(s.sendApdu).toHaveBeenCalledTimes(1),e(l).toStrictEqual(n(t)),e(u).toStrictEqual(p(new y))}),c("Disconnected while sending APDU",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const a=d.sendApdu(o);d.eventDeviceDisconnected();const r=await a;e(s.sendApdu).toHaveBeenCalledTimes(1),e(r).toStrictEqual(p(new f))}),c("Request disconnection while sending APDU",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const a=d.sendApdu(o);d.closeConnection();const r=await a;e(s.sendApdu).toHaveBeenCalledTimes(1),e(r).toStrictEqual(p(new f))})}),m("Send APDUs triggering disconnection",()=>{c("should send one APDU successfully",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const a=await d.sendApdu(o,!0);e(s.sendApdu).toHaveBeenCalledTimes(2),e(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),e(a).toStrictEqual(n(t))}),c("should send several APDUs successfully",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce(n(t)).mockRejectedValueOnce(new Error("Transport error")).mockResolvedValueOnce(n(t));const r=d.sendApdu(o,!0);await Promise.resolve(),d.eventDeviceDisconnected(),d.eventDeviceConnected();const u=d.sendApdu(a),l=await r,A=await u;e(s.sendApdu).toHaveBeenCalledTimes(3),e(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(l).toStrictEqual(n(t)),e(A).toStrictEqual(n(t))}),c("should send a second APDU after reconnection",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce(n(t)).mockRejectedValueOnce(new Error("Transport error")).mockResolvedValueOnce(n(t));const r=await d.sendApdu(o,!0);d.eventDeviceDisconnected(),d.eventDeviceConnected();const u=await d.sendApdu(a);e(s.sendApdu).toHaveBeenCalledTimes(3),e(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(r).toStrictEqual(n(t)),e(u).toStrictEqual(n(t))}),c("should send a second APDU without reconnection, after GetAppAndVersion response",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce(n(t)).mockResolvedValueOnce(n(t)).mockResolvedValueOnce(n(t));const r=await d.sendApdu(o,!0),u=await d.sendApdu(a);e(s.sendApdu).toHaveBeenCalledTimes(3),e(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(r).toStrictEqual(n(t)),e(u).toStrictEqual(n(t))}),c("should send a second APDU without reconnection, after GetAppAndVersion retries",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce(n(t)).mockResolvedValueOnce(n(v)).mockResolvedValueOnce(n(v)).mockResolvedValueOnce(n(t)).mockResolvedValueOnce(n(t));const r=await d.sendApdu(o,!0),u=await d.sendApdu(a);e(s.sendApdu).toHaveBeenCalledTimes(5),e(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(r).toStrictEqual(n(t)),e(u).toStrictEqual(n(t))}),c("should not send several APDUs in parallel",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const r=d.sendApdu(o,!0),u=await d.sendApdu(a),l=await r;e(s.sendApdu).toHaveBeenCalledTimes(2),e(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),e(l).toStrictEqual(n(t)),e(u).toStrictEqual(p(new y))}),c("should send another APDU in promise handler",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));let r;const u=await d.sendApdu(o,!0).then(A=>(r=d.sendApdu(a),A));d.eventDeviceDisconnected(),d.eventDeviceConnected();const l=await r;e(s.sendApdu).toHaveBeenCalledTimes(3),e(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(u).toStrictEqual(n(t)),e(l).toStrictEqual(n(t))}),c("send an APDU while device is reconnecting",async()=>{const o=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t)),d.eventDeviceDisconnected();const a=d.sendApdu(o,!0);d.eventDeviceConnected();const r=await a;e(s.sendApdu).toHaveBeenCalledTimes(2),e(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),e(r).toStrictEqual(n(t))}),c("Close while an APDU is waiting for reconnection",async()=>{const o=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));let r;const u=d.sendApdu(o,!0);await Promise.resolve(),d.eventDeviceDisconnected();const l=await u;r=d.sendApdu(a),d.closeConnection();const A=await r;e(s.sendApdu.mock.calls).toEqual([[o,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),e(l).toStrictEqual(n(t)),e(A).toStrictEqual(p(new f))})})});
1
+ import{Left as A,Right as n}from"purify-ts/Either";import{afterEach as y,beforeEach as U,describe as m,expect as e,it as c,vi as i}from"vitest";import{ApduResponse as x}from"../../device-session/ApduResponse";import{DeviceConnectionStateMachine as w}from"./DeviceConnectionStateMachine";import{DeviceDisconnectedWhileSendingError as f}from"./Errors";m("DeviceConnectionStateMachine",()=>{let o;const s={sendApdu:i.fn(),getDependencies:i.fn(),setDependencies:i.fn(),closeConnection:i.fn(),setupConnection:i.fn()},t=new x({statusCode:Uint8Array.from([144,0]),data:new Uint8Array}),v=new x({statusCode:Uint8Array.from([102,1]),data:new Uint8Array});U(()=>{i.useFakeTimers(),o=new w({deviceId:"deviceId",deviceApduSender:s,timeoutDuration:1e3,tryToReconnect:i.fn(),onTerminated:i.fn()})}),y(()=>{i.useRealTimers(),i.restoreAllMocks()}),m("Send APDUs",()=>{c("should send APDU successfully",async()=>{const d=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const a=await o.sendApdu(d);e(s.sendApdu).toHaveBeenCalledTimes(1),e(a).toStrictEqual(n(t))}),c("should send several APDUs successfully",async()=>{const d=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const r=await o.sendApdu(d),u=await o.sendApdu(a);e(s.sendApdu).toHaveBeenCalledTimes(2),e(r).toStrictEqual(n(t)),e(u).toStrictEqual(n(t))}),c("should not send several APDUs in parallel",async()=>{const d=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const r=o.sendApdu(d),u=o.sendApdu(a),l=await r,p=await u;e(s.sendApdu).toHaveBeenCalledTimes(2),e(l).toStrictEqual(n(t)),e(p).toStrictEqual(n(t))}),c("Disconnected while sending APDU",async()=>{const d=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const a=o.sendApdu(d);o.eventDeviceDisconnected();const r=await a;e(s.sendApdu).toHaveBeenCalledTimes(1),e(r).toStrictEqual(A(new f))}),c("Request disconnection while sending APDU",async()=>{const d=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const a=o.sendApdu(d);o.closeConnection();const r=await a;e(s.sendApdu).toHaveBeenCalledTimes(1),e(r).toStrictEqual(A(new f))})}),m("Send APDUs triggering disconnection",()=>{c("should send one APDU successfully",async()=>{const d=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const a=await o.sendApdu(d,!0);e(s.sendApdu).toHaveBeenCalledTimes(2),e(s.sendApdu.mock.calls).toEqual([[d,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),e(a).toStrictEqual(n(t))}),c("should send several APDUs successfully",async()=>{const d=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce(n(t)).mockRejectedValueOnce(new Error("Transport error")).mockResolvedValueOnce(n(t));const r=o.sendApdu(d,!0);await Promise.resolve(),o.eventDeviceDisconnected(),o.eventDeviceConnected();const u=o.sendApdu(a),l=await r,p=await u;e(s.sendApdu).toHaveBeenCalledTimes(3),e(s.sendApdu.mock.calls).toEqual([[d,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(l).toStrictEqual(n(t)),e(p).toStrictEqual(n(t))}),c("should send a second APDU after reconnection",async()=>{const d=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce(n(t)).mockRejectedValueOnce(new Error("Transport error")).mockResolvedValueOnce(n(t));const r=await o.sendApdu(d,!0);o.eventDeviceDisconnected(),o.eventDeviceConnected();const u=await o.sendApdu(a);e(s.sendApdu).toHaveBeenCalledTimes(3),e(s.sendApdu.mock.calls).toEqual([[d,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(r).toStrictEqual(n(t)),e(u).toStrictEqual(n(t))}),c("should send a second APDU without reconnection, after GetAppAndVersion response",async()=>{const d=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce(n(t)).mockResolvedValueOnce(n(t)).mockResolvedValueOnce(n(t));const r=await o.sendApdu(d,!0),u=await o.sendApdu(a);e(s.sendApdu).toHaveBeenCalledTimes(3),e(s.sendApdu.mock.calls).toEqual([[d,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(r).toStrictEqual(n(t)),e(u).toStrictEqual(n(t))}),c("should send a second APDU without reconnection, after GetAppAndVersion retries",async()=>{const d=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValueOnce(n(t)).mockResolvedValueOnce(n(v)).mockResolvedValueOnce(n(v)).mockResolvedValueOnce(n(t)).mockResolvedValueOnce(n(t));const r=await o.sendApdu(d,!0),u=await o.sendApdu(a);e(s.sendApdu).toHaveBeenCalledTimes(5),e(s.sendApdu.mock.calls).toEqual([[d,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(r).toStrictEqual(n(t)),e(u).toStrictEqual(n(t))}),c("should not send several APDUs in parallel",async()=>{const d=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));const r=o.sendApdu(d,!0),u=o.sendApdu(a),l=await r,p=await u;e(s.sendApdu).toHaveBeenCalledTimes(3),e(s.sendApdu.mock.calls).toEqual([[d,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(l).toStrictEqual(n(t)),e(p).toStrictEqual(n(t))}),c("should send another APDU in promise handler",async()=>{const d=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));let r;const u=await o.sendApdu(d,!0).then(p=>(r=o.sendApdu(a),p));o.eventDeviceDisconnected(),o.eventDeviceConnected();const l=await r;e(s.sendApdu).toHaveBeenCalledTimes(3),e(s.sendApdu.mock.calls).toEqual([[d,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0],[a,!1,void 0]]),e(u).toStrictEqual(n(t)),e(l).toStrictEqual(n(t))}),c("send an APDU while device is reconnecting",async()=>{const d=Uint8Array.from([1,2,3,4]);s.sendApdu.mockResolvedValue(n(t)),o.eventDeviceDisconnected();const a=o.sendApdu(d,!0);o.eventDeviceConnected();const r=await a;e(s.sendApdu).toHaveBeenCalledTimes(2),e(s.sendApdu.mock.calls).toEqual([[d,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),e(r).toStrictEqual(n(t))}),c("Close while an APDU is waiting for reconnection",async()=>{const d=Uint8Array.from([1,2,3,4]),a=Uint8Array.from([9,2,3,4]);s.sendApdu.mockResolvedValue(n(t));let r;const u=o.sendApdu(d,!0);await Promise.resolve(),o.eventDeviceDisconnected();const l=await u;r=o.sendApdu(a),o.closeConnection();const p=await r;e(s.sendApdu.mock.calls).toEqual([[d,!1,void 0],[Uint8Array.from([176,1,0,0,0]),!1,void 0]]),e(l).toStrictEqual(n(t)),e(p).toStrictEqual(A(new f))})})});
2
2
  //# sourceMappingURL=DeviceConnectionStateMachine.test.js.map