@ledgerhq/device-management-kit 1.7.1 → 1.9.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 (201) hide show
  1. package/README.md +0 -3
  2. package/lib/cjs/package.json +1 -1
  3. package/lib/cjs/src/api/DeviceManagementKitBuilder.test.js +1 -1
  4. package/lib/cjs/src/api/DeviceManagementKitBuilder.test.js.map +2 -2
  5. package/lib/cjs/src/api/device-action/__test-utils__/setupTestMachine.js +1 -1
  6. package/lib/cjs/src/api/device-action/__test-utils__/setupTestMachine.js.map +3 -3
  7. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js +1 -1
  8. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  9. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js +1 -1
  10. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js.map +3 -3
  11. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js +1 -1
  12. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js.map +3 -3
  13. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/types.js +1 -1
  14. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/types.js.map +2 -2
  15. package/lib/cjs/src/api/device-action/os/InstallLanguagePackage/types.js +1 -1
  16. package/lib/cjs/src/api/device-action/os/InstallLanguagePackage/types.js.map +3 -3
  17. package/lib/cjs/src/api/device-action/task/GetFirmwareMetadataTask.js +1 -1
  18. package/lib/cjs/src/api/device-action/task/GetFirmwareMetadataTask.js.map +3 -3
  19. package/lib/cjs/src/api/device-action/task/GetFirmwareMetadataTask.test.js +1 -1
  20. package/lib/cjs/src/api/device-action/task/GetFirmwareMetadataTask.test.js.map +3 -3
  21. package/lib/cjs/src/api/index.js +1 -1
  22. package/lib/cjs/src/api/index.js.map +3 -3
  23. package/lib/cjs/src/api/types.js +1 -1
  24. package/lib/cjs/src/api/types.js.map +3 -3
  25. package/lib/cjs/src/api/utils/ApplicationChecker.js +1 -1
  26. package/lib/cjs/src/api/utils/ApplicationChecker.js.map +3 -3
  27. package/lib/cjs/src/api/utils/ApplicationChecker.test.js +1 -1
  28. package/lib/cjs/src/api/utils/ApplicationChecker.test.js.map +2 -2
  29. package/lib/cjs/src/api/utils/apduLogs.js +1 -1
  30. package/lib/cjs/src/api/utils/apduLogs.js.map +3 -3
  31. package/lib/cjs/src/api/utils/apduLogs.test.js +1 -1
  32. package/lib/cjs/src/api/utils/apduLogs.test.js.map +3 -3
  33. package/lib/cjs/src/di.test.js +2 -0
  34. package/lib/cjs/src/di.test.js.map +7 -0
  35. package/lib/cjs/src/internal/device-session/model/DeviceSession.js +1 -1
  36. package/lib/cjs/src/internal/device-session/model/DeviceSession.js.map +3 -3
  37. package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.js +1 -1
  38. package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.js.map +2 -2
  39. package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.test.js +1 -1
  40. package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.test.js.map +2 -2
  41. package/lib/cjs/src/internal/manager-api/data/HttpManagerApiDataSource.js +1 -1
  42. package/lib/cjs/src/internal/manager-api/data/HttpManagerApiDataSource.js.map +2 -2
  43. package/lib/cjs/src/internal/manager-api/data/HttpManagerApiDataSource.test.js +1 -1
  44. package/lib/cjs/src/internal/manager-api/data/HttpManagerApiDataSource.test.js.map +2 -2
  45. package/lib/cjs/src/internal/manager-api/data/ManagerApiDataSource.js +1 -1
  46. package/lib/cjs/src/internal/manager-api/data/ManagerApiDataSource.js.map +1 -1
  47. package/lib/cjs/src/internal/manager-api/model/Const.js +1 -1
  48. package/lib/cjs/src/internal/manager-api/model/Const.js.map +2 -2
  49. package/lib/cjs/src/internal/manager-api/model/Firmware.js +1 -1
  50. package/lib/cjs/src/internal/manager-api/model/Firmware.js.map +1 -1
  51. package/lib/cjs/src/internal/manager-api/service/DefaultManagerApiService.js +1 -1
  52. package/lib/cjs/src/internal/manager-api/service/DefaultManagerApiService.js.map +2 -2
  53. package/lib/cjs/src/internal/manager-api/service/DefaultManagerApiService.test.js +1 -1
  54. package/lib/cjs/src/internal/manager-api/service/DefaultManagerApiService.test.js.map +3 -3
  55. package/lib/cjs/src/internal/manager-api/service/ManagerApiService.js +1 -1
  56. package/lib/cjs/src/internal/manager-api/service/ManagerApiService.js.map +1 -1
  57. package/lib/cjs/src/internal/secure-channel/model/Errors.js +1 -1
  58. package/lib/cjs/src/internal/secure-channel/model/Errors.js.map +2 -2
  59. package/lib/cjs/src/internal/secure-channel/service/DefaultSecureChannelService.js +1 -1
  60. package/lib/cjs/src/internal/secure-channel/service/DefaultSecureChannelService.js.map +3 -3
  61. package/lib/cjs/src/internal/secure-channel/service/SecureChannelService.js +1 -1
  62. package/lib/cjs/src/internal/secure-channel/service/SecureChannelService.js.map +1 -1
  63. package/lib/esm/package.json +1 -1
  64. package/lib/esm/src/api/DeviceManagementKitBuilder.test.js +1 -1
  65. package/lib/esm/src/api/DeviceManagementKitBuilder.test.js.map +2 -2
  66. package/lib/esm/src/api/device-action/__test-utils__/setupTestMachine.js +1 -1
  67. package/lib/esm/src/api/device-action/__test-utils__/setupTestMachine.js.map +3 -3
  68. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js +1 -1
  69. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  70. package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js +1 -1
  71. package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js.map +3 -3
  72. package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js +1 -1
  73. package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js.map +3 -3
  74. package/lib/esm/src/api/device-action/os/GetDeviceStatus/types.js +1 -1
  75. package/lib/esm/src/api/device-action/os/GetDeviceStatus/types.js.map +2 -2
  76. package/lib/esm/src/api/device-action/os/InstallLanguagePackage/types.js +1 -1
  77. package/lib/esm/src/api/device-action/os/InstallLanguagePackage/types.js.map +3 -3
  78. package/lib/esm/src/api/device-action/task/GetFirmwareMetadataTask.js +1 -1
  79. package/lib/esm/src/api/device-action/task/GetFirmwareMetadataTask.js.map +3 -3
  80. package/lib/esm/src/api/device-action/task/GetFirmwareMetadataTask.test.js +1 -1
  81. package/lib/esm/src/api/device-action/task/GetFirmwareMetadataTask.test.js.map +3 -3
  82. package/lib/esm/src/api/index.js +1 -1
  83. package/lib/esm/src/api/index.js.map +3 -3
  84. package/lib/esm/src/api/types.js +1 -0
  85. package/lib/esm/src/api/types.js.map +4 -4
  86. package/lib/esm/src/api/utils/ApplicationChecker.js +1 -1
  87. package/lib/esm/src/api/utils/ApplicationChecker.js.map +3 -3
  88. package/lib/esm/src/api/utils/ApplicationChecker.test.js +1 -1
  89. package/lib/esm/src/api/utils/ApplicationChecker.test.js.map +2 -2
  90. package/lib/esm/src/api/utils/apduLogs.js +1 -1
  91. package/lib/esm/src/api/utils/apduLogs.js.map +3 -3
  92. package/lib/esm/src/api/utils/apduLogs.test.js +1 -1
  93. package/lib/esm/src/api/utils/apduLogs.test.js.map +3 -3
  94. package/lib/esm/src/di.test.js +2 -0
  95. package/lib/esm/src/di.test.js.map +7 -0
  96. package/lib/esm/src/internal/device-session/model/DeviceSession.js +1 -1
  97. package/lib/esm/src/internal/device-session/model/DeviceSession.js.map +3 -3
  98. package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.js +1 -1
  99. package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.js.map +2 -2
  100. package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.test.js +1 -1
  101. package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.test.js.map +2 -2
  102. package/lib/esm/src/internal/manager-api/data/HttpManagerApiDataSource.js +1 -1
  103. package/lib/esm/src/internal/manager-api/data/HttpManagerApiDataSource.js.map +3 -3
  104. package/lib/esm/src/internal/manager-api/data/HttpManagerApiDataSource.test.js +1 -1
  105. package/lib/esm/src/internal/manager-api/data/HttpManagerApiDataSource.test.js.map +3 -3
  106. package/lib/esm/src/internal/manager-api/model/Const.js +1 -1
  107. package/lib/esm/src/internal/manager-api/model/Const.js.map +2 -2
  108. package/lib/esm/src/internal/manager-api/service/DefaultManagerApiService.js +1 -1
  109. package/lib/esm/src/internal/manager-api/service/DefaultManagerApiService.js.map +2 -2
  110. package/lib/esm/src/internal/manager-api/service/DefaultManagerApiService.test.js +1 -1
  111. package/lib/esm/src/internal/manager-api/service/DefaultManagerApiService.test.js.map +3 -3
  112. package/lib/esm/src/internal/secure-channel/model/Errors.js +1 -1
  113. package/lib/esm/src/internal/secure-channel/model/Errors.js.map +3 -3
  114. package/lib/esm/src/internal/secure-channel/service/DefaultSecureChannelService.js +1 -1
  115. package/lib/esm/src/internal/secure-channel/service/DefaultSecureChannelService.js.map +3 -3
  116. package/lib/types/src/api/device-action/__test-utils__/setupTestMachine.d.ts +3 -0
  117. package/lib/types/src/api/device-action/__test-utils__/setupTestMachine.d.ts.map +1 -1
  118. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts +3 -1
  119. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts.map +1 -1
  120. package/lib/types/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.d.ts +0 -9
  121. package/lib/types/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.d.ts.map +1 -1
  122. package/lib/types/src/api/device-action/os/GetDeviceStatus/types.d.ts +4 -4
  123. package/lib/types/src/api/device-action/os/GetDeviceStatus/types.d.ts.map +1 -1
  124. package/lib/types/src/api/device-action/os/InstallLanguagePackage/types.d.ts +1 -0
  125. package/lib/types/src/api/device-action/os/InstallLanguagePackage/types.d.ts.map +1 -1
  126. package/lib/types/src/api/device-action/task/GetFirmwareMetadataTask.d.ts +2 -0
  127. package/lib/types/src/api/device-action/task/GetFirmwareMetadataTask.d.ts.map +1 -1
  128. package/lib/types/src/api/index.d.ts +3 -4
  129. package/lib/types/src/api/index.d.ts.map +1 -1
  130. package/lib/types/src/api/types.d.ts +1 -1
  131. package/lib/types/src/api/types.d.ts.map +1 -1
  132. package/lib/types/src/api/utils/ApplicationChecker.d.ts +17 -0
  133. package/lib/types/src/api/utils/ApplicationChecker.d.ts.map +1 -1
  134. package/lib/types/src/api/utils/apduLogs.d.ts +15 -0
  135. package/lib/types/src/api/utils/apduLogs.d.ts.map +1 -1
  136. package/lib/types/src/di.test.d.ts +2 -0
  137. package/lib/types/src/di.test.d.ts.map +1 -0
  138. package/lib/types/src/internal/device-session/model/DeviceSession.d.ts.map +1 -1
  139. package/lib/types/src/internal/device-session/model/DeviceSessionRefresher.d.ts.map +1 -1
  140. package/lib/types/src/internal/manager-api/data/HttpManagerApiDataSource.d.ts +2 -2
  141. package/lib/types/src/internal/manager-api/data/HttpManagerApiDataSource.d.ts.map +1 -1
  142. package/lib/types/src/internal/manager-api/data/ManagerApiDataSource.d.ts +4 -4
  143. package/lib/types/src/internal/manager-api/data/ManagerApiDataSource.d.ts.map +1 -1
  144. package/lib/types/src/internal/manager-api/model/Const.d.ts +1 -1
  145. package/lib/types/src/internal/manager-api/model/Const.d.ts.map +1 -1
  146. package/lib/types/src/internal/manager-api/model/Firmware.d.ts +3 -0
  147. package/lib/types/src/internal/manager-api/model/Firmware.d.ts.map +1 -1
  148. package/lib/types/src/internal/manager-api/service/DefaultManagerApiService.d.ts +2 -1
  149. package/lib/types/src/internal/manager-api/service/DefaultManagerApiService.d.ts.map +1 -1
  150. package/lib/types/src/internal/manager-api/service/ManagerApiService.d.ts +9 -3
  151. package/lib/types/src/internal/manager-api/service/ManagerApiService.d.ts.map +1 -1
  152. package/lib/types/src/internal/secure-channel/model/Errors.d.ts +8 -1
  153. package/lib/types/src/internal/secure-channel/model/Errors.d.ts.map +1 -1
  154. package/lib/types/src/internal/secure-channel/service/DefaultSecureChannelService.d.ts +1 -1
  155. package/lib/types/src/internal/secure-channel/service/DefaultSecureChannelService.d.ts.map +1 -1
  156. package/lib/types/src/internal/secure-channel/service/SecureChannelService.d.ts +2 -2
  157. package/lib/types/src/internal/secure-channel/service/SecureChannelService.d.ts.map +1 -1
  158. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  159. package/package.json +1 -1
  160. package/lib/cjs/src/api/command/os/BackupStorageCommand.js +0 -2
  161. package/lib/cjs/src/api/command/os/BackupStorageCommand.js.map +0 -7
  162. package/lib/cjs/src/api/command/os/BackupStorageCommand.test.js +0 -2
  163. package/lib/cjs/src/api/command/os/BackupStorageCommand.test.js.map +0 -7
  164. package/lib/cjs/src/api/command/os/GetAppStorageInfoCommand.js +0 -2
  165. package/lib/cjs/src/api/command/os/GetAppStorageInfoCommand.js.map +0 -7
  166. package/lib/cjs/src/api/command/os/GetAppStorageInfoCommand.test.js +0 -2
  167. package/lib/cjs/src/api/command/os/GetAppStorageInfoCommand.test.js.map +0 -7
  168. package/lib/cjs/src/api/device-action/task/BackupAppStorageTask.js +0 -2
  169. package/lib/cjs/src/api/device-action/task/BackupAppStorageTask.js.map +0 -7
  170. package/lib/cjs/src/api/device-action/task/BackupAppStorageTask.test.js +0 -2
  171. package/lib/cjs/src/api/device-action/task/BackupAppStorageTask.test.js.map +0 -7
  172. package/lib/cjs/src/api/storage/KeyValueStorage.js +0 -2
  173. package/lib/cjs/src/api/storage/KeyValueStorage.js.map +0 -7
  174. package/lib/esm/src/api/command/os/BackupStorageCommand.js +0 -2
  175. package/lib/esm/src/api/command/os/BackupStorageCommand.js.map +0 -7
  176. package/lib/esm/src/api/command/os/BackupStorageCommand.test.js +0 -2
  177. package/lib/esm/src/api/command/os/BackupStorageCommand.test.js.map +0 -7
  178. package/lib/esm/src/api/command/os/GetAppStorageInfoCommand.js +0 -2
  179. package/lib/esm/src/api/command/os/GetAppStorageInfoCommand.js.map +0 -7
  180. package/lib/esm/src/api/command/os/GetAppStorageInfoCommand.test.js +0 -2
  181. package/lib/esm/src/api/command/os/GetAppStorageInfoCommand.test.js.map +0 -7
  182. package/lib/esm/src/api/device-action/task/BackupAppStorageTask.js +0 -2
  183. package/lib/esm/src/api/device-action/task/BackupAppStorageTask.js.map +0 -7
  184. package/lib/esm/src/api/device-action/task/BackupAppStorageTask.test.js +0 -2
  185. package/lib/esm/src/api/device-action/task/BackupAppStorageTask.test.js.map +0 -7
  186. package/lib/esm/src/api/storage/KeyValueStorage.js +0 -2
  187. package/lib/esm/src/api/storage/KeyValueStorage.js.map +0 -7
  188. package/lib/types/src/api/command/os/BackupStorageCommand.d.ts +0 -23
  189. package/lib/types/src/api/command/os/BackupStorageCommand.d.ts.map +0 -1
  190. package/lib/types/src/api/command/os/BackupStorageCommand.test.d.ts +0 -2
  191. package/lib/types/src/api/command/os/BackupStorageCommand.test.d.ts.map +0 -1
  192. package/lib/types/src/api/command/os/GetAppStorageInfoCommand.d.ts +0 -31
  193. package/lib/types/src/api/command/os/GetAppStorageInfoCommand.d.ts.map +0 -1
  194. package/lib/types/src/api/command/os/GetAppStorageInfoCommand.test.d.ts +0 -2
  195. package/lib/types/src/api/command/os/GetAppStorageInfoCommand.test.d.ts.map +0 -1
  196. package/lib/types/src/api/device-action/task/BackupAppStorageTask.d.ts +0 -23
  197. package/lib/types/src/api/device-action/task/BackupAppStorageTask.d.ts.map +0 -1
  198. package/lib/types/src/api/device-action/task/BackupAppStorageTask.test.d.ts +0 -2
  199. package/lib/types/src/api/device-action/task/BackupAppStorageTask.test.d.ts.map +0 -1
  200. package/lib/types/src/api/storage/KeyValueStorage.d.ts +0 -7
  201. package/lib/types/src/api/storage/KeyValueStorage.d.ts.map +0 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/device-session/model/DeviceSession.ts"],
4
- "sourcesContent": ["import { type Either } from \"purify-ts\";\nimport {\n BehaviorSubject,\n from,\n lastValueFrom,\n type Observable,\n timeout,\n} from \"rxjs\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { type Command } from \"@api/command/Command\";\nimport { type CommandResult } from \"@api/command/model/CommandResult\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nimport { type DeviceSessionId } from \"@api/device-session/types\";\nimport { type DmkError } from \"@api/Error\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport {\n SendApduTimeoutError,\n SendCommandTimeoutError,\n} from \"@api/transport/model/Errors\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport {\n formatApduReceivedLog,\n formatApduSendingLog,\n} from \"@api/utils/apduLogs\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { IntentQueueService } from \"@internal/device-session/service/IntentQueueService\";\nimport { RefresherService } from \"@internal/device-session/service/RefresherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DevicePinger } from \"./DevicePinger\";\nimport {\n DeviceSessionEventDispatcher,\n SessionEvents,\n} from \"./DeviceSessionEventDispatcher\";\nimport { DeviceSessionRefresher } from \"./DeviceSessionRefresher\";\nimport { DeviceSessionStateHandler } from \"./DeviceSessionStateHandler\";\n\nexport type SessionConstructorArgs = {\n connectedDevice: TransportConnectedDevice;\n id?: DeviceSessionId;\n};\n\nexport type DeviceSessionRefresherOptions = {\n isRefresherDisabled: boolean;\n pollingInterval?: number;\n};\n\ntype SendApduOptions = {\n isPolling?: boolean;\n triggersDisconnection?: boolean;\n abortTimeout?: number;\n};\n\n/**\n * Represents a session with a device.\n */\nexport class DeviceSession {\n private readonly _id: DeviceSessionId;\n private readonly _connectedDevice: TransportConnectedDevice;\n private readonly _deviceState: BehaviorSubject<DeviceSessionState>;\n private readonly _managerApiService: ManagerApiService;\n private readonly _secureChannelService: SecureChannelService;\n private readonly _logger: LoggerPublisherService;\n private readonly _loggerModuleFactory: (\n tag: string,\n ) => LoggerPublisherService;\n private readonly _refresherOptions: DeviceSessionRefresherOptions;\n private _pinger: DevicePinger;\n private _deviceSessionRefresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private readonly _intentQueueService: IntentQueueService;\n private _sessionEventDispatcher = new DeviceSessionEventDispatcher();\n private _bypassIntentQueue: boolean = false;\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n deviceSessionRefresherOptions: DeviceSessionRefresherOptions | undefined,\n intentQueueServiceFactory: (\n sessionEventDispatcher: DeviceSessionEventDispatcher,\n ) => IntentQueueService = (sessionEventDispatcher) =>\n new IntentQueueService(loggerModuleFactory, sessionEventDispatcher),\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._loggerModuleFactory = loggerModuleFactory;\n this._logger = loggerModuleFactory(\"device-session\");\n this._managerApiService = managerApiService;\n this._intentQueueService = intentQueueServiceFactory(\n this._sessionEventDispatcher,\n );\n this._secureChannelService = secureChannelService;\n this._refresherOptions = {\n ...DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n ...deviceSessionRefresherOptions,\n };\n this._deviceState = new BehaviorSubject<DeviceSessionState>({\n sessionStateType: DeviceSessionStateType.Connected,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n });\n\n this._pinger = new DevicePinger(\n loggerModuleFactory,\n connectedDevice,\n this._sessionEventDispatcher,\n (command, abortTimeout) => this.sendCommand(command, abortTimeout),\n );\n this._deviceSessionRefresher = new DeviceSessionRefresher(\n loggerModuleFactory,\n this._refresherOptions,\n this._sessionEventDispatcher,\n this._connectedDevice,\n );\n new DeviceSessionStateHandler(\n loggerModuleFactory,\n this._sessionEventDispatcher,\n this._connectedDevice,\n this._deviceState,\n (state) => this.setDeviceSessionState(state),\n );\n\n this._refresherService = new RefresherService(loggerModuleFactory, {\n start: () => this._deviceSessionRefresher.restartRefresher(),\n stop: () => this._deviceSessionRefresher.stopRefresher(),\n });\n }\n\n public async initialiseSession(): Promise<void> {\n try {\n if (this._refresherOptions.isRefresherDisabled) await this._pinger.ping();\n else this._deviceSessionRefresher.startRefresher();\n } catch (error) {\n this._logger.error(\"Error while initialising session\", {\n data: { error },\n });\n throw error;\n }\n }\n\n public get id(): DeviceSessionId {\n return this._id;\n }\n\n public get connectedDevice(): TransportConnectedDevice {\n return this._connectedDevice;\n }\n\n public get state(): Observable<DeviceSessionState> {\n return this._deviceState.asObservable();\n }\n\n public getDeviceSessionState(): DeviceSessionState {\n return this._deviceState.getValue();\n }\n\n public setDeviceSessionState(state: DeviceSessionState): void {\n this._deviceState.next(state);\n }\n\n public sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n // Bypass intent queue if flag is set\n if (this._bypassIntentQueue) {\n return this._unsafeInternalSendApdu(rawApdu, options);\n }\n return this._internalSendApdu(rawApdu, options);\n }\n\n private _internalSendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions,\n ): Promise<Either<DmkError, ApduResponse>> {\n const abortTimeout = options.abortTimeout;\n const beforeQueuedTimestamp = Date.now();\n const { observable, cancel } = this._intentQueueService.enqueue({\n type: \"send-apdu\",\n execute: () =>\n from(\n (async () => {\n const elapsedTime = Date.now() - beforeQueuedTimestamp;\n const result = await this._unsafeInternalSendApdu(rawApdu, {\n isPolling: options.isPolling,\n triggersDisconnection: options.triggersDisconnection,\n // Subtract the elapsed time to account for the time spent in the queue\n // to sync both observable and transport timeout\n abortTimeout: abortTimeout\n ? abortTimeout - elapsedTime\n : undefined,\n });\n return result;\n })(),\n ),\n });\n\n const timeoutObservable = abortTimeout\n ? observable.pipe(\n timeout({\n each: abortTimeout,\n with: () => {\n cancel();\n throw new SendApduTimeoutError();\n },\n }),\n )\n : observable;\n\n return lastValueFrom(timeoutObservable);\n }\n\n private async _unsafeInternalSendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n this._logger.debug(formatApduSendingLog(rawApdu));\n const result = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n options.abortTimeout,\n );\n\n return result\n .ifRight((response: ApduResponse) => {\n this._logger.debug(formatApduReceivedLog(response));\n if (CommandUtils.isLockedDeviceResponse(response)) {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_LOCKED,\n });\n } else {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n }\n })\n .ifLeft(() => {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_UNKNOWN,\n });\n });\n }\n\n public sendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n this._logger.debug(`[sendCommand] ${command.name}`);\n\n // Bypass intent queue if flag is set\n if (this._bypassIntentQueue) {\n return this._unsafeInternalSendCommand(command, abortTimeout);\n }\n return this._internalSendCommand(command, abortTimeout);\n }\n\n private _internalSendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const beforeQueuedTimestamp = Date.now();\n const { observable, cancel } = this._intentQueueService.enqueue({\n type: \"send-command\",\n execute: () =>\n from(\n (async () => {\n const elapsedTime = Date.now() - beforeQueuedTimestamp;\n const result = await this._unsafeInternalSendCommand(\n command,\n // Subtract the elapsed time to account for the time spent in the queue\n // to sync both observable and transport timeout\n abortTimeout ? abortTimeout - elapsedTime : undefined,\n );\n return result;\n })(),\n ),\n });\n\n const timeoutObservable = abortTimeout\n ? observable.pipe(\n timeout({\n each: abortTimeout,\n with: () => {\n cancel();\n throw new SendCommandTimeoutError();\n },\n }),\n )\n : observable;\n\n return lastValueFrom(timeoutObservable);\n }\n\n private async _unsafeInternalSendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const apdu = command.getApdu();\n\n const response = await this._unsafeInternalSendApdu(apdu.getRawApdu(), {\n isPolling: false,\n triggersDisconnection: command.triggersDisconnection ?? false,\n abortTimeout,\n });\n\n return response.caseOf({\n Left: (err) => {\n this._logger.error(\"[sendCommand] error\", { data: { err } });\n throw err;\n },\n Right: (r) => {\n const result = command.parseResponse(\n r,\n this._connectedDevice.deviceModel.id,\n );\n this._logger.debug(\"[sendCommand] result\", { data: { result } });\n return result;\n },\n });\n }\n\n public executeDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n // Bypass intent queue if flag is set\n if (this._bypassIntentQueue) {\n return this._unsafeInternalExecuteDeviceAction(deviceAction);\n }\n return this._internalExecuteDeviceAction(deviceAction);\n }\n\n private _internalExecuteDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n let deviceActionCancel: (() => void) | undefined;\n\n const { observable: o, cancel: queueCancel } =\n this._intentQueueService.enqueue({\n type: \"device-action\",\n execute: () => {\n const { observable, cancel } =\n this._unsafeInternalExecuteDeviceAction(deviceAction);\n deviceActionCancel = cancel;\n return observable;\n },\n });\n\n return {\n observable: o,\n cancel: () => {\n deviceActionCancel?.();\n queueCancel();\n },\n };\n }\n\n private _unsafeInternalExecuteDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n const { observable, cancel } = deviceAction._execute({\n sendApdu: async (apdu: Uint8Array) => this._unsafeInternalSendApdu(apdu), // note: there is no timeout handled at this stage\n sendCommand: async <Response, ErrorStatusCodes, Args>(\n command: Command<Response, ErrorStatusCodes, Args>,\n ) => this._unsafeInternalSendCommand(command), // note: there is no timeout handled at this stage\n getDeviceModel: () => this._connectedDevice.deviceModel,\n getDeviceSessionState: () => this._deviceState.getValue(),\n getDeviceSessionStateObservable: () => this.state,\n setDeviceSessionState: (state: DeviceSessionState) => {\n this.setDeviceSessionState(state);\n return this._deviceState.getValue();\n },\n getManagerApiService: () => this._managerApiService,\n getSecureChannelService: () => this._secureChannelService,\n loggerFactory: this._loggerModuleFactory,\n });\n\n return {\n observable,\n cancel,\n };\n }\n\n public close(): void {\n this._updateDeviceStatus(DeviceStatus.NOT_CONNECTED);\n this._deviceState.complete();\n this._deviceSessionRefresher.stopRefresher();\n this._pinger.unsubscribe();\n }\n\n public disableRefresher(id: string): () => void {\n return this._refresherService.disableRefresher(id);\n }\n\n public _unsafeBypassIntentQueue(bypass: boolean): void {\n this._bypassIntentQueue = bypass;\n }\n\n private _updateDeviceStatus(deviceStatus: DeviceStatus): void {\n const state = this._deviceState.getValue();\n this._deviceState.next({ ...state, deviceStatus });\n }\n}\n"],
5
- "mappings": "AACA,OACE,mBAAAA,EACA,QAAAC,EACA,iBAAAC,EAEA,WAAAC,MACK,OACP,OAAS,MAAMC,MAAc,OAI7B,OAAS,gBAAAC,MAAoB,kCAC7B,OAAS,gBAAAC,MAAoB,2BAO7B,OAEE,0BAAAC,MACK,yCAIP,OACE,wBAAAC,EACA,2BAAAC,MACK,8BAEP,OACE,yBAAAC,EACA,wBAAAC,MACK,sBACP,OAAS,4CAAAC,MAAgD,4DACzD,OAAS,sBAAAC,MAA0B,sDACnC,OAAS,oBAAAC,MAAwB,oDAIjC,OAAS,gBAAAC,MAAoB,iBAC7B,OACE,gCAAAC,EACA,iBAAAC,MACK,iCACP,OAAS,0BAAAC,MAA8B,2BACvC,OAAS,6BAAAC,MAAiC,8BAqBnC,MAAMC,CAAc,CACR,IACA,iBACA,aACA,mBACA,sBACA,QACA,qBAGA,kBACT,QACA,wBACS,kBACA,oBACT,wBAA0B,IAAIJ,EAC9B,mBAA8B,GAEtC,YACE,CAAE,gBAAAK,EAAiB,GAAAC,EAAKlB,EAAO,CAAE,EACjCmB,EACAC,EACAC,EACAC,EACAC,EAE2BC,GACzB,IAAIf,EAAmBU,EAAqBK,CAAsB,EACpE,CACA,KAAK,IAAMN,EACX,KAAK,iBAAmBD,EACxB,KAAK,qBAAuBE,EAC5B,KAAK,QAAUA,EAAoB,gBAAgB,EACnD,KAAK,mBAAqBC,EAC1B,KAAK,oBAAsBG,EACzB,KAAK,uBACP,EACA,KAAK,sBAAwBF,EAC7B,KAAK,kBAAoB,CACvB,GAAGb,EACH,GAAGc,CACL,EACA,KAAK,aAAe,IAAI1B,EAAoC,CAC1D,iBAAkBO,EAAuB,UACzC,aAAcD,EAAa,UAC3B,cAAe,KAAK,iBAAiB,YAAY,EACnD,CAAC,EAED,KAAK,QAAU,IAAIS,EACjBQ,EACAF,EACA,KAAK,wBACL,CAACQ,EA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D,CAC7D,KAAM,CAAE,WAAAT,EAAY,OAAAC,CAAO,EAAIQ,EAAa,SAAS,CACnD,SAAU,MAAOJ,GAAqB,KAAK,wBAAwBA,CAAI,EACvE,YAAa,MACXZ,GACG,KAAK,2BAA2BA,CAAO,EAC5C,eAAgB,IAAM,KAAK,iBAAiB,YAC5C,sBAAuB,IAAM,KAAK,aAAa,SAAS,EACxD,gCAAiC,IAAM,KAAK,MAC5C,sBAAwBE,IACtB,KAAK,sBAAsBA,CAAK,EACzB,KAAK,aAAa,SAAS,GAEpC,qBAAsB,IAAM,KAAK,mBACjC,wBAAyB,IAAM,KAAK,sBACpC,cAAe,KAAK,oBACtB,CAAC,EAED,MAAO,CACL,WAAAK,EACA,OAAAC,CACF,CACF,CAEO,OAAc,CACnB,KAAK,oBAAoB/B,EAAa,aAAa,EACnD,KAAK,aAAa,SAAS,EAC3B,KAAK,wBAAwB,cAAc,EAC3C,KAAK,QAAQ,YAAY,CAC3B,CAEO,iBAAiBgB,EAAwB,CAC9C,OAAO,KAAK,kBAAkB,iBAAiBA,CAAE,CACnD,CAEO,yBAAyB2B,EAAuB,CACrD,KAAK,mBAAqBA,CAC5B,CAEQ,oBAAoBC,EAAkC,CAC5D,MAAMnB,EAAQ,KAAK,aAAa,SAAS,EACzC,KAAK,aAAa,KAAK,CAAE,GAAGA,EAAO,aAAAmB,CAAa,CAAC,CACnD,CACF",
6
- "names": ["BehaviorSubject", "from", "lastValueFrom", "timeout", "uuidv4", "CommandUtils", "DeviceStatus", "DeviceSessionStateType", "SendApduTimeoutError", "SendCommandTimeoutError", "formatApduReceivedLog", "formatApduSendingLog", "DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS", "IntentQueueService", "RefresherService", "DevicePinger", "DeviceSessionEventDispatcher", "SessionEvents", "DeviceSessionRefresher", "DeviceSessionStateHandler", "DeviceSession", "connectedDevice", "id", "loggerModuleFactory", "managerApiService", "secureChannelService", "deviceSessionRefresherOptions", "intentQueueServiceFactory", "sessionEventDispatcher", "command", "abortTimeout", "state", "error", "rawApdu", "options", "beforeQueuedTimestamp", "observable", "cancel", "elapsedTime", "timeoutObservable", "response", "apdu", "err", "r", "result", "deviceAction", "deviceActionCancel", "o", "queueCancel", "bypass", "deviceStatus"]
4
+ "sourcesContent": ["import { type Either } from \"purify-ts\";\nimport {\n BehaviorSubject,\n from,\n lastValueFrom,\n type Observable,\n timeout,\n} from \"rxjs\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { type Command } from \"@api/command/Command\";\nimport { type CommandResult } from \"@api/command/model/CommandResult\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nimport { type DeviceSessionId } from \"@api/device-session/types\";\nimport { type DmkError } from \"@api/Error\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport {\n SendApduTimeoutError,\n SendCommandTimeoutError,\n} from \"@api/transport/model/Errors\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport {\n formatApduExchangeLog,\n formatApduSendingLog,\n} from \"@api/utils/apduLogs\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { IntentQueueService } from \"@internal/device-session/service/IntentQueueService\";\nimport { RefresherService } from \"@internal/device-session/service/RefresherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DevicePinger } from \"./DevicePinger\";\nimport {\n DeviceSessionEventDispatcher,\n SessionEvents,\n} from \"./DeviceSessionEventDispatcher\";\nimport { DeviceSessionRefresher } from \"./DeviceSessionRefresher\";\nimport { DeviceSessionStateHandler } from \"./DeviceSessionStateHandler\";\n\nexport type SessionConstructorArgs = {\n connectedDevice: TransportConnectedDevice;\n id?: DeviceSessionId;\n};\n\nexport type DeviceSessionRefresherOptions = {\n isRefresherDisabled: boolean;\n pollingInterval?: number;\n};\n\ntype SendApduOptions = {\n isPolling?: boolean;\n triggersDisconnection?: boolean;\n abortTimeout?: number;\n};\n\n/**\n * Represents a session with a device.\n */\nexport class DeviceSession {\n private readonly _id: DeviceSessionId;\n private readonly _connectedDevice: TransportConnectedDevice;\n private readonly _deviceState: BehaviorSubject<DeviceSessionState>;\n private readonly _managerApiService: ManagerApiService;\n private readonly _secureChannelService: SecureChannelService;\n private readonly _logger: LoggerPublisherService;\n private readonly _loggerModuleFactory: (\n tag: string,\n ) => LoggerPublisherService;\n private readonly _refresherOptions: DeviceSessionRefresherOptions;\n private _pinger: DevicePinger;\n private _deviceSessionRefresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private readonly _intentQueueService: IntentQueueService;\n private _sessionEventDispatcher = new DeviceSessionEventDispatcher();\n private _bypassIntentQueue: boolean = false;\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n deviceSessionRefresherOptions: DeviceSessionRefresherOptions | undefined,\n intentQueueServiceFactory: (\n sessionEventDispatcher: DeviceSessionEventDispatcher,\n ) => IntentQueueService = (sessionEventDispatcher) =>\n new IntentQueueService(loggerModuleFactory, sessionEventDispatcher),\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._loggerModuleFactory = loggerModuleFactory;\n this._logger = loggerModuleFactory(\"device-session\");\n this._managerApiService = managerApiService;\n this._intentQueueService = intentQueueServiceFactory(\n this._sessionEventDispatcher,\n );\n this._secureChannelService = secureChannelService;\n this._refresherOptions = {\n ...DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n ...deviceSessionRefresherOptions,\n };\n this._deviceState = new BehaviorSubject<DeviceSessionState>({\n sessionStateType: DeviceSessionStateType.Connected,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n });\n\n this._pinger = new DevicePinger(\n loggerModuleFactory,\n connectedDevice,\n this._sessionEventDispatcher,\n (command, abortTimeout) => this.sendCommand(command, abortTimeout),\n );\n this._deviceSessionRefresher = new DeviceSessionRefresher(\n loggerModuleFactory,\n this._refresherOptions,\n this._sessionEventDispatcher,\n this._connectedDevice,\n );\n new DeviceSessionStateHandler(\n loggerModuleFactory,\n this._sessionEventDispatcher,\n this._connectedDevice,\n this._deviceState,\n (state) => this.setDeviceSessionState(state),\n );\n\n this._refresherService = new RefresherService(loggerModuleFactory, {\n start: () => this._deviceSessionRefresher.restartRefresher(),\n stop: () => this._deviceSessionRefresher.stopRefresher(),\n });\n }\n\n public async initialiseSession(): Promise<void> {\n try {\n if (this._refresherOptions.isRefresherDisabled) await this._pinger.ping();\n else this._deviceSessionRefresher.startRefresher();\n } catch (error) {\n this._logger.error(\"Error while initialising session\", {\n data: { error },\n });\n throw error;\n }\n }\n\n public get id(): DeviceSessionId {\n return this._id;\n }\n\n public get connectedDevice(): TransportConnectedDevice {\n return this._connectedDevice;\n }\n\n public get state(): Observable<DeviceSessionState> {\n return this._deviceState.asObservable();\n }\n\n public getDeviceSessionState(): DeviceSessionState {\n return this._deviceState.getValue();\n }\n\n public setDeviceSessionState(state: DeviceSessionState): void {\n this._deviceState.next(state);\n }\n\n public sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n // Bypass intent queue if flag is set\n if (this._bypassIntentQueue) {\n return this._unsafeInternalSendApdu(rawApdu, options);\n }\n return this._internalSendApdu(rawApdu, options);\n }\n\n private _internalSendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions,\n ): Promise<Either<DmkError, ApduResponse>> {\n const abortTimeout = options.abortTimeout;\n const beforeQueuedTimestamp = Date.now();\n const { observable, cancel } = this._intentQueueService.enqueue({\n type: \"send-apdu\",\n execute: () =>\n from(\n (async () => {\n const elapsedTime = Date.now() - beforeQueuedTimestamp;\n const result = await this._unsafeInternalSendApdu(rawApdu, {\n isPolling: options.isPolling,\n triggersDisconnection: options.triggersDisconnection,\n // Subtract the elapsed time to account for the time spent in the queue\n // to sync both observable and transport timeout\n abortTimeout: abortTimeout\n ? abortTimeout - elapsedTime\n : undefined,\n });\n return result;\n })(),\n ),\n });\n\n const timeoutObservable = abortTimeout\n ? observable.pipe(\n timeout({\n each: abortTimeout,\n with: () => {\n cancel();\n throw new SendApduTimeoutError();\n },\n }),\n )\n : observable;\n\n return lastValueFrom(timeoutObservable);\n }\n\n private async _unsafeInternalSendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n this._logger.debug(formatApduSendingLog(rawApdu));\n const result = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n options.abortTimeout,\n );\n\n return result\n .ifRight((response: ApduResponse) => {\n const { message, data } = formatApduExchangeLog(\n this._id,\n rawApdu,\n response,\n );\n this._logger.debug(message, { data });\n if (CommandUtils.isLockedDeviceResponse(response)) {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_LOCKED,\n });\n } else {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n }\n })\n .ifLeft(() => {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_UNKNOWN,\n });\n });\n }\n\n public sendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n this._logger.debug(`[sendCommand] ${command.name}`);\n\n // Bypass intent queue if flag is set\n if (this._bypassIntentQueue) {\n return this._unsafeInternalSendCommand(command, abortTimeout);\n }\n return this._internalSendCommand(command, abortTimeout);\n }\n\n private _internalSendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const beforeQueuedTimestamp = Date.now();\n const { observable, cancel } = this._intentQueueService.enqueue({\n type: \"send-command\",\n execute: () =>\n from(\n (async () => {\n const elapsedTime = Date.now() - beforeQueuedTimestamp;\n const result = await this._unsafeInternalSendCommand(\n command,\n // Subtract the elapsed time to account for the time spent in the queue\n // to sync both observable and transport timeout\n abortTimeout ? abortTimeout - elapsedTime : undefined,\n );\n return result;\n })(),\n ),\n });\n\n const timeoutObservable = abortTimeout\n ? observable.pipe(\n timeout({\n each: abortTimeout,\n with: () => {\n cancel();\n throw new SendCommandTimeoutError();\n },\n }),\n )\n : observable;\n\n return lastValueFrom(timeoutObservable);\n }\n\n private async _unsafeInternalSendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const apdu = command.getApdu();\n\n const response = await this._unsafeInternalSendApdu(apdu.getRawApdu(), {\n isPolling: false,\n triggersDisconnection: command.triggersDisconnection ?? false,\n abortTimeout,\n });\n\n return response.caseOf({\n Left: (err) => {\n this._logger.error(\"[sendCommand] error\", { data: { err } });\n throw err;\n },\n Right: (r) => {\n const result = command.parseResponse(\n r,\n this._connectedDevice.deviceModel.id,\n );\n this._logger.debug(\"[sendCommand] result\", { data: { result } });\n return result;\n },\n });\n }\n\n public executeDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n // Bypass intent queue if flag is set\n if (this._bypassIntentQueue) {\n return this._unsafeInternalExecuteDeviceAction(deviceAction);\n }\n return this._internalExecuteDeviceAction(deviceAction);\n }\n\n private _internalExecuteDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n let deviceActionCancel: (() => void) | undefined;\n\n const { observable: o, cancel: queueCancel } =\n this._intentQueueService.enqueue({\n type: \"device-action\",\n execute: () => {\n const { observable, cancel } =\n this._unsafeInternalExecuteDeviceAction(deviceAction);\n deviceActionCancel = cancel;\n return observable;\n },\n });\n\n return {\n observable: o,\n cancel: () => {\n deviceActionCancel?.();\n queueCancel();\n },\n };\n }\n\n private _unsafeInternalExecuteDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n const { observable, cancel } = deviceAction._execute({\n sendApdu: async (apdu: Uint8Array) => this._unsafeInternalSendApdu(apdu), // note: there is no timeout handled at this stage\n sendCommand: async <Response, ErrorStatusCodes, Args>(\n command: Command<Response, ErrorStatusCodes, Args>,\n ) => this._unsafeInternalSendCommand(command), // note: there is no timeout handled at this stage\n getDeviceModel: () => this._connectedDevice.deviceModel,\n getDeviceSessionState: () => this._deviceState.getValue(),\n getDeviceSessionStateObservable: () => this.state,\n setDeviceSessionState: (state: DeviceSessionState) => {\n this.setDeviceSessionState(state);\n return this._deviceState.getValue();\n },\n getManagerApiService: () => this._managerApiService,\n getSecureChannelService: () => this._secureChannelService,\n loggerFactory: this._loggerModuleFactory,\n });\n\n return {\n observable,\n cancel,\n };\n }\n\n public close(): void {\n this._updateDeviceStatus(DeviceStatus.NOT_CONNECTED);\n this._deviceState.complete();\n this._deviceSessionRefresher.stopRefresher();\n this._pinger.unsubscribe();\n }\n\n public disableRefresher(id: string): () => void {\n return this._refresherService.disableRefresher(id);\n }\n\n public _unsafeBypassIntentQueue(bypass: boolean): void {\n this._bypassIntentQueue = bypass;\n }\n\n private _updateDeviceStatus(deviceStatus: DeviceStatus): void {\n const state = this._deviceState.getValue();\n this._deviceState.next({ ...state, deviceStatus });\n }\n}\n"],
5
+ "mappings": "AACA,OACE,mBAAAA,EACA,QAAAC,EACA,iBAAAC,EAEA,WAAAC,MACK,OACP,OAAS,MAAMC,MAAc,OAI7B,OAAS,gBAAAC,MAAoB,kCAC7B,OAAS,gBAAAC,MAAoB,2BAO7B,OAEE,0BAAAC,MACK,yCAIP,OACE,wBAAAC,EACA,2BAAAC,MACK,8BAEP,OACE,yBAAAC,EACA,wBAAAC,MACK,sBACP,OAAS,4CAAAC,MAAgD,4DACzD,OAAS,sBAAAC,MAA0B,sDACnC,OAAS,oBAAAC,MAAwB,oDAIjC,OAAS,gBAAAC,MAAoB,iBAC7B,OACE,gCAAAC,EACA,iBAAAC,MACK,iCACP,OAAS,0BAAAC,MAA8B,2BACvC,OAAS,6BAAAC,MAAiC,8BAqBnC,MAAMC,CAAc,CACR,IACA,iBACA,aACA,mBACA,sBACA,QACA,qBAGA,kBACT,QACA,wBACS,kBACA,oBACT,wBAA0B,IAAIJ,EAC9B,mBAA8B,GAEtC,YACE,CAAE,gBAAAK,EAAiB,GAAAC,EAAKlB,EAAO,CAAE,EACjCmB,EACAC,EACAC,EACAC,EACAC,EAE2BC,GACzB,IAAIf,EAAmBU,EAAqBK,CAAsB,EACpE,CACA,KAAK,IAAMN,EACX,KAAK,iBAAmBD,EACxB,KAAK,qBAAuBE,EAC5B,KAAK,QAAUA,EAAoB,gBAAgB,EACnD,KAAK,mBAAqBC,EAC1B,KAAK,oBAAsBG,EACzB,KAAK,uBACP,EACA,KAAK,sBAAwBF,EAC7B,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ommandUtils", "DeviceStatus", "DeviceSessionStateType", "SendApduTimeoutError", "SendCommandTimeoutError", "formatApduExchangeLog", "formatApduSendingLog", "DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS", "IntentQueueService", "RefresherService", "DevicePinger", "DeviceSessionEventDispatcher", "SessionEvents", "DeviceSessionRefresher", "DeviceSessionStateHandler", "DeviceSession", "connectedDevice", "id", "loggerModuleFactory", "managerApiService", "secureChannelService", "deviceSessionRefresherOptions", "intentQueueServiceFactory", "sessionEventDispatcher", "command", "abortTimeout", "state", "error", "rawApdu", "options", "beforeQueuedTimestamp", "observable", "cancel", "elapsedTime", "timeoutObservable", "response", "message", "data", "apdu", "err", "r", "result", "deviceAction", "deviceActionCancel", "o", "queueCancel", "bypass", "deviceStatus"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{distinctUntilChanged as c,filter as o,map as l,startWith as a,tap as h,timer as f,withLatestFrom as v}from"rxjs";import{DeviceModelId as _}from"../../../api/device/DeviceModel";import{DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL as n,DEVICE_SESSION_REFRESHER_POLLING_INTERVAL as p}from"../../device-session/data/DeviceSessionRefresherConst";import{SessionEvents as t}from"../../device-session/model/DeviceSessionEventDispatcher";class D{constructor(s,r,e,i){this._sessionEventDispatcher=e;this._refresherOptions=r,this._logger=s("device-session-refresher"),this._connectedDeviceID=i.deviceModel.id}_refresherSubscription;_refresherOptions;_logger;_connectedDeviceID;startRefresher(){if(this._refresherOptions.isRefresherDisabled||this._refresherSubscription)return;const s=this.getValidPollingInterval(this._refresherOptions,this._logger)*2,r=this._sessionEventDispatcher.listen().pipe(o(e=>e.eventName===t.DEVICE_STATE_UPDATE_BUSY||e.eventName===t.NEW_STATE),l(e=>e.eventName===t.DEVICE_STATE_UPDATE_BUSY),a(!1),c());this._refresherSubscription=f(0,s).pipe(v(r),h(([e,i])=>{i&&this._logger.debug("Refresh skipped: device is busy")}),o(([e,i])=>!i),h(()=>this._sessionEventDispatcher.dispatch({eventName:t.REFRESH_NEEDED}))).subscribe(),this._logger.info("Refresher started.")}stopRefresher(){this._refresherSubscription&&(this._refresherSubscription.unsubscribe(),this._refresherSubscription=void 0,this._logger.info("Refresher stopped."))}restartRefresher(){this.stopRefresher(),this.startRefresher(),this._logger.info("Refresher restarted.")}getValidPollingInterval=(s,r)=>{const{pollingInterval:e}=s;switch(this._connectedDeviceID){case _.NANO_S:{const i=p*2;return e!==void 0&&e<i?(r.warn(`Polling interval of ${e} is too low, setting to minimum as ${i}`),i):e??i}default:return e!==void 0&&e<n?(r.warn(`Polling interval of ${e} is too low, setting to minimum as ${n}`),n):e??p}}}export{D as DeviceSessionRefresher};
1
+ import{distinctUntilChanged as c,filter as o,map as l,startWith as a,tap as h,timer as f,withLatestFrom as v}from"rxjs";import{DeviceModelId as _}from"../../../api/device/DeviceModel";import{DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL as n,DEVICE_SESSION_REFRESHER_POLLING_INTERVAL as p}from"../../device-session/data/DeviceSessionRefresherConst";import{SessionEvents as t}from"../../device-session/model/DeviceSessionEventDispatcher";class D{constructor(s,r,e,i){this._sessionEventDispatcher=e;this._refresherOptions=r,this._logger=s("device-session-refresher"),this._connectedDeviceID=i.deviceModel.id}_refresherSubscription;_refresherOptions;_logger;_connectedDeviceID;startRefresher(){if(this._refresherOptions.isRefresherDisabled||this._refresherSubscription)return;const s=this.getValidPollingInterval(this._refresherOptions,this._logger),r=this._sessionEventDispatcher.listen().pipe(o(e=>e.eventName===t.DEVICE_STATE_UPDATE_BUSY||e.eventName===t.NEW_STATE),l(e=>e.eventName===t.DEVICE_STATE_UPDATE_BUSY),a(!1),c());this._refresherSubscription=f(0,s).pipe(v(r),h(([e,i])=>{i&&this._logger.debug("Refresh skipped: device is busy")}),o(([e,i])=>!i),h(()=>this._sessionEventDispatcher.dispatch({eventName:t.REFRESH_NEEDED}))).subscribe(),this._logger.info("Refresher started.")}stopRefresher(){this._refresherSubscription&&(this._refresherSubscription.unsubscribe(),this._refresherSubscription=void 0,this._logger.info("Refresher stopped."))}restartRefresher(){this.stopRefresher(),this.startRefresher(),this._logger.info("Refresher restarted.")}getValidPollingInterval=(s,r)=>{const{pollingInterval:e}=s;switch(this._connectedDeviceID){case _.NANO_S:{const i=p*2;return e!==void 0&&e<i?(r.warn(`Polling interval of ${e} is too low, setting to minimum as ${i}`),i):e??i}default:return e!==void 0&&e<n?(r.warn(`Polling interval of ${e} is too low, setting to minimum as ${n}`),n):e??p}}}export{D as DeviceSessionRefresher};
2
2
  //# sourceMappingURL=DeviceSessionRefresher.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/device-session/model/DeviceSessionRefresher.ts"],
4
- "sourcesContent": ["import {\n distinctUntilChanged,\n filter,\n map,\n startWith,\n type Subscription,\n tap,\n timer,\n withLatestFrom,\n} from \"rxjs\";\n\nimport { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { type LoggerPublisherService } from \"@api/types\";\nimport {\n DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL,\n DEVICE_SESSION_REFRESHER_POLLING_INTERVAL,\n} from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport {\n type DeviceSessionEventDispatcher,\n SessionEvents,\n} from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\n\nexport interface DeviceSessionRefresherOptions {\n isRefresherDisabled: boolean;\n pollingInterval?: number;\n}\n\nexport class DeviceSessionRefresher {\n private _refresherSubscription!: Subscription | undefined;\n private _refresherOptions: DeviceSessionRefresherOptions;\n private readonly _logger: LoggerPublisherService;\n private _connectedDeviceID: DeviceModelId;\n\n constructor(\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n refresherOptions: DeviceSessionRefresherOptions,\n private _sessionEventDispatcher: DeviceSessionEventDispatcher,\n connectedDevice: TransportConnectedDevice,\n ) {\n this._refresherOptions = refresherOptions;\n this._logger = loggerModuleFactory(\"device-session-refresher\");\n this._connectedDeviceID = connectedDevice.deviceModel.id;\n }\n\n public startRefresher(): void {\n if (this._refresherOptions.isRefresherDisabled) return;\n if (this._refresherSubscription) return;\n\n const pollingInterval =\n this.getValidPollingInterval(this._refresherOptions, this._logger) * 2;\n\n const isBusy$ = this._sessionEventDispatcher.listen().pipe(\n filter(\n (event) =>\n event.eventName === SessionEvents.DEVICE_STATE_UPDATE_BUSY ||\n event.eventName === SessionEvents.NEW_STATE,\n ),\n map(\n (event) => event.eventName === SessionEvents.DEVICE_STATE_UPDATE_BUSY,\n ),\n startWith(false),\n distinctUntilChanged(),\n );\n\n this._refresherSubscription = timer(0, pollingInterval)\n .pipe(\n withLatestFrom(isBusy$),\n tap(([_, isBusy]) => {\n if (isBusy) {\n this._logger.debug(\"Refresh skipped: device is busy\");\n }\n }),\n filter(([_, isBusy]) => !isBusy),\n tap(() =>\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.REFRESH_NEEDED,\n }),\n ),\n )\n .subscribe();\n\n this._logger.info(\"Refresher started.\");\n }\n\n public stopRefresher(): void {\n if (this._refresherSubscription) {\n this._refresherSubscription.unsubscribe();\n this._refresherSubscription = undefined;\n this._logger.info(\"Refresher stopped.\");\n }\n }\n\n public restartRefresher(): void {\n this.stopRefresher();\n this.startRefresher();\n this._logger.info(\"Refresher restarted.\");\n }\n\n private getValidPollingInterval = (\n refresherOptions: DeviceSessionRefresherOptions,\n logger: LoggerPublisherService,\n ): number => {\n const { pollingInterval } = refresherOptions;\n switch (this._connectedDeviceID) {\n case DeviceModelId.NANO_S: {\n const defaultNanoPollingInterval =\n DEVICE_SESSION_REFRESHER_POLLING_INTERVAL * 2;\n if (\n pollingInterval !== undefined &&\n pollingInterval < defaultNanoPollingInterval\n ) {\n logger.warn(\n `Polling interval of ${pollingInterval} is too low, setting to minimum as ${defaultNanoPollingInterval}`,\n );\n return defaultNanoPollingInterval;\n }\n return pollingInterval ?? defaultNanoPollingInterval;\n }\n default:\n if (\n pollingInterval !== undefined &&\n pollingInterval < DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL\n ) {\n logger.warn(\n `Polling interval of ${pollingInterval} is too low, setting to minimum as ${DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL}`,\n );\n return DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL;\n }\n\n return pollingInterval ?? DEVICE_SESSION_REFRESHER_POLLING_INTERVAL;\n }\n };\n}\n"],
5
- "mappings": "AAAA,OACE,wBAAAA,EACA,UAAAC,EACA,OAAAC,EACA,aAAAC,EAEA,OAAAC,EACA,SAAAC,EACA,kBAAAC,MACK,OAEP,OAAS,iBAAAC,MAAqB,0BAG9B,OACE,qDAAAC,EACA,6CAAAC,MACK,4DACP,OAEE,iBAAAC,MACK,8DAOA,MAAMC,CAAuB,CAMlC,YACEC,EACAC,EACQC,EACRC,EACA,CAFQ,6BAAAD,EAGR,KAAK,kBAAoBD,EACzB,KAAK,QAAUD,EAAoB,0BAA0B,EAC7D,KAAK,mBAAqBG,EAAgB,YAAY,EACxD,CAdQ,uBACA,kBACS,QACT,mBAaD,gBAAuB,CAE5B,GADI,KAAK,kBAAkB,qBACvB,KAAK,uBAAwB,OAEjC,MAAMC,EACJ,KAAK,wBAAwB,KAAK,kBAAmB,KAAK,OAAO,EAAI,EAEjEC,EAAU,KAAK,wBAAwB,OAAO,EAAE,KACpDhB,EACGiB,GACCA,EAAM,YAAcR,EAAc,0BAClCQ,EAAM,YAAcR,EAAc,SACtC,EACAR,EACGgB,GAAUA,EAAM,YAAcR,EAAc,wBAC/C,EACAP,EAAU,EAAK,EACfH,EAAqB,CACvB,EAEA,KAAK,uBAAyBK,EAAM,EAAGW,CAAe,EACnD,KACCV,EAAeW,CAAO,EACtBb,EAAI,CAAC,CAACe,EAAGC,CAAM,IAAM,CACfA,GACF,KAAK,QAAQ,MAAM,iCAAiC,CAExD,CAAC,EACDnB,EAAO,CAAC,CAACkB,EAAGC,CAAM,IAAM,CAACA,CAAM,EAC/BhB,EAAI,IACF,KAAK,wBAAwB,SAAS,CACpC,UAAWM,EAAc,cAC3B,CAAC,CACH,CACF,EACC,UAAU,EAEb,KAAK,QAAQ,KAAK,oBAAoB,CACxC,CAEO,eAAsB,CACvB,KAAK,yBACP,KAAK,uBAAuB,YAAY,EACxC,KAAK,uBAAyB,OAC9B,KAAK,QAAQ,KAAK,oBAAoB,EAE1C,CAEO,kBAAyB,CAC9B,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,QAAQ,KAAK,sBAAsB,CAC1C,CAEQ,wBAA0B,CAChCG,EACAQ,IACW,CACX,KAAM,CAAE,gBAAAL,CAAgB,EAAIH,EAC5B,OAAQ,KAAK,mBAAoB,CAC/B,KAAKN,EAAc,OAAQ,CACzB,MAAMe,EACJb,EAA4C,EAC9C,OACEO,IAAoB,QACpBA,EAAkBM,GAElBD,EAAO,KACL,uBAAuBL,CAAe,sCAAsCM,CAA0B,EACxG,EACOA,GAEFN,GAAmBM,CAC5B,CACA,QACE,OACEN,IAAoB,QACpBA,EAAkBR,GAElBa,EAAO,KACL,uBAAuBL,CAAe,sCAAsCR,CAAiD,EAC/H,EACOA,GAGFQ,GAAmBP,CAC9B,CACF,CACF",
4
+ "sourcesContent": ["import {\n distinctUntilChanged,\n filter,\n map,\n startWith,\n type Subscription,\n tap,\n timer,\n withLatestFrom,\n} from \"rxjs\";\n\nimport { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { type LoggerPublisherService } from \"@api/types\";\nimport {\n DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL,\n DEVICE_SESSION_REFRESHER_POLLING_INTERVAL,\n} from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport {\n type DeviceSessionEventDispatcher,\n SessionEvents,\n} from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\n\nexport interface DeviceSessionRefresherOptions {\n isRefresherDisabled: boolean;\n pollingInterval?: number;\n}\n\nexport class DeviceSessionRefresher {\n private _refresherSubscription!: Subscription | undefined;\n private _refresherOptions: DeviceSessionRefresherOptions;\n private readonly _logger: LoggerPublisherService;\n private _connectedDeviceID: DeviceModelId;\n\n constructor(\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n refresherOptions: DeviceSessionRefresherOptions,\n private _sessionEventDispatcher: DeviceSessionEventDispatcher,\n connectedDevice: TransportConnectedDevice,\n ) {\n this._refresherOptions = refresherOptions;\n this._logger = loggerModuleFactory(\"device-session-refresher\");\n this._connectedDeviceID = connectedDevice.deviceModel.id;\n }\n\n public startRefresher(): void {\n if (this._refresherOptions.isRefresherDisabled) return;\n if (this._refresherSubscription) return;\n\n const pollingInterval = this.getValidPollingInterval(\n this._refresherOptions,\n this._logger,\n );\n\n const isBusy$ = this._sessionEventDispatcher.listen().pipe(\n filter(\n (event) =>\n event.eventName === SessionEvents.DEVICE_STATE_UPDATE_BUSY ||\n event.eventName === SessionEvents.NEW_STATE,\n ),\n map(\n (event) => event.eventName === SessionEvents.DEVICE_STATE_UPDATE_BUSY,\n ),\n startWith(false),\n distinctUntilChanged(),\n );\n\n this._refresherSubscription = timer(0, pollingInterval)\n .pipe(\n withLatestFrom(isBusy$),\n tap(([_, isBusy]) => {\n if (isBusy) {\n this._logger.debug(\"Refresh skipped: device is busy\");\n }\n }),\n filter(([_, isBusy]) => !isBusy),\n tap(() =>\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.REFRESH_NEEDED,\n }),\n ),\n )\n .subscribe();\n\n this._logger.info(\"Refresher started.\");\n }\n\n public stopRefresher(): void {\n if (this._refresherSubscription) {\n this._refresherSubscription.unsubscribe();\n this._refresherSubscription = undefined;\n this._logger.info(\"Refresher stopped.\");\n }\n }\n\n public restartRefresher(): void {\n this.stopRefresher();\n this.startRefresher();\n this._logger.info(\"Refresher restarted.\");\n }\n\n private getValidPollingInterval = (\n refresherOptions: DeviceSessionRefresherOptions,\n logger: LoggerPublisherService,\n ): number => {\n const { pollingInterval } = refresherOptions;\n switch (this._connectedDeviceID) {\n case DeviceModelId.NANO_S: {\n const defaultNanoPollingInterval =\n DEVICE_SESSION_REFRESHER_POLLING_INTERVAL * 2;\n if (\n pollingInterval !== undefined &&\n pollingInterval < defaultNanoPollingInterval\n ) {\n logger.warn(\n `Polling interval of ${pollingInterval} is too low, setting to minimum as ${defaultNanoPollingInterval}`,\n );\n return defaultNanoPollingInterval;\n }\n return pollingInterval ?? defaultNanoPollingInterval;\n }\n default:\n if (\n pollingInterval !== undefined &&\n pollingInterval < DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL\n ) {\n logger.warn(\n `Polling interval of ${pollingInterval} is too low, setting to minimum as ${DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL}`,\n );\n return DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL;\n }\n\n return pollingInterval ?? DEVICE_SESSION_REFRESHER_POLLING_INTERVAL;\n }\n };\n}\n"],
5
+ "mappings": "AAAA,OACE,wBAAAA,EACA,UAAAC,EACA,OAAAC,EACA,aAAAC,EAEA,OAAAC,EACA,SAAAC,EACA,kBAAAC,MACK,OAEP,OAAS,iBAAAC,MAAqB,0BAG9B,OACE,qDAAAC,EACA,6CAAAC,MACK,4DACP,OAEE,iBAAAC,MACK,8DAOA,MAAMC,CAAuB,CAMlC,YACEC,EACAC,EACQC,EACRC,EACA,CAFQ,6BAAAD,EAGR,KAAK,kBAAoBD,EACzB,KAAK,QAAUD,EAAoB,0BAA0B,EAC7D,KAAK,mBAAqBG,EAAgB,YAAY,EACxD,CAdQ,uBACA,kBACS,QACT,mBAaD,gBAAuB,CAE5B,GADI,KAAK,kBAAkB,qBACvB,KAAK,uBAAwB,OAEjC,MAAMC,EAAkB,KAAK,wBAC3B,KAAK,kBACL,KAAK,OACP,EAEMC,EAAU,KAAK,wBAAwB,OAAO,EAAE,KACpDhB,EACGiB,GACCA,EAAM,YAAcR,EAAc,0BAClCQ,EAAM,YAAcR,EAAc,SACtC,EACAR,EACGgB,GAAUA,EAAM,YAAcR,EAAc,wBAC/C,EACAP,EAAU,EAAK,EACfH,EAAqB,CACvB,EAEA,KAAK,uBAAyBK,EAAM,EAAGW,CAAe,EACnD,KACCV,EAAeW,CAAO,EACtBb,EAAI,CAAC,CAACe,EAAGC,CAAM,IAAM,CACfA,GACF,KAAK,QAAQ,MAAM,iCAAiC,CAExD,CAAC,EACDnB,EAAO,CAAC,CAACkB,EAAGC,CAAM,IAAM,CAACA,CAAM,EAC/BhB,EAAI,IACF,KAAK,wBAAwB,SAAS,CACpC,UAAWM,EAAc,cAC3B,CAAC,CACH,CACF,EACC,UAAU,EAEb,KAAK,QAAQ,KAAK,oBAAoB,CACxC,CAEO,eAAsB,CACvB,KAAK,yBACP,KAAK,uBAAuB,YAAY,EACxC,KAAK,uBAAyB,OAC9B,KAAK,QAAQ,KAAK,oBAAoB,EAE1C,CAEO,kBAAyB,CAC9B,KAAK,cAAc,EACnB,KAAK,eAAe,EACpB,KAAK,QAAQ,KAAK,sBAAsB,CAC1C,CAEQ,wBAA0B,CAChCG,EACAQ,IACW,CACX,KAAM,CAAE,gBAAAL,CAAgB,EAAIH,EAC5B,OAAQ,KAAK,mBAAoB,CAC/B,KAAKN,EAAc,OAAQ,CACzB,MAAMe,EACJb,EAA4C,EAC9C,OACEO,IAAoB,QACpBA,EAAkBM,GAElBD,EAAO,KACL,uBAAuBL,CAAe,sCAAsCM,CAA0B,EACxG,EACOA,GAEFN,GAAmBM,CAC5B,CACA,QACE,OACEN,IAAoB,QACpBA,EAAkBR,GAElBa,EAAO,KACL,uBAAuBL,CAAe,sCAAsCR,CAAiD,EAC/H,EACOA,GAGFQ,GAAmBP,CAC9B,CACF,CACF",
6
6
  "names": ["distinctUntilChanged", "filter", "map", "startWith", "tap", "timer", "withLatestFrom", "DeviceModelId", "DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL", "DEVICE_SESSION_REFRESHER_POLLING_INTERVAL", "SessionEvents", "DeviceSessionRefresher", "loggerModuleFactory", "refresherOptions", "_sessionEventDispatcher", "connectedDevice", "pollingInterval", "isBusy$", "event", "_", "isBusy", "logger", "defaultNanoPollingInterval"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{Subject as D}from"rxjs";import{afterEach as E,beforeEach as S,describe as w,expect as n,it as l,vi as r}from"vitest";import{DeviceModelId as m}from"../../../api/device/DeviceModel";import{DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL as d,DEVICE_SESSION_REFRESHER_POLLING_INTERVAL as T}from"../../device-session/data/DeviceSessionRefresherConst";import{SessionEvents as h}from"../../device-session/model/DeviceSessionEventDispatcher";import{DeviceSessionRefresher as c}from"./DeviceSessionRefresher";w("DeviceSessionRefresher",()=>{let p,s,o;const v={deviceModel:{id:m.FLEX}},R={deviceModel:{id:m.NANO_S}},a=r.fn(()=>o);let e;S(()=>{r.useFakeTimers(),p=new D,s={listen:()=>p.asObservable(),dispatch:r.fn()},o={info:r.fn(),warn:r.fn(),error:r.fn(),debug:r.fn(),subscribers:[]}}),E(()=>{e?.stopRefresher(),r.useRealTimers(),r.restoreAllMocks()}),l("should not start refresher if disabled",()=>{const t={isRefresherDisabled:!0,pollingInterval:1e3};e=new c(a,t,s,v),e.startRefresher(),r.advanceTimersByTime(2e3),n(s.dispatch).not.toHaveBeenCalled()}),l("should warn and use minimum polling interval for default device when provided interval is too low",()=>{const t=d-100,i={isRefresherDisabled:!1,pollingInterval:t};e=new c(a,i,s,v),e.startRefresher();const f=`Polling interval of ${t} is too low, setting to minimum as ${d}`;n(o.warn).toHaveBeenCalledWith(f)}),l("should warn and use minimum polling interval for NANO_S device when provided interval is too low",()=>{const t=T*2,i=t-100,f={isRefresherDisabled:!1,pollingInterval:i};e=new c(a,f,s,R),e.startRefresher();const u=`Polling interval of ${i} is too low, setting to minimum as ${t}`;n(o.warn).toHaveBeenCalledWith(u)}),l("should not warn when provided polling interval is valid for default device",()=>{const i={isRefresherDisabled:!1,pollingInterval:d+100};e=new c(a,i,s,v),e.startRefresher(),n(o.warn).not.toHaveBeenCalled()}),l("should dispatch refresh event on timer ticks",()=>{const t=d+100,i={isRefresherDisabled:!1,pollingInterval:t};e=new c(a,i,s,v),e.startRefresher(),p.next({eventName:h.NEW_STATE});const f=t*2;r.advanceTimersByTime(f*3),n(s.dispatch.mock.calls.length).toBe(4),n(s.dispatch.mock.calls[0][0]).toEqual({eventName:h.REFRESH_NEEDED})}),l("should stop refresher",()=>{const t={isRefresherDisabled:!1,pollingInterval:1e3};e=new c(a,t,s,v),e.startRefresher(),s.dispatch.mockClear(),e.stopRefresher(),r.advanceTimersByTime(2e3),n(s.dispatch).not.toHaveBeenCalled(),n(o.info).toHaveBeenCalledWith("Refresher stopped.")}),l("should restart refresher",()=>{const t={isRefresherDisabled:!1,pollingInterval:1e3};e=new c(a,t,s,v),e.startRefresher(),s.dispatch.mockClear(),r.clearAllTimers(),e.restartRefresher(),n(o.info).toHaveBeenCalledWith("Refresher stopped."),n(o.info).toHaveBeenCalledWith("Refresher restarted."),p.next({eventName:h.NEW_STATE}),r.advanceTimersByTime(2e3),n(s.dispatch.mock.calls.length).toBeGreaterThan(0)})});
1
+ import{Subject as D}from"rxjs";import{afterEach as E,beforeEach as S,describe as w,expect as n,it as l,vi as r}from"vitest";import{DeviceModelId as m}from"../../../api/device/DeviceModel";import{DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL as d,DEVICE_SESSION_REFRESHER_POLLING_INTERVAL as T}from"../../device-session/data/DeviceSessionRefresherConst";import{SessionEvents as h}from"../../device-session/model/DeviceSessionEventDispatcher";import{DeviceSessionRefresher as c}from"./DeviceSessionRefresher";w("DeviceSessionRefresher",()=>{let p,s,o;const v={deviceModel:{id:m.FLEX}},R={deviceModel:{id:m.NANO_S}},a=r.fn(()=>o);let e;S(()=>{r.useFakeTimers(),p=new D,s={listen:()=>p.asObservable(),dispatch:r.fn()},o={info:r.fn(),warn:r.fn(),error:r.fn(),debug:r.fn(),subscribers:[]}}),E(()=>{e?.stopRefresher(),r.useRealTimers(),r.restoreAllMocks()}),l("should not start refresher if disabled",()=>{const t={isRefresherDisabled:!0,pollingInterval:1e3};e=new c(a,t,s,v),e.startRefresher(),r.advanceTimersByTime(2e3),n(s.dispatch).not.toHaveBeenCalled()}),l("should warn and use minimum polling interval for default device when provided interval is too low",()=>{const t=d-100,i={isRefresherDisabled:!1,pollingInterval:t};e=new c(a,i,s,v),e.startRefresher();const f=`Polling interval of ${t} is too low, setting to minimum as ${d}`;n(o.warn).toHaveBeenCalledWith(f)}),l("should warn and use minimum polling interval for NANO_S device when provided interval is too low",()=>{const t=T*2,i=t-100,f={isRefresherDisabled:!1,pollingInterval:i};e=new c(a,f,s,R),e.startRefresher();const u=`Polling interval of ${i} is too low, setting to minimum as ${t}`;n(o.warn).toHaveBeenCalledWith(u)}),l("should not warn when provided polling interval is valid for default device",()=>{const i={isRefresherDisabled:!1,pollingInterval:d+100};e=new c(a,i,s,v),e.startRefresher(),n(o.warn).not.toHaveBeenCalled()}),l("should dispatch refresh event on timer ticks",()=>{const t=d+100,i={isRefresherDisabled:!1,pollingInterval:t};e=new c(a,i,s,v),e.startRefresher(),p.next({eventName:h.NEW_STATE});const f=t;r.advanceTimersByTime(f*3),n(s.dispatch.mock.calls.length).toBe(4),n(s.dispatch.mock.calls[0][0]).toEqual({eventName:h.REFRESH_NEEDED})}),l("should stop refresher",()=>{const t={isRefresherDisabled:!1,pollingInterval:1e3};e=new c(a,t,s,v),e.startRefresher(),s.dispatch.mockClear(),e.stopRefresher(),r.advanceTimersByTime(2e3),n(s.dispatch).not.toHaveBeenCalled(),n(o.info).toHaveBeenCalledWith("Refresher stopped.")}),l("should restart refresher",()=>{const t={isRefresherDisabled:!1,pollingInterval:1e3};e=new c(a,t,s,v),e.startRefresher(),s.dispatch.mockClear(),r.clearAllTimers(),e.restartRefresher(),n(o.info).toHaveBeenCalledWith("Refresher stopped."),n(o.info).toHaveBeenCalledWith("Refresher restarted."),p.next({eventName:h.NEW_STATE}),r.advanceTimersByTime(2e3),n(s.dispatch.mock.calls.length).toBeGreaterThan(0)})});
2
2
  //# sourceMappingURL=DeviceSessionRefresher.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/device-session/model/DeviceSessionRefresher.test.ts"],
4
- "sourcesContent": ["import { Subject } from \"rxjs\";\nimport { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport type { LoggerPublisherService } from \"@api/types\";\nimport {\n DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL,\n DEVICE_SESSION_REFRESHER_POLLING_INTERVAL,\n} from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport type {\n DeviceSessionEventDispatcher,\n NewEvent,\n} from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\nimport { SessionEvents } from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\n\nimport {\n DeviceSessionRefresher,\n type DeviceSessionRefresherOptions,\n} from \"./DeviceSessionRefresher\";\n\ndescribe(\"DeviceSessionRefresher\", () => {\n let subject: Subject<NewEvent>;\n let mockSessionEventDispatcher: DeviceSessionEventDispatcher;\n let mockLogger: LoggerPublisherService & {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n debug: ReturnType<typeof vi.fn>;\n subscribers?: unknown[];\n };\n\n const stubDefaultDevice = {\n deviceModel: {\n id: DeviceModelId.FLEX,\n },\n } as TransportConnectedDevice;\n\n const stubNanoSDevice = {\n deviceModel: {\n id: DeviceModelId.NANO_S,\n },\n } as TransportConnectedDevice;\n\n const mockedLoggerModuleFactory = vi.fn(() => mockLogger);\n let refresher: DeviceSessionRefresher;\n\n beforeEach(() => {\n vi.useFakeTimers();\n subject = new Subject<NewEvent>();\n mockSessionEventDispatcher = {\n listen: () => subject.asObservable(),\n dispatch: vi.fn(),\n } as unknown as DeviceSessionEventDispatcher;\n mockLogger = {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n debug: vi.fn(),\n subscribers: [],\n };\n });\n\n afterEach(() => {\n refresher?.stopRefresher();\n vi.useRealTimers();\n vi.restoreAllMocks();\n });\n\n it(\"should not start refresher if disabled\", () => {\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: true,\n pollingInterval: 1000,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n vi.advanceTimersByTime(2000);\n\n expect(mockSessionEventDispatcher.dispatch).not.toHaveBeenCalled();\n });\n\n it(\"should warn and use minimum polling interval for default device when provided interval is too low\", () => {\n const lowInterval = DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL - 100;\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: lowInterval,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n\n const expectedMessage = `Polling interval of ${lowInterval} is too low, setting to minimum as ${DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL}`;\n expect(mockLogger.warn).toHaveBeenCalledWith(expectedMessage);\n });\n\n it(\"should warn and use minimum polling interval for NANO_S device when provided interval is too low\", () => {\n const defaultNanoPollingInterval =\n DEVICE_SESSION_REFRESHER_POLLING_INTERVAL * 2;\n const lowInterval = defaultNanoPollingInterval - 100;\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: lowInterval,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubNanoSDevice,\n );\n refresher.startRefresher();\n\n const expectedMessage = `Polling interval of ${lowInterval} is too low, setting to minimum as ${defaultNanoPollingInterval}`;\n expect(mockLogger.warn).toHaveBeenCalledWith(expectedMessage);\n });\n\n it(\"should not warn when provided polling interval is valid for default device\", () => {\n const validInterval =\n DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL + 100;\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: validInterval,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n\n expect(mockLogger.warn).not.toHaveBeenCalled();\n });\n\n it(\"should dispatch refresh event on timer ticks\", () => {\n const validInterval =\n DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL + 100;\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: validInterval,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n\n // Trigger NEW_STATE event to start the refresher timer\n subject.next({ eventName: SessionEvents.NEW_STATE });\n\n const timerInterval = validInterval * 2;\n\n vi.advanceTimersByTime(timerInterval * 3);\n\n expect(\n (mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>).mock\n .calls.length,\n ).toBe(4);\n expect(\n (mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>).mock\n .calls[0]![0],\n ).toEqual({\n eventName: SessionEvents.REFRESH_NEEDED,\n });\n });\n\n it(\"should stop refresher\", () => {\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: 1000,\n };\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n (\n mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>\n ).mockClear();\n\n refresher.stopRefresher();\n vi.advanceTimersByTime(2000);\n\n expect(mockSessionEventDispatcher.dispatch).not.toHaveBeenCalled();\n expect(mockLogger.info).toHaveBeenCalledWith(\"Refresher stopped.\");\n });\n\n it(\"should restart refresher\", () => {\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: 1000,\n };\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n (\n mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>\n ).mockClear();\n vi.clearAllTimers();\n\n refresher.restartRefresher();\n expect(mockLogger.info).toHaveBeenCalledWith(\"Refresher stopped.\");\n expect(mockLogger.info).toHaveBeenCalledWith(\"Refresher restarted.\");\n\n // Trigger NEW_STATE event to start the refresher timer\n subject.next({ eventName: SessionEvents.NEW_STATE });\n\n vi.advanceTimersByTime(2000);\n expect(\n (mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>).mock\n .calls.length,\n ).toBeGreaterThan(0);\n });\n});\n"],
5
- "mappings": "AAAA,OAAS,WAAAA,MAAe,OACxB,OAAS,aAAAC,EAAW,cAAAC,EAAY,YAAAC,EAAU,UAAAC,EAAQ,MAAAC,EAAI,MAAAC,MAAU,SAEhE,OAAS,iBAAAC,MAAqB,0BAG9B,OACE,qDAAAC,EACA,6CAAAC,MACK,4DAKP,OAAS,iBAAAC,MAAqB,8DAE9B,OACE,0BAAAC,MAEK,2BAEPR,EAAS,yBAA0B,IAAM,CACvC,IAAIS,EACAC,EACAC,EAQJ,MAAMC,EAAoB,CACxB,YAAa,CACX,GAAIR,EAAc,IACpB,CACF,EAEMS,EAAkB,CACtB,YAAa,CACX,GAAIT,EAAc,MACpB,CACF,EAEMU,EAA4BX,EAAG,GAAG,IAAMQ,CAAU,EACxD,IAAII,EAEJhB,EAAW,IAAM,CACfI,EAAG,cAAc,EACjBM,EAAU,IAAIZ,EAC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,qBAAqB,oBAAoB,EACjEV,EAAOU,EAAW,IAAI,EAAE,qBAAqB,sBAAsB,EAGnEF,EAAQ,KAAK,CAAE,UAAWF,EAAc,SAAU,CAAC,EAEnDJ,EAAG,oBAAoB,GAAI,EAC3BF,EACGS,EAA2B,SAAsC,KAC/D,MAAM,MACX,EAAE,gBAAgB,CAAC,CACrB,CAAC,CACH,CAAC",
4
+ "sourcesContent": ["import { Subject } from \"rxjs\";\nimport { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport type { LoggerPublisherService } from \"@api/types\";\nimport {\n DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL,\n DEVICE_SESSION_REFRESHER_POLLING_INTERVAL,\n} from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport type {\n DeviceSessionEventDispatcher,\n NewEvent,\n} from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\nimport { SessionEvents } from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\n\nimport {\n DeviceSessionRefresher,\n type DeviceSessionRefresherOptions,\n} from \"./DeviceSessionRefresher\";\n\ndescribe(\"DeviceSessionRefresher\", () => {\n let subject: Subject<NewEvent>;\n let mockSessionEventDispatcher: DeviceSessionEventDispatcher;\n let mockLogger: LoggerPublisherService & {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n debug: ReturnType<typeof vi.fn>;\n subscribers?: unknown[];\n };\n\n const stubDefaultDevice = {\n deviceModel: {\n id: DeviceModelId.FLEX,\n },\n } as TransportConnectedDevice;\n\n const stubNanoSDevice = {\n deviceModel: {\n id: DeviceModelId.NANO_S,\n },\n } as TransportConnectedDevice;\n\n const mockedLoggerModuleFactory = vi.fn(() => mockLogger);\n let refresher: DeviceSessionRefresher;\n\n beforeEach(() => {\n vi.useFakeTimers();\n subject = new Subject<NewEvent>();\n mockSessionEventDispatcher = {\n listen: () => subject.asObservable(),\n dispatch: vi.fn(),\n } as unknown as DeviceSessionEventDispatcher;\n mockLogger = {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n debug: vi.fn(),\n subscribers: [],\n };\n });\n\n afterEach(() => {\n refresher?.stopRefresher();\n vi.useRealTimers();\n vi.restoreAllMocks();\n });\n\n it(\"should not start refresher if disabled\", () => {\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: true,\n pollingInterval: 1000,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n vi.advanceTimersByTime(2000);\n\n expect(mockSessionEventDispatcher.dispatch).not.toHaveBeenCalled();\n });\n\n it(\"should warn and use minimum polling interval for default device when provided interval is too low\", () => {\n const lowInterval = DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL - 100;\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: lowInterval,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n\n const expectedMessage = `Polling interval of ${lowInterval} is too low, setting to minimum as ${DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL}`;\n expect(mockLogger.warn).toHaveBeenCalledWith(expectedMessage);\n });\n\n it(\"should warn and use minimum polling interval for NANO_S device when provided interval is too low\", () => {\n const defaultNanoPollingInterval =\n DEVICE_SESSION_REFRESHER_POLLING_INTERVAL * 2;\n const lowInterval = defaultNanoPollingInterval - 100;\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: lowInterval,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubNanoSDevice,\n );\n refresher.startRefresher();\n\n const expectedMessage = `Polling interval of ${lowInterval} is too low, setting to minimum as ${defaultNanoPollingInterval}`;\n expect(mockLogger.warn).toHaveBeenCalledWith(expectedMessage);\n });\n\n it(\"should not warn when provided polling interval is valid for default device\", () => {\n const validInterval =\n DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL + 100;\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: validInterval,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n\n expect(mockLogger.warn).not.toHaveBeenCalled();\n });\n\n it(\"should dispatch refresh event on timer ticks\", () => {\n const validInterval =\n DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL + 100;\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: validInterval,\n };\n\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n\n // Trigger NEW_STATE event to start the refresher timer\n subject.next({ eventName: SessionEvents.NEW_STATE });\n\n const timerInterval = validInterval;\n\n vi.advanceTimersByTime(timerInterval * 3);\n\n expect(\n (mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>).mock\n .calls.length,\n ).toBe(4);\n expect(\n (mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>).mock\n .calls[0]![0],\n ).toEqual({\n eventName: SessionEvents.REFRESH_NEEDED,\n });\n });\n\n it(\"should stop refresher\", () => {\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: 1000,\n };\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n (\n mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>\n ).mockClear();\n\n refresher.stopRefresher();\n vi.advanceTimersByTime(2000);\n\n expect(mockSessionEventDispatcher.dispatch).not.toHaveBeenCalled();\n expect(mockLogger.info).toHaveBeenCalledWith(\"Refresher stopped.\");\n });\n\n it(\"should restart refresher\", () => {\n const options: DeviceSessionRefresherOptions = {\n isRefresherDisabled: false,\n pollingInterval: 1000,\n };\n refresher = new DeviceSessionRefresher(\n mockedLoggerModuleFactory,\n options,\n mockSessionEventDispatcher,\n stubDefaultDevice,\n );\n refresher.startRefresher();\n (\n mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>\n ).mockClear();\n vi.clearAllTimers();\n\n refresher.restartRefresher();\n expect(mockLogger.info).toHaveBeenCalledWith(\"Refresher stopped.\");\n expect(mockLogger.info).toHaveBeenCalledWith(\"Refresher restarted.\");\n\n // Trigger NEW_STATE event to start the refresher timer\n subject.next({ eventName: SessionEvents.NEW_STATE });\n\n vi.advanceTimersByTime(2000);\n expect(\n (mockSessionEventDispatcher.dispatch as ReturnType<typeof vi.fn>).mock\n .calls.length,\n ).toBeGreaterThan(0);\n });\n});\n"],
5
+ "mappings": "AAAA,OAAS,WAAAA,MAAe,OACxB,OAAS,aAAAC,EAAW,cAAAC,EAAY,YAAAC,EAAU,UAAAC,EAAQ,MAAAC,EAAI,MAAAC,MAAU,SAEhE,OAAS,iBAAAC,MAAqB,0BAG9B,OACE,qDAAAC,EACA,6CAAAC,MACK,4DAKP,OAAS,iBAAAC,MAAqB,8DAE9B,OACE,0BAAAC,MAEK,2BAEPR,EAAS,yBAA0B,IAAM,CACvC,IAAIS,EACAC,EACAC,EAQJ,MAAMC,EAAoB,CACxB,YAAa,CACX,GAAIR,EAAc,IACpB,CACF,EAEMS,EAAkB,CACtB,YAAa,CACX,GAAIT,EAAc,MACpB,CACF,EAEMU,EAA4BX,EAAG,GAAG,IAAMQ,CAAU,EACxD,IAAII,EAEJhB,EAAW,IAAM,CACfI,EAAG,cAAc,EACjBM,EAAU,IAAIZ,EACda,EAA6B,CAC3B,OAAQ,IAAMD,EAAQ,aAAa,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BAAqB,sBAAsB,EAGnEF,EAAQ,KAAK,CAAE,UAAWF,EAAc,SAAU,CAAC,EAEnDJ,EAAG,oBAAoB,GAAI,EAC3BF,EACGS,EAA2B,SAAsC,KAC/D,MAAM,MACX,EAAE,gBAAgB,CAAC,CACrB,CAAC,CACH,CAAC",
6
6
  "names": ["Subject", "afterEach", "beforeEach", "describe", "expect", "it", "vi", "DeviceModelId", "DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL", "DEVICE_SESSION_REFRESHER_POLLING_INTERVAL", "SessionEvents", "DeviceSessionRefresher", "subject", "mockSessionEventDispatcher", "mockLogger", "stubDefaultDevice", "stubNanoSDevice", "mockedLoggerModuleFactory", "refresher", "options", "lowInterval", "expectedMessage", "defaultNanoPollingInterval", "validInterval", "timerInterval"]
7
7
  }
@@ -1,2 +1,2 @@
1
- var d=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var y=(n,e,r,t)=>{for(var i=t>1?void 0:t?A(e,r):e,a=n.length-1,p;a>=0;a--)(p=n[a])&&(i=(t?p(e,r,i):p(i))||i);return t&&i&&d(e,r,i),i},u=(n,e)=>(r,t)=>e(r,t,n);import{inject as w,injectable as _}from"inversify";import{EitherAsync as o}from"purify-ts";import{DmkNetworkClient as D}from"../../../api/network/DmkNetworkClient";import{DmkNetworkClientError as F}from"../../../api/network/DmkNetworkClientError";import{managerApiTypes as E}from"../../manager-api/di/managerApiTypes";import{AppType as m}from"../../manager-api/model/Application";import{DEFAULT_PROVIDER as L}from"../../manager-api/model/Const";import{DEFAULT_FIRMWARE_DISTRIBUTION_SALT as b}from"../../manager-api/model/Const";import{HttpFetchApiError as f}from"../../manager-api/model/Errors";import{AppTypeDto as c}from"./ManagerApiDto";const s=n=>n instanceof F&&n.cause!==void 0?new f(n.cause):new f(n);let l=class{http;_provider=L;_firmwareDistributionSalt=b;constructor({managerApiUrl:e,provider:r,firmwareDistributionSalt:t}){this.http=new D({baseUrl:e}),this._provider=r,this._firmwareDistributionSalt=t}setProvider(e){this._provider===e||e<1||(this._provider=e)}getProvider(){return this._provider}getAppList(e){const{targetId:r,firmwareVersionName:t}=e;return o(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:t}})).chain(i=>this.mapApplicationDtoToApplication(i)).mapLeft(s)}getMcuList(){return o(()=>this.http.get("/mcu_versions")).chain(e=>this.mapMcuDtoToMcu(e)).mapLeft(s)}getDeviceVersion(e){const{targetId:r}=e;return o(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(t=>this.mapDeviceVersionDto(t)).mapLeft(s)}getFirmwareVersion(e){const{deviceId:r,version:t}=e;return o(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:t,provider:this._provider}})).chain(i=>this.mapFinalFirmwareDto(i)).mapLeft(s)}getFirmwareVersionById(e){return o(()=>this.http.get(`/firmware_final_versions/${e}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(s)}getOsuFirmwareVersion(e){const{deviceId:r,version:t}=e;return o(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:t,provider:this._provider}})).chain(i=>this.mapOsuFirmwareDto(i)).mapLeft(s)}getLatestFirmwareVersion(e){const r="34.27.0",{currentFinalFirmwareId:t,deviceId:i}=e;return o(()=>this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:t,device_version:i,provider:this._provider,salt:this._firmwareDistributionSalt,livecommonversion:r}})).chain(a=>this.mapLatestFirmwareDto(a)).mapLeft(s)}getAppsByHash(e){const{hashes:r}=e;return o(()=>this.http.post("/v2/apps/hash",r)).chain(t=>this.mapNullableApplicationDtoToApplication(t)).mapLeft(s)}getLanguagePackages(e){const{deviceId:r,currentFinalFirmwareId:t}=e;return o(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:t}})).chain(i=>this.mapLanguagesDtoToLanguages(i)).mapLeft(s)}mapAppTypeDtoToAppType(e){if(e===null)return null;switch(e){case c.currency:return m.currency;case c.plugin:return m.plugin;case c.tool:return m.tool;case c.swap:return m.swap}}mapApplicationDtoToApplication(e){return o(()=>Promise.resolve(e.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(e){return o(()=>Promise.resolve(e.map(r=>r===null?null:this.mapApplicationDto(r))))}mapApplicationDto(e){if(typeof e!="object"||typeof e.versionId!="number"||typeof e.versionName!="string"||e.versionDisplayName!==null&&typeof e.versionDisplayName!="string"||typeof e.version!="string"||e.currencyId!==null&&typeof e.currencyId!="string"||e.description!==null&&typeof e.description!="string"||e.applicationType!==null&&typeof e.applicationType!="string"||typeof e.dateModified!="string"||e.icon!==null&&typeof e.icon!="string"||e.authorName!==null&&typeof e.authorName!="string"||e.supportURL!==null&&typeof e.supportURL!="string"||e.contactURL!==null&&typeof e.contactURL!="string"||e.sourceURL!==null&&typeof e.sourceURL!="string"||e.compatibleWallets!==null&&typeof e.compatibleWallets!="string"||typeof e.hash!="string"||typeof e.perso!="string"||typeof e.firmware!="string"||typeof e.firmwareKey!="string"||typeof e.delete!="string"||typeof e.deleteKey!="string"||e.bytes!==null&&typeof e.bytes!="number"||e.warning!==null&&typeof e.warning!="string"||typeof e.isDevTools!="boolean"||e.category!==null&&typeof e.category!="number"||e.parent!==null&&typeof e.parent!="number"||e.parentName!==null&&typeof e.parentName!="string")throw new Error(`Incomplete application: ${JSON.stringify(e)}`);const{applicationType:r,hash:t,perso:i,firmware:a,firmwareKey:p,delete:h,deleteKey:g,...v}=e;return{...v,hash:t,perso:i,firmware:a,firmwareKey:p,delete:h,deleteKey:g,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(e){return o(()=>Promise.resolve(e.map(r=>{if(typeof r!="object"||typeof r.id!="number"||typeof r.name!="string")throw new Error(`Incomplete MCU version: ${JSON.stringify(r)}`);return{id:r.id,name:r.name}})))}mapDeviceVersionDto(e){return o(()=>{if(typeof e!="object"||typeof e.id!="number")throw new Error(`Incomplete device version: ${JSON.stringify(e)}`);const r={id:e.id};return Promise.resolve(r)})}mapFinalFirmwareDto(e){return o(()=>{if(typeof e!="object"||typeof e.id!="number"||typeof e.version!="string"||typeof e.perso!="string"||e.firmware!==null&&typeof e.firmware!="string"||e.firmware_key!==null&&typeof e.firmware_key!="string"||e.hash!==null&&typeof e.hash!="string"||e.bytes!==null&&typeof e.bytes!="number"||!Array.isArray(e.mcu_versions))throw new Error(`Incomplete final firmware: ${JSON.stringify(e)}`);const r={id:e.id,version:e.version,perso:e.perso,firmware:e.firmware,firmwareKey:e.firmware_key,hash:e.hash,bytes:e.bytes,mcuVersions:e.mcu_versions};return Promise.resolve(r)})}mapLatestFirmwareDto(e){return o(()=>{if(e.result!=="success"||!e.se_firmware_osu_version)throw new Error(`Latest firmware could not be retrieved: ${e.result}`);const r=e.se_firmware_osu_version;return Promise.resolve(r)}).chain(r=>this.mapOsuFirmwareDto(r))}mapOsuFirmwareDto(e){return o(()=>{if(typeof e!="object"||typeof e.id!="number"||typeof e.perso!="string"||typeof e.firmware!="string"||typeof e.firmware_key!="string"||e.hash!==null&&typeof e.hash!="string"||typeof e.next_se_firmware_final_version!="number")throw new Error(`Incomplete latest firmware: ${JSON.stringify(e)}`);const r={id:e.id,perso:e.perso,firmware:e.firmware,firmwareKey:e.firmware_key,hash:e.hash,nextFinalFirmware:e.next_se_firmware_final_version};return Promise.resolve(r)})}mapLanguagesDtoToLanguages(e){return o(()=>Promise.resolve(e.map(r=>this.mapLanguageDto(r))))}mapLanguageDto(e){if(typeof e!="object"||typeof e.language!="string"||typeof e.languagePackageVersionId!="number"||typeof e.version!="string"||typeof e.language_package_id!="number"||typeof e.apdu_install_url!="string"||typeof e.apdu_uninstall_url!="string"||typeof e.bytes!="number"||typeof e.date_creation!="string"||typeof e.date_last_modified!="string")throw new Error(`Incomplete language version: ${JSON.stringify(e)}`);return{language:e.language,languagePackageVersionId:e.languagePackageVersionId,version:e.version,languagePackageId:e.language_package_id,apduInstallUrl:e.apdu_install_url,apduUninstallUrl:e.apdu_uninstall_url,bytes:e.bytes,dateCreation:e.date_creation,dateLastModified:e.date_last_modified}}};l=y([_(),u(0,w(E.DmkConfig))],l);export{l as HttpManagerApiDataSource};
1
+ var d=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var y=(n,e,r,t)=>{for(var i=t>1?void 0:t?A(e,r):e,a=n.length-1,p;a>=0;a--)(p=n[a])&&(i=(t?p(e,r,i):p(i))||i);return t&&i&&d(e,r,i),i},u=(n,e)=>(r,t)=>e(r,t,n);import{inject as _,injectable as w}from"inversify";import{EitherAsync as o,Just as D,Nothing as F}from"purify-ts";import{DmkNetworkClient as E}from"../../../api/network/DmkNetworkClient";import{DmkNetworkClientError as L}from"../../../api/network/DmkNetworkClientError";import{managerApiTypes as b}from"../../manager-api/di/managerApiTypes";import{AppType as m}from"../../manager-api/model/Application";import{DEFAULT_PROVIDER as V}from"../../manager-api/model/Const";import{DEFAULT_FIRMWARE_DISTRIBUTION_SALT as P}from"../../manager-api/model/Const";import{HttpFetchApiError as f}from"../../manager-api/model/Errors";import{AppTypeDto as c}from"./ManagerApiDto";const s=n=>n instanceof L&&n.cause!==void 0?new f(n.cause):new f(n);let l=class{http;_provider=V;_firmwareDistributionSalt=P;constructor({managerApiUrl:e,provider:r,firmwareDistributionSalt:t}){this.http=new E({baseUrl:e}),this._provider=r,this._firmwareDistributionSalt=t}setProvider(e){this._provider===e||e<1||(this._provider=e)}getProvider(){return this._provider}getAppList(e){const{targetId:r,firmwareVersionName:t}=e;return o(()=>this.http.get("/v2/apps/by-target",{params:{target_id:r,provider:this._provider,firmware_version_name:t}})).chain(i=>this.mapApplicationDtoToApplication(i)).mapLeft(s)}getMcuList(){return o(()=>this.http.get("/mcu_versions")).chain(e=>this.mapMcuDtoToMcu(e)).mapLeft(s)}getDeviceVersion(e){const{targetId:r}=e;return o(()=>this.http.get("/get_device_version",{params:{target_id:r,provider:this._provider}})).chain(t=>this.mapDeviceVersionDto(t)).mapLeft(s)}getFirmwareVersion(e){const{deviceId:r,version:t}=e;return o(()=>this.http.get("/get_firmware_version",{params:{device_version:r,version_name:t,provider:this._provider}})).chain(i=>this.mapFinalFirmwareDto(i)).mapLeft(s)}getFirmwareVersionById(e){return o(()=>this.http.get(`/firmware_final_versions/${e}`)).chain(r=>this.mapFinalFirmwareDto(r)).mapLeft(s)}getOsuFirmwareVersion(e){const{deviceId:r,version:t}=e;return o(()=>this.http.get("/get_osu_version",{params:{device_version:r,version_name:t,provider:this._provider}})).chain(i=>this.mapOsuFirmwareDto(i)).mapLeft(s)}getLatestFirmwareVersion(e){const r="34.27.0",{currentFinalFirmwareId:t,deviceId:i}=e;return o(()=>this.http.get("/get_latest_firmware",{params:{current_se_firmware_final_version:t,device_version:i,provider:this._provider,salt:this._firmwareDistributionSalt,livecommonversion:r}})).chain(a=>this.mapLatestFirmwareDto(a)).mapLeft(s)}getAppsByHash(e){const{hashes:r}=e;return o(()=>this.http.post("/v2/apps/hash",r)).chain(t=>this.mapNullableApplicationDtoToApplication(t)).mapLeft(s)}getLanguagePackages(e){const{deviceId:r,currentFinalFirmwareId:t}=e;return o(()=>this.http.get("/language-packages",{params:{device_version:r,current_se_firmware_final_version:t}})).chain(i=>this.mapLanguagesDtoToLanguages(i)).mapLeft(s)}mapAppTypeDtoToAppType(e){if(e===null)return null;switch(e){case c.currency:return m.currency;case c.plugin:return m.plugin;case c.tool:return m.tool;case c.swap:return m.swap}}mapApplicationDtoToApplication(e){return o(()=>Promise.resolve(e.map(r=>this.mapApplicationDto(r))))}mapNullableApplicationDtoToApplication(e){return o(()=>Promise.resolve(e.map(r=>r===null?null:this.mapApplicationDto(r))))}mapApplicationDto(e){if(typeof e!="object"||typeof e.versionId!="number"||typeof e.versionName!="string"||e.versionDisplayName!==null&&typeof e.versionDisplayName!="string"||typeof e.version!="string"||e.currencyId!==null&&typeof e.currencyId!="string"||e.description!==null&&typeof e.description!="string"||e.applicationType!==null&&typeof e.applicationType!="string"||typeof e.dateModified!="string"||e.icon!==null&&typeof e.icon!="string"||e.authorName!==null&&typeof e.authorName!="string"||e.supportURL!==null&&typeof e.supportURL!="string"||e.contactURL!==null&&typeof e.contactURL!="string"||e.sourceURL!==null&&typeof e.sourceURL!="string"||e.compatibleWallets!==null&&typeof e.compatibleWallets!="string"||typeof e.hash!="string"||typeof e.perso!="string"||typeof e.firmware!="string"||typeof e.firmwareKey!="string"||typeof e.delete!="string"||typeof e.deleteKey!="string"||e.bytes!==null&&typeof e.bytes!="number"||e.warning!==null&&typeof e.warning!="string"||typeof e.isDevTools!="boolean"||e.category!==null&&typeof e.category!="number"||e.parent!==null&&typeof e.parent!="number"||e.parentName!==null&&typeof e.parentName!="string")throw new Error(`Incomplete application: ${JSON.stringify(e)}`);const{applicationType:r,hash:t,perso:i,firmware:a,firmwareKey:p,delete:h,deleteKey:g,...v}=e;return{...v,hash:t,perso:i,firmware:a,firmwareKey:p,delete:h,deleteKey:g,applicationType:this.mapAppTypeDtoToAppType(r)}}mapMcuDtoToMcu(e){return o(()=>Promise.resolve(e.map(r=>{if(typeof r!="object"||typeof r.id!="number"||typeof r.name!="string"||typeof r.from_bootloader_version!="string")throw new Error(`Incomplete MCU version: ${JSON.stringify(r)}`);return{id:r.id,name:r.name,fromBootloaderVersion:r.from_bootloader_version,providers:r.providers}})))}mapDeviceVersionDto(e){return o(()=>{if(typeof e!="object"||typeof e.id!="number")throw new Error(`Incomplete device version: ${JSON.stringify(e)}`);const r={id:e.id};return Promise.resolve(r)})}mapFinalFirmwareDto(e){return o(()=>{if(typeof e!="object"||typeof e.id!="number"||typeof e.version!="string"||typeof e.perso!="string"||e.firmware!==null&&typeof e.firmware!="string"||e.firmware_key!==null&&typeof e.firmware_key!="string"||e.hash!==null&&typeof e.hash!="string"||e.bytes!==null&&typeof e.bytes!="number"||!Array.isArray(e.mcu_versions))throw new Error(`Incomplete final firmware: ${JSON.stringify(e)}`);const r={id:e.id,version:e.version,perso:e.perso,firmware:e.firmware,firmwareKey:e.firmware_key,hash:e.hash,bytes:e.bytes,mcuVersions:e.mcu_versions};return Promise.resolve(r)})}mapLatestFirmwareDto(e){return o(()=>{if(e.result==="null")return Promise.resolve(null);if(e.result!=="success"||!e.se_firmware_osu_version)throw new Error(`Latest firmware could not be retrieved: ${e.result}`);const r=e.se_firmware_osu_version;return Promise.resolve(r)}).chain(r=>r===null?o(()=>Promise.resolve(F)):this.mapOsuFirmwareDto(r).map(t=>D(t)))}mapOsuFirmwareDto(e){return o(()=>{if(typeof e!="object"||typeof e.id!="number"||e.notes!==null&&typeof e.notes!="string"||typeof e.perso!="string"||typeof e.firmware!="string"||typeof e.firmware_key!="string"||e.hash!==null&&typeof e.hash!="string"||typeof e.next_se_firmware_final_version!="number")throw new Error(`Incomplete latest firmware: ${JSON.stringify(e)}`);const r={id:e.id,notes:e.notes,perso:e.perso,firmware:e.firmware,firmwareKey:e.firmware_key,hash:e.hash,nextFinalFirmware:e.next_se_firmware_final_version};return Promise.resolve(r)})}mapLanguagesDtoToLanguages(e){return o(()=>Promise.resolve(e.map(r=>this.mapLanguageDto(r))))}mapLanguageDto(e){if(typeof e!="object"||typeof e.language!="string"||typeof e.languagePackageVersionId!="number"||typeof e.version!="string"||typeof e.language_package_id!="number"||typeof e.apdu_install_url!="string"||typeof e.apdu_uninstall_url!="string"||typeof e.bytes!="number"||typeof e.date_creation!="string"||typeof e.date_last_modified!="string")throw new Error(`Incomplete language version: ${JSON.stringify(e)}`);return{language:e.language,languagePackageVersionId:e.languagePackageVersionId,version:e.version,languagePackageId:e.language_package_id,apduInstallUrl:e.apdu_install_url,apduUninstallUrl:e.apdu_uninstall_url,bytes:e.bytes,dateCreation:e.date_creation,dateLastModified:e.date_last_modified}}};l=y([w(),u(0,_(b.DmkConfig))],l);export{l as HttpManagerApiDataSource};
2
2
  //# sourceMappingURL=HttpManagerApiDataSource.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/manager-api/data/HttpManagerApiDataSource.ts"],
4
- "sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { EitherAsync } from \"purify-ts\";\n\nimport { type DmkConfig } from \"@api/DmkConfig\";\nimport { DmkNetworkClient } from \"@api/network/DmkNetworkClient\";\nimport { DmkNetworkClientError } from \"@api/network/DmkNetworkClientError\";\nimport { managerApiTypes } from \"@internal/manager-api/di/managerApiTypes\";\nimport {\n type Application,\n AppType,\n} from \"@internal/manager-api/model/Application\";\nimport { DEFAULT_PROVIDER } from \"@internal/manager-api/model/Const\";\nimport { DEFAULT_FIRMWARE_DISTRIBUTION_SALT } from \"@internal/manager-api/model/Const\";\nimport { type DeviceVersion } from \"@internal/manager-api/model/Device\";\nimport { HttpFetchApiError } from \"@internal/manager-api/model/Errors\";\nimport type {\n FinalFirmware,\n McuFirmware,\n OsuFirmware,\n} from \"@internal/manager-api/model/Firmware\";\nimport { type LanguagePackage } from \"@internal/manager-api/model/Language\";\nimport {\n type GetAppByHashParams,\n type GetAppListParams,\n type GetDeviceVersionParams,\n type GetFirmwareVersionParams,\n type GetLanguagePackagesParams,\n type GetLatestFirmwareVersionParams,\n} from \"@internal/manager-api/model/Params\";\n\nimport { ManagerApiDataSource } from \"./ManagerApiDataSource\";\nimport {\n ApplicationDto,\n AppTypeDto,\n DeviceVersionDto,\n FirmwareFinalVersionDto,\n FirmwareOsuVersionDto,\n LanguagePackageVersionDto,\n LatestFirmwareOsuVersionResponseDto,\n McuVersionDto,\n} from \"./ManagerApiDto\";\n\nconst toHttpFetchApiError = (error: unknown): HttpFetchApiError => {\n // The network client wraps fetch errors in DmkNetworkClientError. Unwrap the\n // original cause when available so consumers (and tests) keep seeing the\n // underlying error.\n if (error instanceof DmkNetworkClientError && error.cause !== undefined) {\n return new HttpFetchApiError(error.cause);\n }\n return new HttpFetchApiError(error);\n};\n\n@injectable()\nexport class HttpManagerApiDataSource implements ManagerApiDataSource {\n private readonly http: DmkNetworkClient;\n private _provider: number = DEFAULT_PROVIDER;\n private _firmwareDistributionSalt: string =\n DEFAULT_FIRMWARE_DISTRIBUTION_SALT;\n\n constructor(\n @inject(managerApiTypes.DmkConfig)\n { managerApiUrl, provider, firmwareDistributionSalt }: DmkConfig,\n ) {\n this.http = new DmkNetworkClient({ baseUrl: managerApiUrl });\n this._provider = provider;\n this._firmwareDistributionSalt = firmwareDistributionSalt;\n }\n\n setProvider(provider: number): void {\n if (this._provider === provider || provider < 1) {\n return;\n }\n this._provider = provider;\n }\n\n getProvider(): number {\n return this._provider;\n }\n\n getAppList(\n params: GetAppListParams,\n ): EitherAsync<HttpFetchApiError, Array<Application>> {\n const { targetId, firmwareVersionName } = params;\n return EitherAsync(() =>\n this.http.get(\"/v2/apps/by-target\", {\n params: {\n target_id: targetId,\n provider: this._provider,\n firmware_version_name: firmwareVersionName,\n },\n }),\n )\n .chain((apps) =>\n this.mapApplicationDtoToApplication(apps as Array<ApplicationDto>),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getMcuList(): EitherAsync<HttpFetchApiError, Array<McuFirmware>> {\n return EitherAsync(() => this.http.get(\"/mcu_versions\"))\n .chain((mcus) => this.mapMcuDtoToMcu(mcus as Array<McuVersionDto>))\n .mapLeft(toHttpFetchApiError);\n }\n\n getDeviceVersion(\n params: GetDeviceVersionParams,\n ): EitherAsync<HttpFetchApiError, DeviceVersion> {\n const { targetId } = params;\n return EitherAsync(() =>\n this.http.get(\"/get_device_version\", {\n params: { target_id: targetId, provider: this._provider },\n }),\n )\n .chain((deviceVersion) =>\n this.mapDeviceVersionDto(deviceVersion as DeviceVersionDto),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getFirmwareVersion(\n params: GetFirmwareVersionParams,\n ): EitherAsync<HttpFetchApiError, FinalFirmware> {\n const { deviceId, version } = params;\n return EitherAsync(() =>\n this.http.get(\"/get_firmware_version\", {\n params: {\n device_version: deviceId,\n version_name: version,\n provider: this._provider,\n },\n }),\n )\n .chain((finalFirmware) =>\n this.mapFinalFirmwareDto(finalFirmware as FirmwareFinalVersionDto),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getFirmwareVersionById(\n finalFirmwareId: number,\n ): EitherAsync<HttpFetchApiError, FinalFirmware> {\n return EitherAsync(() =>\n this.http.get(`/firmware_final_versions/${finalFirmwareId}`),\n )\n .chain((finalFirmware) =>\n this.mapFinalFirmwareDto(finalFirmware as FirmwareFinalVersionDto),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getOsuFirmwareVersion(\n params: GetFirmwareVersionParams,\n ): EitherAsync<HttpFetchApiError, OsuFirmware> {\n const { deviceId, version } = params;\n return EitherAsync(() =>\n this.http.get(\"/get_osu_version\", {\n params: {\n device_version: deviceId,\n version_name: version,\n provider: this._provider,\n },\n }),\n )\n .chain((osuFirmware) =>\n this.mapOsuFirmwareDto(osuFirmware as FirmwareOsuVersionDto),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getLatestFirmwareVersion(\n params: GetLatestFirmwareVersionParams,\n ): EitherAsync<HttpFetchApiError, OsuFirmware> {\n const livecommonversion = \"34.27.0\"; // Legacy parameter that should just be a too old\n const { currentFinalFirmwareId, deviceId } = params;\n return EitherAsync(() =>\n this.http.get(\"/get_latest_firmware\", {\n params: {\n current_se_firmware_final_version: currentFinalFirmwareId,\n device_version: deviceId,\n provider: this._provider,\n salt: this._firmwareDistributionSalt,\n livecommonversion,\n },\n }),\n )\n .chain((latestFirmware) =>\n this.mapLatestFirmwareDto(\n latestFirmware as LatestFirmwareOsuVersionResponseDto,\n ),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getAppsByHash(\n params: GetAppByHashParams,\n ): EitherAsync<HttpFetchApiError, Array<Application | null>> {\n const { hashes } = params;\n return EitherAsync(() => this.http.post(\"/v2/apps/hash\", hashes))\n .chain((apps) =>\n this.mapNullableApplicationDtoToApplication(\n apps as Array<ApplicationDto | null>,\n ),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getLanguagePackages(\n params: GetLanguagePackagesParams,\n ): EitherAsync<HttpFetchApiError, Array<LanguagePackage>> {\n const { deviceId, currentFinalFirmwareId } = params;\n return EitherAsync(() =>\n this.http.get(\"/language-packages\", {\n params: {\n device_version: deviceId,\n current_se_firmware_final_version: currentFinalFirmwareId,\n },\n }),\n )\n .chain((apps) =>\n this.mapLanguagesDtoToLanguages(\n apps as Array<LanguagePackageVersionDto>,\n ),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n private mapAppTypeDtoToAppType(appType: AppTypeDto | null): AppType | null {\n if (appType === null) {\n return null;\n }\n switch (appType) {\n case AppTypeDto.currency:\n return AppType.currency;\n case AppTypeDto.plugin:\n return AppType.plugin;\n case AppTypeDto.tool:\n return AppType.tool;\n case AppTypeDto.swap:\n return AppType.swap;\n }\n }\n\n private mapApplicationDtoToApplication(\n apps: Array<ApplicationDto>,\n ): EitherAsync<Error, Array<Application>> {\n return EitherAsync(() =>\n Promise.resolve(apps.map((app) => this.mapApplicationDto(app))),\n );\n }\n\n private mapNullableApplicationDtoToApplication(\n apps: Array<ApplicationDto | null>,\n ): EitherAsync<Error, Array<Application | null>> {\n return EitherAsync(() =>\n Promise.resolve(\n apps.map((app) => {\n if (app === null) {\n return null;\n }\n return this.mapApplicationDto(app);\n }),\n ),\n );\n }\n\n private mapApplicationDto(app: ApplicationDto): Application {\n if (\n typeof app !== \"object\" ||\n typeof app.versionId !== \"number\" ||\n typeof app.versionName !== \"string\" ||\n (app.versionDisplayName !== null &&\n typeof app.versionDisplayName !== \"string\") ||\n typeof app.version !== \"string\" ||\n (app.currencyId !== null && typeof app.currencyId !== \"string\") ||\n (app.description !== null && typeof app.description !== \"string\") ||\n (app.applicationType !== null &&\n typeof app.applicationType !== \"string\") ||\n typeof app.dateModified !== \"string\" ||\n (app.icon !== null && typeof app.icon !== \"string\") ||\n (app.authorName !== null && typeof app.authorName !== \"string\") ||\n (app.supportURL !== null && typeof app.supportURL !== \"string\") ||\n (app.contactURL !== null && typeof app.contactURL !== \"string\") ||\n (app.sourceURL !== null && typeof app.sourceURL !== \"string\") ||\n (app.compatibleWallets !== null &&\n typeof app.compatibleWallets !== \"string\") ||\n typeof app.hash !== \"string\" ||\n typeof app.perso !== \"string\" ||\n typeof app.firmware !== \"string\" ||\n typeof app.firmwareKey !== \"string\" ||\n typeof app.delete !== \"string\" ||\n typeof app.deleteKey !== \"string\" ||\n (app.bytes !== null && typeof app.bytes !== \"number\") ||\n (app.warning !== null && typeof app.warning !== \"string\") ||\n typeof app.isDevTools !== \"boolean\" ||\n (app.category !== null && typeof app.category !== \"number\") ||\n (app.parent !== null && typeof app.parent !== \"number\") ||\n (app.parentName !== null && typeof app.parentName !== \"string\")\n ) {\n throw new Error(`Incomplete application: ${JSON.stringify(app)}`);\n }\n const {\n applicationType,\n hash,\n perso,\n firmware,\n firmwareKey,\n delete: del,\n deleteKey,\n ...rest\n } = app;\n const ret: Application = {\n ...rest,\n hash: hash!,\n perso: perso!,\n firmware: firmware!,\n firmwareKey: firmwareKey!,\n delete: del!,\n deleteKey: deleteKey!,\n applicationType: this.mapAppTypeDtoToAppType(applicationType),\n };\n return ret;\n }\n\n private mapMcuDtoToMcu(\n mcus: Array<McuVersionDto>,\n ): EitherAsync<Error, Array<McuFirmware>> {\n return EitherAsync(() =>\n Promise.resolve(\n mcus.map((mcu) => {\n if (\n typeof mcu !== \"object\" ||\n typeof mcu.id !== \"number\" ||\n typeof mcu.name !== \"string\"\n ) {\n throw new Error(`Incomplete MCU version: ${JSON.stringify(mcu)}`);\n }\n const ret: McuFirmware = {\n id: mcu.id,\n name: mcu.name,\n };\n return ret;\n }),\n ),\n );\n }\n\n private mapDeviceVersionDto(\n deviceVersion: DeviceVersionDto,\n ): EitherAsync<Error, DeviceVersion> {\n return EitherAsync(() => {\n if (\n typeof deviceVersion !== \"object\" ||\n typeof deviceVersion.id !== \"number\"\n ) {\n throw new Error(\n `Incomplete device version: ${JSON.stringify(deviceVersion)}`,\n );\n }\n const ret: DeviceVersion = {\n id: deviceVersion.id,\n };\n return Promise.resolve(ret);\n });\n }\n\n private mapFinalFirmwareDto(\n finalFirmware: FirmwareFinalVersionDto,\n ): EitherAsync<Error, FinalFirmware> {\n return EitherAsync(() => {\n if (\n typeof finalFirmware !== \"object\" ||\n typeof finalFirmware.id !== \"number\" ||\n typeof finalFirmware.version !== \"string\" ||\n typeof finalFirmware.perso !== \"string\" ||\n (finalFirmware.firmware !== null &&\n typeof finalFirmware.firmware !== \"string\") ||\n (finalFirmware.firmware_key !== null &&\n typeof finalFirmware.firmware_key !== \"string\") ||\n (finalFirmware.hash !== null &&\n typeof finalFirmware.hash !== \"string\") ||\n (finalFirmware.bytes !== null &&\n typeof finalFirmware.bytes !== \"number\") ||\n !Array.isArray(finalFirmware.mcu_versions)\n ) {\n throw new Error(\n `Incomplete final firmware: ${JSON.stringify(finalFirmware)}`,\n );\n }\n const ret: FinalFirmware = {\n id: finalFirmware.id,\n version: finalFirmware.version,\n perso: finalFirmware.perso,\n firmware: finalFirmware.firmware,\n firmwareKey: finalFirmware.firmware_key,\n hash: finalFirmware.hash,\n bytes: finalFirmware.bytes,\n mcuVersions: finalFirmware.mcu_versions,\n };\n return Promise.resolve(ret);\n });\n }\n\n private mapLatestFirmwareDto(\n latestFirmware: LatestFirmwareOsuVersionResponseDto,\n ): EitherAsync<Error, OsuFirmware> {\n return EitherAsync<Error, FirmwareOsuVersionDto>(() => {\n if (\n latestFirmware.result !== \"success\" ||\n !latestFirmware.se_firmware_osu_version\n ) {\n throw new Error(\n `Latest firmware could not be retrieved: ${latestFirmware.result}`,\n );\n }\n const osuDto = latestFirmware.se_firmware_osu_version;\n return Promise.resolve(osuDto);\n }).chain((osuDto) => this.mapOsuFirmwareDto(osuDto));\n }\n\n private mapOsuFirmwareDto(\n osuDto: FirmwareOsuVersionDto,\n ): EitherAsync<Error, OsuFirmware> {\n return EitherAsync(() => {\n if (\n typeof osuDto !== \"object\" ||\n typeof osuDto.id !== \"number\" ||\n typeof osuDto.perso !== \"string\" ||\n typeof osuDto.firmware !== \"string\" ||\n typeof osuDto.firmware_key !== \"string\" ||\n (osuDto.hash !== null && typeof osuDto.hash !== \"string\") ||\n typeof osuDto.next_se_firmware_final_version !== \"number\"\n ) {\n throw new Error(\n `Incomplete latest firmware: ${JSON.stringify(osuDto)}`,\n );\n }\n const ret: OsuFirmware = {\n id: osuDto.id,\n perso: osuDto.perso,\n firmware: osuDto.firmware,\n firmwareKey: osuDto.firmware_key,\n hash: osuDto.hash,\n nextFinalFirmware: osuDto.next_se_firmware_final_version,\n };\n return Promise.resolve(ret);\n });\n }\n\n private mapLanguagesDtoToLanguages(\n languages: Array<LanguagePackageVersionDto>,\n ): EitherAsync<Error, Array<LanguagePackage>> {\n return EitherAsync(() =>\n Promise.resolve(\n languages.map((language) => this.mapLanguageDto(language)),\n ),\n );\n }\n\n private mapLanguageDto(language: LanguagePackageVersionDto): LanguagePackage {\n if (\n typeof language !== \"object\" ||\n typeof language.language !== \"string\" ||\n typeof language.languagePackageVersionId !== \"number\" ||\n typeof language.version !== \"string\" ||\n typeof language.language_package_id !== \"number\" ||\n typeof language.apdu_install_url !== \"string\" ||\n typeof language.apdu_uninstall_url !== \"string\" ||\n typeof language.bytes !== \"number\" ||\n typeof language.date_creation !== \"string\" ||\n typeof language.date_last_modified !== \"string\"\n ) {\n throw new Error(\n `Incomplete language version: ${JSON.stringify(language)}`,\n );\n }\n const ret: LanguagePackage = {\n language: language.language,\n languagePackageVersionId: language.languagePackageVersionId,\n version: language.version,\n languagePackageId: language.language_package_id,\n apduInstallUrl: language.apdu_install_url,\n apduUninstallUrl: language.apdu_uninstall_url,\n bytes: language.bytes,\n dateCreation: language.date_creation,\n dateLastModified: language.date_last_modified,\n };\n return ret;\n }\n}\n"],
5
- "mappings": "iOAAA,OAAS,UAAAA,EAAQ,cAAAC,MAAkB,YACnC,OAAS,eAAAC,MAAmB,YAG5B,OAAS,oBAAAC,MAAwB,gCACjC,OAAS,yBAAAC,MAA6B,qCACtC,OAAS,mBAAAC,MAAuB,2CAChC,OAEE,WAAAC,MACK,0CACP,OAAS,oBAAAC,MAAwB,o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IAPxB5C",
6
- "names": ["inject", "injectable", "EitherAsync", "DmkNetworkClient", "DmkNetworkClientError", "managerApiTypes", "AppType", "DEFAULT_PROVIDER", "DEFAULT_FIRMWARE_DISTRIBUTION_SALT", "HttpFetchApiError", "AppTypeDto", "toHttpFetchApiError", "error", "DmkNetworkClientError", "HttpFetchApiError", "HttpManagerApiDataSource", "DEFAULT_PROVIDER", "DEFAULT_FIRMWARE_DISTRIBUTION_SALT", "managerApiUrl", "provider", "firmwareDistributionSalt", "DmkNetworkClient", "params", "targetId", "firmwareVersionName", "EitherAsync", "apps", "mcus", "deviceVersion", "deviceId", "version", "finalFirmware", "finalFirmwareId", "osuFirmware", "livecommonversion", "currentFinalFirmwareId", "latestFirmware", "hashes", "appType", "AppTypeDto", "AppType", "app", "applicationType", "hash", "perso", "firmware", "firmwareKey", "del", "deleteKey", "rest", "mcu", "ret", "osuDto", "languages", "language", "__decorateClass", "injectable", "__decorateParam", "inject", "managerApiTypes"]
4
+ "sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { EitherAsync, Just, Maybe, Nothing } from \"purify-ts\";\n\nimport { type DmkConfig } from \"@api/DmkConfig\";\nimport { DmkNetworkClient } from \"@api/network/DmkNetworkClient\";\nimport { DmkNetworkClientError } from \"@api/network/DmkNetworkClientError\";\nimport { managerApiTypes } from \"@internal/manager-api/di/managerApiTypes\";\nimport {\n type Application,\n AppType,\n} from \"@internal/manager-api/model/Application\";\nimport { DEFAULT_PROVIDER } from \"@internal/manager-api/model/Const\";\nimport { DEFAULT_FIRMWARE_DISTRIBUTION_SALT } from \"@internal/manager-api/model/Const\";\nimport { type DeviceVersion } from \"@internal/manager-api/model/Device\";\nimport { HttpFetchApiError } from \"@internal/manager-api/model/Errors\";\nimport type {\n FinalFirmware,\n McuFirmware,\n OsuFirmware,\n} from \"@internal/manager-api/model/Firmware\";\nimport { type LanguagePackage } from \"@internal/manager-api/model/Language\";\nimport {\n type GetAppByHashParams,\n type GetAppListParams,\n type GetDeviceVersionParams,\n type GetFirmwareVersionParams,\n type GetLanguagePackagesParams,\n type GetLatestFirmwareVersionParams,\n} from \"@internal/manager-api/model/Params\";\n\nimport { ManagerApiDataSource } from \"./ManagerApiDataSource\";\nimport {\n ApplicationDto,\n AppTypeDto,\n DeviceVersionDto,\n FirmwareFinalVersionDto,\n FirmwareOsuVersionDto,\n LanguagePackageVersionDto,\n LatestFirmwareOsuVersionResponseDto,\n McuVersionDto,\n} from \"./ManagerApiDto\";\n\nconst toHttpFetchApiError = (error: unknown): HttpFetchApiError => {\n // The network client wraps fetch errors in DmkNetworkClientError. Unwrap the\n // original cause when available so consumers (and tests) keep seeing the\n // underlying error.\n if (error instanceof DmkNetworkClientError && error.cause !== undefined) {\n return new HttpFetchApiError(error.cause);\n }\n return new HttpFetchApiError(error);\n};\n\n@injectable()\nexport class HttpManagerApiDataSource implements ManagerApiDataSource {\n private readonly http: DmkNetworkClient;\n private _provider: number = DEFAULT_PROVIDER;\n private _firmwareDistributionSalt: string =\n DEFAULT_FIRMWARE_DISTRIBUTION_SALT;\n\n constructor(\n @inject(managerApiTypes.DmkConfig)\n { managerApiUrl, provider, firmwareDistributionSalt }: DmkConfig,\n ) {\n this.http = new DmkNetworkClient({ baseUrl: managerApiUrl });\n this._provider = provider;\n this._firmwareDistributionSalt = firmwareDistributionSalt;\n }\n\n setProvider(provider: number): void {\n if (this._provider === provider || provider < 1) {\n return;\n }\n this._provider = provider;\n }\n\n getProvider(): number {\n return this._provider;\n }\n\n getAppList(\n params: GetAppListParams,\n ): EitherAsync<HttpFetchApiError, Array<Application>> {\n const { targetId, firmwareVersionName } = params;\n return EitherAsync(() =>\n this.http.get(\"/v2/apps/by-target\", {\n params: {\n target_id: targetId,\n provider: this._provider,\n firmware_version_name: firmwareVersionName,\n },\n }),\n )\n .chain((apps) =>\n this.mapApplicationDtoToApplication(apps as Array<ApplicationDto>),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getMcuList(): EitherAsync<HttpFetchApiError, Array<McuFirmware>> {\n return EitherAsync(() => this.http.get(\"/mcu_versions\"))\n .chain((mcus) => this.mapMcuDtoToMcu(mcus as Array<McuVersionDto>))\n .mapLeft(toHttpFetchApiError);\n }\n\n getDeviceVersion(\n params: GetDeviceVersionParams,\n ): EitherAsync<HttpFetchApiError, DeviceVersion> {\n const { targetId } = params;\n return EitherAsync(() =>\n this.http.get(\"/get_device_version\", {\n params: { target_id: targetId, provider: this._provider },\n }),\n )\n .chain((deviceVersion) =>\n this.mapDeviceVersionDto(deviceVersion as DeviceVersionDto),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getFirmwareVersion(\n params: GetFirmwareVersionParams,\n ): EitherAsync<HttpFetchApiError, FinalFirmware> {\n const { deviceId, version } = params;\n return EitherAsync(() =>\n this.http.get(\"/get_firmware_version\", {\n params: {\n device_version: deviceId,\n version_name: version,\n provider: this._provider,\n },\n }),\n )\n .chain((finalFirmware) =>\n this.mapFinalFirmwareDto(finalFirmware as FirmwareFinalVersionDto),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getFirmwareVersionById(\n finalFirmwareId: number,\n ): EitherAsync<HttpFetchApiError, FinalFirmware> {\n return EitherAsync(() =>\n this.http.get(`/firmware_final_versions/${finalFirmwareId}`),\n )\n .chain((finalFirmware) =>\n this.mapFinalFirmwareDto(finalFirmware as FirmwareFinalVersionDto),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getOsuFirmwareVersion(\n params: GetFirmwareVersionParams,\n ): EitherAsync<HttpFetchApiError, OsuFirmware> {\n const { deviceId, version } = params;\n return EitherAsync(() =>\n this.http.get(\"/get_osu_version\", {\n params: {\n device_version: deviceId,\n version_name: version,\n provider: this._provider,\n },\n }),\n )\n .chain((osuFirmware) =>\n this.mapOsuFirmwareDto(osuFirmware as FirmwareOsuVersionDto),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getLatestFirmwareVersion(\n params: GetLatestFirmwareVersionParams,\n ): EitherAsync<HttpFetchApiError, Maybe<OsuFirmware>> {\n const livecommonversion = \"34.27.0\"; // Legacy parameter that should just be a too old\n const { currentFinalFirmwareId, deviceId } = params;\n return EitherAsync(() =>\n this.http.get(\"/get_latest_firmware\", {\n params: {\n current_se_firmware_final_version: currentFinalFirmwareId,\n device_version: deviceId,\n provider: this._provider,\n salt: this._firmwareDistributionSalt,\n livecommonversion,\n },\n }),\n )\n .chain((latestFirmware) =>\n this.mapLatestFirmwareDto(\n latestFirmware as LatestFirmwareOsuVersionResponseDto,\n ),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getAppsByHash(\n params: GetAppByHashParams,\n ): EitherAsync<HttpFetchApiError, Array<Application | null>> {\n const { hashes } = params;\n return EitherAsync(() => this.http.post(\"/v2/apps/hash\", hashes))\n .chain((apps) =>\n this.mapNullableApplicationDtoToApplication(\n apps as Array<ApplicationDto | null>,\n ),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n getLanguagePackages(\n params: GetLanguagePackagesParams,\n ): EitherAsync<HttpFetchApiError, Array<LanguagePackage>> {\n const { deviceId, currentFinalFirmwareId } = params;\n return EitherAsync(() =>\n this.http.get(\"/language-packages\", {\n params: {\n device_version: deviceId,\n current_se_firmware_final_version: currentFinalFirmwareId,\n },\n }),\n )\n .chain((apps) =>\n this.mapLanguagesDtoToLanguages(\n apps as Array<LanguagePackageVersionDto>,\n ),\n )\n .mapLeft(toHttpFetchApiError);\n }\n\n private mapAppTypeDtoToAppType(appType: AppTypeDto | null): AppType | null {\n if (appType === null) {\n return null;\n }\n switch (appType) {\n case AppTypeDto.currency:\n return AppType.currency;\n case AppTypeDto.plugin:\n return AppType.plugin;\n case AppTypeDto.tool:\n return AppType.tool;\n case AppTypeDto.swap:\n return AppType.swap;\n }\n }\n\n private mapApplicationDtoToApplication(\n apps: Array<ApplicationDto>,\n ): EitherAsync<Error, Array<Application>> {\n return EitherAsync(() =>\n Promise.resolve(apps.map((app) => this.mapApplicationDto(app))),\n );\n }\n\n private mapNullableApplicationDtoToApplication(\n apps: Array<ApplicationDto | null>,\n ): EitherAsync<Error, Array<Application | null>> {\n return EitherAsync(() =>\n Promise.resolve(\n apps.map((app) => {\n if (app === null) {\n return null;\n }\n return this.mapApplicationDto(app);\n }),\n ),\n );\n }\n\n private mapApplicationDto(app: ApplicationDto): Application {\n if (\n typeof app !== \"object\" ||\n typeof app.versionId !== \"number\" ||\n typeof app.versionName !== \"string\" ||\n (app.versionDisplayName !== null &&\n typeof app.versionDisplayName !== \"string\") ||\n typeof app.version !== \"string\" ||\n (app.currencyId !== null && typeof app.currencyId !== \"string\") ||\n (app.description !== null && typeof app.description !== \"string\") ||\n (app.applicationType !== null &&\n typeof app.applicationType !== \"string\") ||\n typeof app.dateModified !== \"string\" ||\n (app.icon !== null && typeof app.icon !== \"string\") ||\n (app.authorName !== null && typeof app.authorName !== \"string\") ||\n (app.supportURL !== null && typeof app.supportURL !== \"string\") ||\n (app.contactURL !== null && typeof app.contactURL !== \"string\") ||\n (app.sourceURL !== null && typeof app.sourceURL !== \"string\") ||\n (app.compatibleWallets !== null &&\n typeof app.compatibleWallets !== \"string\") ||\n typeof app.hash !== \"string\" ||\n typeof app.perso !== \"string\" ||\n typeof app.firmware !== \"string\" ||\n typeof app.firmwareKey !== \"string\" ||\n typeof app.delete !== \"string\" ||\n typeof app.deleteKey !== \"string\" ||\n (app.bytes !== null && typeof app.bytes !== \"number\") ||\n (app.warning !== null && typeof app.warning !== \"string\") ||\n typeof app.isDevTools !== \"boolean\" ||\n (app.category !== null && typeof app.category !== \"number\") ||\n (app.parent !== null && typeof app.parent !== \"number\") ||\n (app.parentName !== null && typeof app.parentName !== \"string\")\n ) {\n throw new Error(`Incomplete application: ${JSON.stringify(app)}`);\n }\n const {\n applicationType,\n hash,\n perso,\n firmware,\n firmwareKey,\n delete: del,\n deleteKey,\n ...rest\n } = app;\n const ret: Application = {\n ...rest,\n hash: hash!,\n perso: perso!,\n firmware: firmware!,\n firmwareKey: firmwareKey!,\n delete: del!,\n deleteKey: deleteKey!,\n applicationType: this.mapAppTypeDtoToAppType(applicationType),\n };\n return ret;\n }\n\n private mapMcuDtoToMcu(\n mcus: Array<McuVersionDto>,\n ): EitherAsync<Error, Array<McuFirmware>> {\n return EitherAsync(() =>\n Promise.resolve(\n mcus.map((mcu) => {\n if (\n typeof mcu !== \"object\" ||\n typeof mcu.id !== \"number\" ||\n typeof mcu.name !== \"string\" ||\n typeof mcu.from_bootloader_version !== \"string\"\n ) {\n throw new Error(`Incomplete MCU version: ${JSON.stringify(mcu)}`);\n }\n const ret: McuFirmware = {\n id: mcu.id,\n name: mcu.name,\n fromBootloaderVersion: mcu.from_bootloader_version,\n providers: mcu.providers,\n };\n return ret;\n }),\n ),\n );\n }\n\n private mapDeviceVersionDto(\n deviceVersion: DeviceVersionDto,\n ): EitherAsync<Error, DeviceVersion> {\n return EitherAsync(() => {\n if (\n typeof deviceVersion !== \"object\" ||\n typeof deviceVersion.id !== \"number\"\n ) {\n throw new Error(\n `Incomplete device version: ${JSON.stringify(deviceVersion)}`,\n );\n }\n const ret: DeviceVersion = {\n id: deviceVersion.id,\n };\n return Promise.resolve(ret);\n });\n }\n\n private mapFinalFirmwareDto(\n finalFirmware: FirmwareFinalVersionDto,\n ): EitherAsync<Error, FinalFirmware> {\n return EitherAsync(() => {\n if (\n typeof finalFirmware !== \"object\" ||\n typeof finalFirmware.id !== \"number\" ||\n typeof finalFirmware.version !== \"string\" ||\n typeof finalFirmware.perso !== \"string\" ||\n (finalFirmware.firmware !== null &&\n typeof finalFirmware.firmware !== \"string\") ||\n (finalFirmware.firmware_key !== null &&\n typeof finalFirmware.firmware_key !== \"string\") ||\n (finalFirmware.hash !== null &&\n typeof finalFirmware.hash !== \"string\") ||\n (finalFirmware.bytes !== null &&\n typeof finalFirmware.bytes !== \"number\") ||\n !Array.isArray(finalFirmware.mcu_versions)\n ) {\n throw new Error(\n `Incomplete final firmware: ${JSON.stringify(finalFirmware)}`,\n );\n }\n const ret: FinalFirmware = {\n id: finalFirmware.id,\n version: finalFirmware.version,\n perso: finalFirmware.perso,\n firmware: finalFirmware.firmware,\n firmwareKey: finalFirmware.firmware_key,\n hash: finalFirmware.hash,\n bytes: finalFirmware.bytes,\n mcuVersions: finalFirmware.mcu_versions,\n };\n return Promise.resolve(ret);\n });\n }\n\n private mapLatestFirmwareDto(\n latestFirmware: LatestFirmwareOsuVersionResponseDto,\n ): EitherAsync<Error, Maybe<OsuFirmware>> {\n return EitherAsync<Error, FirmwareOsuVersionDto | null>(() => {\n /**\n * This is how we know that there is no update available.\n * See the {@link https://github.com/LedgerHQ/ledger-live/blob/develop/libs/device-core/src/managerApi/repositories/HttpManagerApiRepository.ts#L59-L61 | ledger-live implementation}.\n */\n if (latestFirmware.result === \"null\") {\n return Promise.resolve(null);\n }\n if (\n latestFirmware.result !== \"success\" ||\n !latestFirmware.se_firmware_osu_version\n ) {\n throw new Error(\n `Latest firmware could not be retrieved: ${latestFirmware.result}`,\n );\n }\n const osuDto = latestFirmware.se_firmware_osu_version;\n return Promise.resolve(osuDto);\n }).chain((osuDto) => {\n if (null === osuDto) {\n return EitherAsync(() => Promise.resolve(Nothing));\n }\n return this.mapOsuFirmwareDto(osuDto).map((osuFirmware) =>\n Just(osuFirmware),\n );\n });\n }\n\n private mapOsuFirmwareDto(\n osuDto: FirmwareOsuVersionDto,\n ): EitherAsync<Error, OsuFirmware> {\n return EitherAsync(() => {\n if (\n typeof osuDto !== \"object\" ||\n typeof osuDto.id !== \"number\" ||\n (osuDto.notes !== null && typeof osuDto.notes !== \"string\") ||\n typeof osuDto.perso !== \"string\" ||\n typeof osuDto.firmware !== \"string\" ||\n typeof osuDto.firmware_key !== \"string\" ||\n (osuDto.hash !== null && typeof osuDto.hash !== \"string\") ||\n typeof osuDto.next_se_firmware_final_version !== \"number\"\n ) {\n throw new Error(\n `Incomplete latest firmware: ${JSON.stringify(osuDto)}`,\n );\n }\n const ret: OsuFirmware = {\n id: osuDto.id,\n notes: osuDto.notes,\n perso: osuDto.perso,\n firmware: osuDto.firmware,\n firmwareKey: osuDto.firmware_key,\n hash: osuDto.hash,\n nextFinalFirmware: osuDto.next_se_firmware_final_version,\n };\n return Promise.resolve(ret);\n });\n }\n\n private mapLanguagesDtoToLanguages(\n languages: Array<LanguagePackageVersionDto>,\n ): EitherAsync<Error, Array<LanguagePackage>> {\n return EitherAsync(() =>\n Promise.resolve(\n languages.map((language) => this.mapLanguageDto(language)),\n ),\n );\n }\n\n private mapLanguageDto(language: LanguagePackageVersionDto): LanguagePackage {\n if (\n typeof language !== \"object\" ||\n typeof language.language !== \"string\" ||\n typeof language.languagePackageVersionId !== \"number\" ||\n typeof language.version !== \"string\" ||\n typeof language.language_package_id !== \"number\" ||\n typeof language.apdu_install_url !== \"string\" ||\n typeof language.apdu_uninstall_url !== \"string\" ||\n typeof language.bytes !== \"number\" ||\n typeof language.date_creation !== \"string\" ||\n typeof language.date_last_modified !== \"string\"\n ) {\n throw new Error(\n `Incomplete language version: ${JSON.stringify(language)}`,\n );\n }\n const ret: LanguagePackage = {\n language: language.language,\n languagePackageVersionId: language.languagePackageVersionId,\n version: language.version,\n languagePackageId: language.language_package_id,\n apduInstallUrl: language.apdu_install_url,\n apduUninstallUrl: language.apdu_uninstall_url,\n bytes: language.bytes,\n dateCreation: language.date_creation,\n dateLastModified: language.date_last_modified,\n };\n return ret;\n }\n}\n"],
5
+ "mappings": "iOAAA,OAAS,UAAAA,EAAQ,cAAAC,MAAkB,YACnC,OAAS,eAAAC,EAAa,QAAAC,EAAa,WAAAC,MAAe,YAGlD,OAAS,oBAAAC,MAAwB,gCACjC,OAAS,yBAAAC,MAA6B,qCACtC,OAAS,mBAAAC,MAAuB,2CAChC,OAEE,WAAAC,MACK,0CACP,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,sCAAAC,MAA0C,oCAEnD,OAAS,qBAAAC,MAAyB,qCAiBlC,OAEE,cAAAC,MAOK,kBAEP,MAAMC,EAAuBC,GAIvBA,aAAiBC,GAAyBD,EAAM,QAAU,OACrD,I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EAAS,MAChB,aAAcA,EAAS,cACvB,iBAAkBA,EAAS,kBAC7B,CAEF,CACF,EAtcazC,EAAN0C,EAAA,CADNC,EAAW,EAQPC,EAAA,EAAAC,EAAOC,EAAgB,SAAS,IAPxB9C",
6
+ "names": ["inject", "injectable", "EitherAsync", "Just", "Nothing", "DmkNetworkClient", "DmkNetworkClientError", "managerApiTypes", "AppType", "DEFAULT_PROVIDER", "DEFAULT_FIRMWARE_DISTRIBUTION_SALT", "HttpFetchApiError", "AppTypeDto", "toHttpFetchApiError", "error", "DmkNetworkClientError", "HttpFetchApiError", "HttpManagerApiDataSource", "DEFAULT_PROVIDER", "DEFAULT_FIRMWARE_DISTRIBUTION_SALT", "managerApiUrl", "provider", "firmwareDistributionSalt", "DmkNetworkClient", "params", "targetId", "firmwareVersionName", "EitherAsync", "apps", "mcus", "deviceVersion", "deviceId", "version", "finalFirmware", "finalFirmwareId", "osuFirmware", "livecommonversion", "currentFinalFirmwareId", "latestFirmware", "hashes", "appType", "AppTypeDto", "AppType", "app", "applicationType", "hash", "perso", "firmware", "firmwareKey", "del", "deleteKey", "rest", "mcu", "ret", "osuDto", "Nothing", "Just", "languages", "language", "__decorateClass", "injectable", "__decorateParam", "inject", "managerApiTypes"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{Left as i,Right as t}from"purify-ts";import{BTC_APP as d,BTC_APP_METADATA as n,CUSTOM_LOCK_SCREEN_APP as h,CUSTOM_LOCK_SCREEN_APP_METADATA as p,ETH_APP_METADATA as u}from"../../../api/device-action/__test-utils__/data";import{HttpFetchApiError as o}from"../../manager-api/model/Errors";import{HttpManagerApiDataSource as s}from"./HttpManagerApiDataSource";describe("HttpManagerApiDataSource",()=>{describe("getAppList",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a list of applications",async()=>{const e=[n,u];vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify(e)));const r=await a.getAppList({targetId:"targetId",firmwareVersionName:"firmwareVersionName"});expect(r).toEqual(t(e))}),it("should return an error if payload don't match the dto",async()=>{const{versionId:e,...r}=n,l=[{versionId:"invalidVersion",...r}];vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify(l)));const c=await a.getAppList({targetId:"targetId",firmwareVersionName:"firmwareVersionName"});expect(c.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const r=await a.getAppList({targetId:"targetId",firmwareVersionName:"firmwareVersionName"});expect(r).toEqual(i(new o(e)))})}),describe("getAppsByHash",()=>{describe("success cases",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("with BTC app, should return the metadata",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([n])));const e=[d.appFullHash],r=await a.getAppsByHash({hashes:e});expect(r).toEqual(t([n]))}),it("with no apps, should return an empty list",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([])));const e=[],r=await a.getAppsByHash({hashes:e});expect(r).toEqual(t([]))}),it("with BTC app and custom lock screen, should return the metadata",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([n,p])));const e=[d.appFullHash,h.appFullHash],r=await a.getAppsByHash({hashes:e});expect(r).toEqual(t([n,p]))})}),describe("error cases",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("with BTC app, should fail if payload don't match the dto",async()=>{const{versionId:e,...r}=n;vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{versionId:"invalidVersion",...r}])));const l=[d.appFullHash],c=await a.getAppsByHash({hashes:l});expect(c.isRight()).toEqual(!1)}),it("should throw an error if the request fails",async()=>{const e=new s({managerApiUrl:"http://localhost"}),r=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(r);const l=[d.appFullHash],c=await e.getAppsByHash({hashes:l});expect(c).toEqual(i(new o(r)))})})}),describe("getDeviceVersion",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a complete device version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:17,target_id:"857735172"})));const e=await a.getDeviceVersion({targetId:"targetId"});expect(e).toEqual(t({id:17}))}),it("should return an error if payload don't match dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({target_id:"857735172"})));const e=await a.getDeviceVersion({targetId:"targetId"});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const r=await a.getDeviceVersion({targetId:"targetId"});expect(r).toEqual(i(new o(e)))})}),describe("getFirmwareVersion",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a complete firmware version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:361,version:"1.6.0",perso:"perso_11",firmware:null,firmware_key:"testKey",hash:"hash",bytes:194,mcu_versions:[1,5,7]})));const e=await a.getFirmwareVersion({version:"versionName",deviceId:42});expect(e).toEqual(t({id:361,version:"1.6.0",perso:"perso_11",firmware:null,firmwareKey:"testKey",hash:"hash",bytes:194,mcuVersions:[1,5,7]}))}),it("should return an error if payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:"invalidId",version:"1.6.0",perso:"perso_11",firmware:null,firmware_key:"testKey",hash:"hash",bytes:194,mcu_versions:[1,5,7]})));const e=await a.getFirmwareVersion({version:"versionName",deviceId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const r=await a.getFirmwareVersion({version:"versionName",deviceId:42});expect(r).toEqual(i(new o(e)))})}),describe("setProvider",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://fake-url.com",provider:1})}),it("should not change the provider if the new value is the same",()=>{const e=a._provider;a.setProvider(e),expect(a._provider).toBe(e)}),it("should not change the provider if the new value is less than 1",()=>{const e=a._provider;a.setProvider(0),a.setProvider(-5),expect(a._provider).toBe(e)}),it("should update the provider if a valid and different value is provided",()=>{a.setProvider(2),expect(a._provider).toBe(2)})}),describe("getFirmwareVersionById",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a complete firmware version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:361,version:"1.6.0",perso:"perso_11",firmware:null,firmware_key:"testKey",hash:"hash",bytes:194,mcu_versions:[1,5,7]})));const e=await a.getFirmwareVersionById(42);expect(e).toEqual(t({id:361,version:"1.6.0",perso:"perso_11",firmware:null,firmwareKey:"testKey",hash:"hash",bytes:194,mcuVersions:[1,5,7]}))})}),describe("getLatestFirmwareVersion",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return the latest firmware version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({result:"success",se_firmware_osu_version:{id:361,perso:"perso_11",firmware:"test",firmware_key:"testKey",hash:"hash",next_se_firmware_final_version:567}})));const e=await a.getLatestFirmwareVersion({currentFinalFirmwareId:200,deviceId:42});expect(e).toEqual(t({id:361,perso:"perso_11",firmware:"test",firmwareKey:"testKey",hash:"hash",nextFinalFirmware:567}))}),it("should return an error if result is not success",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({result:"failed",se_firmware_osu_version:null})));const e=await a.getLatestFirmwareVersion({currentFinalFirmwareId:200,deviceId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({result:"success",se_firmware_osu_version:{id:"InvalidId",perso:"perso_11",firmware:"test",firmware_key:"testKey",hash:"hash",next_se_firmware_final_version:567}})));const e=await a.getLatestFirmwareVersion({currentFinalFirmwareId:200,deviceId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const r=await a.getLatestFirmwareVersion({currentFinalFirmwareId:200,deviceId:42});expect(r).toEqual(i(new o(e)))})}),describe("getOsuFirmwareVersion",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a complete OSU firmware version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:361,perso:"perso_11",firmware:"test",firmware_key:"testKey",hash:"hash",next_se_firmware_final_version:567})));const e=await a.getOsuFirmwareVersion({version:"versionName",deviceId:42});expect(e).toEqual(t({id:361,perso:"perso_11",firmware:"test",firmwareKey:"testKey",hash:"hash",nextFinalFirmware:567}))}),it("should return an error if payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:"invalidId",perso:"perso_11",firmware:"test",firmware_key:"testKey",hash:"hash",next_se_firmware_final_version:567})));const e=await a.getOsuFirmwareVersion({version:"versionName",deviceId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const r=await a.getOsuFirmwareVersion({version:"versionName",deviceId:42});expect(r).toEqual(i(new o(e)))})}),describe("getLanguagePackages",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return the langage packages version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{language:"turkish",languagePackageVersionId:474,version:"0.0.4",language_package_id:57,apdu_install_url:"https://download.languages.ledger.com/stax/turkish/bolos_1.6.2_pack_0.0.4_tr.apdu",apdu_uninstall_url:"https://download.languages.ledger.com/stax/turkish/bolos_1.6.2_pack_0.0.4_tr_del.apdu",device_versions:[17],se_firmware_final_versions:[432],bytes:20800,date_creation:"2025-03-04T10:48:27.910630Z",date_last_modified:"2025-03-04T10:48:27.910630Z"},{language:"russian",languagePackageVersionId:470,version:"0.0.4",language_package_id:56,apdu_install_url:"https://download.languages.ledger.com/stax/russian/bolos_1.6.2_pack_0.0.4_ru.apdu",apdu_uninstall_url:"https://download.languages.ledger.com/stax/russian/bolos_1.6.2_pack_0.0.4_ru_del.apdu",device_versions:[17],se_firmware_final_versions:[432],bytes:46592,date_creation:"2025-03-04T10:48:26.218729Z",date_last_modified:"2025-03-04T10:48:26.218729Z"}])));const e=await a.getLanguagePackages({deviceId:1,currentFinalFirmwareId:42});expect(e).toEqual(t([{language:"turkish",languagePackageVersionId:474,version:"0.0.4",languagePackageId:57,apduInstallUrl:"https://download.languages.ledger.com/stax/turkish/bolos_1.6.2_pack_0.0.4_tr.apdu",apduUninstallUrl:"https://download.languages.ledger.com/stax/turkish/bolos_1.6.2_pack_0.0.4_tr_del.apdu",bytes:20800,dateCreation:"2025-03-04T10:48:27.910630Z",dateLastModified:"2025-03-04T10:48:27.910630Z"},{language:"russian",languagePackageVersionId:470,version:"0.0.4",languagePackageId:56,apduInstallUrl:"https://download.languages.ledger.com/stax/russian/bolos_1.6.2_pack_0.0.4_ru.apdu",apduUninstallUrl:"https://download.languages.ledger.com/stax/russian/bolos_1.6.2_pack_0.0.4_ru_del.apdu",bytes:46592,dateCreation:"2025-03-04T10:48:26.218729Z",dateLastModified:"2025-03-04T10:48:26.218729Z"}]))}),it("should return an error if payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{language:"turkish",version:"0.0.4",language_package_id:"invalid"}])));const e=await a.getLanguagePackages({deviceId:1,currentFinalFirmwareId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const r=await a.getLanguagePackages({deviceId:1,currentFinalFirmwareId:42});expect(r).toEqual(i(new o(e)))})}),describe("getMcuList",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a the list of MCUs",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{id:1,mcu:1,name:"1.0",description:null,providers:[],device_versions:[1,2],from_bootloader_version:"",from_bootloader_version_id:2,se_firmware_final_versions:[7,12,13,14,15],date_creation:"2018-09-20T13:30:50.156394Z",date_last_modified:"2018-09-20T13:30:50.156453Z"},{id:2,mcu:1,name:"1.1",description:null,providers:[],device_versions:[1,2],from_bootloader_version:"",from_bootloader_version_id:2,se_firmware_final_versions:[7,12,13,14,15],date_creation:"2018-09-20T13:30:50.339966Z",date_last_modified:"2018-09-20T13:30:50.340031Z"}])));const e=await a.getMcuList();expect(e).toEqual(t([{id:1,name:"1.0"},{id:2,name:"1.1"}]))}),it("should return an error when the payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{id:"invalid id",mcu:1,name:"1.0",description:null,providers:[],se_firmware_final_versions:[7,12,13,14,15],date_creation:"2018-09-20T13:30:50.156394Z",date_last_modified:"2018-09-20T13:30:50.156453Z"}])));const e=await a.getMcuList();expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const r=await a.getMcuList();expect(r).toEqual(i(new o(e)))})}),describe("getProvider",()=>{let a;beforeEach(()=>{a=new s({managerApiUrl:"http://fake-url.com",provider:123})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return the initial provider",()=>{expect(a.getProvider()).toBe(123)}),it("should return the updated provider after setProvider is called",()=>{a.setProvider(321),expect(a.getProvider()).toBe(321)})})});
1
+ import{Just as h,Left as o,Nothing as u,Right as t}from"purify-ts";import{BTC_APP as d,BTC_APP_METADATA as n,CUSTOM_LOCK_SCREEN_APP as g,CUSTOM_LOCK_SCREEN_APP_METADATA as p,ETH_APP_METADATA as f}from"../../../api/device-action/__test-utils__/data";import{HttpFetchApiError as i}from"../../manager-api/model/Errors";import{HttpManagerApiDataSource as s}from"./HttpManagerApiDataSource";describe("HttpManagerApiDataSource",()=>{describe("getAppList",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a list of applications",async()=>{const e=[n,f];vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify(e)));const a=await r.getAppList({targetId:"targetId",firmwareVersionName:"firmwareVersionName"});expect(a).toEqual(t(e))}),it("should return an error if payload don't match the dto",async()=>{const{versionId:e,...a}=n,l=[{versionId:"invalidVersion",...a}];vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify(l)));const c=await r.getAppList({targetId:"targetId",firmwareVersionName:"firmwareVersionName"});expect(c.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const a=await r.getAppList({targetId:"targetId",firmwareVersionName:"firmwareVersionName"});expect(a).toEqual(o(new i(e)))})}),describe("getAppsByHash",()=>{describe("success cases",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("with BTC app, should return the metadata",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([n])));const e=[d.appFullHash],a=await r.getAppsByHash({hashes:e});expect(a).toEqual(t([n]))}),it("with no apps, should return an empty list",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([])));const e=[],a=await r.getAppsByHash({hashes:e});expect(a).toEqual(t([]))}),it("with BTC app and custom lock screen, should return the metadata",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([n,p])));const e=[d.appFullHash,g.appFullHash],a=await r.getAppsByHash({hashes:e});expect(a).toEqual(t([n,p]))})}),describe("error cases",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("with BTC app, should fail if payload don't match the dto",async()=>{const{versionId:e,...a}=n;vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{versionId:"invalidVersion",...a}])));const l=[d.appFullHash],c=await r.getAppsByHash({hashes:l});expect(c.isRight()).toEqual(!1)}),it("should throw an error if the request fails",async()=>{const e=new s({managerApiUrl:"http://localhost"}),a=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(a);const l=[d.appFullHash],c=await e.getAppsByHash({hashes:l});expect(c).toEqual(o(new i(a)))})})}),describe("getDeviceVersion",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a complete device version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:17,target_id:"857735172"})));const e=await r.getDeviceVersion({targetId:"targetId"});expect(e).toEqual(t({id:17}))}),it("should return an error if payload don't match dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({target_id:"857735172"})));const e=await r.getDeviceVersion({targetId:"targetId"});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const a=await r.getDeviceVersion({targetId:"targetId"});expect(a).toEqual(o(new i(e)))})}),describe("getFirmwareVersion",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a complete firmware version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:361,version:"1.6.0",perso:"perso_11",firmware:null,firmware_key:"testKey",hash:"hash",bytes:194,mcu_versions:[1,5,7]})));const e=await r.getFirmwareVersion({version:"versionName",deviceId:42});expect(e).toEqual(t({id:361,version:"1.6.0",perso:"perso_11",firmware:null,firmwareKey:"testKey",hash:"hash",bytes:194,mcuVersions:[1,5,7]}))}),it("should return an error if payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:"invalidId",version:"1.6.0",perso:"perso_11",firmware:null,firmware_key:"testKey",hash:"hash",bytes:194,mcu_versions:[1,5,7]})));const e=await r.getFirmwareVersion({version:"versionName",deviceId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const a=await r.getFirmwareVersion({version:"versionName",deviceId:42});expect(a).toEqual(o(new i(e)))})}),describe("setProvider",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://fake-url.com",provider:1})}),it("should not change the provider if the new value is the same",()=>{const e=r._provider;r.setProvider(e),expect(r._provider).toBe(e)}),it("should not change the provider if the new value is less than 1",()=>{const e=r._provider;r.setProvider(0),r.setProvider(-5),expect(r._provider).toBe(e)}),it("should update the provider if a valid and different value is provided",()=>{r.setProvider(2),expect(r._provider).toBe(2)})}),describe("getFirmwareVersionById",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a complete firmware version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:361,version:"1.6.0",perso:"perso_11",firmware:null,firmware_key:"testKey",hash:"hash",bytes:194,mcu_versions:[1,5,7]})));const e=await r.getFirmwareVersionById(42);expect(e).toEqual(t({id:361,version:"1.6.0",perso:"perso_11",firmware:null,firmwareKey:"testKey",hash:"hash",bytes:194,mcuVersions:[1,5,7]}))})}),describe("getLatestFirmwareVersion",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return the latest firmware version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({result:"success",se_firmware_osu_version:{id:361,perso:"perso_11",notes:"notes",firmware:"test",firmware_key:"testKey",hash:"hash",next_se_firmware_final_version:567}})));const e=await r.getLatestFirmwareVersion({currentFinalFirmwareId:200,deviceId:42});expect(e).toEqual(t(h({id:361,perso:"perso_11",notes:"notes",firmware:"test",firmwareKey:"testKey",hash:"hash",nextFinalFirmware:567})))}),it("should return nothing when no latest firmware version is available",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({result:"null",se_firmware_osu_version:null})));const e=await r.getLatestFirmwareVersion({currentFinalFirmwareId:200,deviceId:42});expect(e).toEqual(t(u))}),it("should return an error if result is not success",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({result:"failed",se_firmware_osu_version:null})));const e=await r.getLatestFirmwareVersion({currentFinalFirmwareId:200,deviceId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({result:"success",se_firmware_osu_version:{id:"InvalidId",perso:"perso_11",firmware:"test",firmware_key:"testKey",hash:"hash",next_se_firmware_final_version:567}})));const e=await r.getLatestFirmwareVersion({currentFinalFirmwareId:200,deviceId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const a=await r.getLatestFirmwareVersion({currentFinalFirmwareId:200,deviceId:42});expect(a).toEqual(o(new i(e)))})}),describe("getOsuFirmwareVersion",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return a complete OSU firmware version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:361,perso:"perso_11",notes:"notes",firmware:"test",firmware_key:"testKey",hash:"hash",next_se_firmware_final_version:567})));const e=await r.getOsuFirmwareVersion({version:"versionName",deviceId:42});expect(e).toEqual(t({id:361,perso:"perso_11",notes:"notes",firmware:"test",firmwareKey:"testKey",hash:"hash",nextFinalFirmware:567}))}),it("should return an error if payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify({id:"invalidId",perso:"perso_11",firmware:"test",firmware_key:"testKey",hash:"hash",next_se_firmware_final_version:567})));const e=await r.getOsuFirmwareVersion({version:"versionName",deviceId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const a=await r.getOsuFirmwareVersion({version:"versionName",deviceId:42});expect(a).toEqual(o(new i(e)))})}),describe("getLanguagePackages",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return the langage packages version",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{language:"turkish",languagePackageVersionId:474,version:"0.0.4",language_package_id:57,apdu_install_url:"https://download.languages.ledger.com/stax/turkish/bolos_1.6.2_pack_0.0.4_tr.apdu",apdu_uninstall_url:"https://download.languages.ledger.com/stax/turkish/bolos_1.6.2_pack_0.0.4_tr_del.apdu",device_versions:[17],se_firmware_final_versions:[432],bytes:20800,date_creation:"2025-03-04T10:48:27.910630Z",date_last_modified:"2025-03-04T10:48:27.910630Z"},{language:"russian",languagePackageVersionId:470,version:"0.0.4",language_package_id:56,apdu_install_url:"https://download.languages.ledger.com/stax/russian/bolos_1.6.2_pack_0.0.4_ru.apdu",apdu_uninstall_url:"https://download.languages.ledger.com/stax/russian/bolos_1.6.2_pack_0.0.4_ru_del.apdu",device_versions:[17],se_firmware_final_versions:[432],bytes:46592,date_creation:"2025-03-04T10:48:26.218729Z",date_last_modified:"2025-03-04T10:48:26.218729Z"}])));const e=await r.getLanguagePackages({deviceId:1,currentFinalFirmwareId:42});expect(e).toEqual(t([{language:"turkish",languagePackageVersionId:474,version:"0.0.4",languagePackageId:57,apduInstallUrl:"https://download.languages.ledger.com/stax/turkish/bolos_1.6.2_pack_0.0.4_tr.apdu",apduUninstallUrl:"https://download.languages.ledger.com/stax/turkish/bolos_1.6.2_pack_0.0.4_tr_del.apdu",bytes:20800,dateCreation:"2025-03-04T10:48:27.910630Z",dateLastModified:"2025-03-04T10:48:27.910630Z"},{language:"russian",languagePackageVersionId:470,version:"0.0.4",languagePackageId:56,apduInstallUrl:"https://download.languages.ledger.com/stax/russian/bolos_1.6.2_pack_0.0.4_ru.apdu",apduUninstallUrl:"https://download.languages.ledger.com/stax/russian/bolos_1.6.2_pack_0.0.4_ru_del.apdu",bytes:46592,dateCreation:"2025-03-04T10:48:26.218729Z",dateLastModified:"2025-03-04T10:48:26.218729Z"}]))}),it("should return an error if payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{language:"turkish",version:"0.0.4",language_package_id:"invalid"}])));const e=await r.getLanguagePackages({deviceId:1,currentFinalFirmwareId:42});expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const a=await r.getLanguagePackages({deviceId:1,currentFinalFirmwareId:42});expect(a).toEqual(o(new i(e)))})}),describe("getMcuList",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://localhost"})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return the list of MCUs",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{id:1,mcu:1,name:"1.0",description:null,providers:[1],device_versions:[1,2],from_bootloader_version:"1.0",from_bootloader_version_id:2,se_firmware_final_versions:[7,12,13,14,15],date_creation:"2018-09-20T13:30:50.156394Z",date_last_modified:"2018-09-20T13:30:50.156453Z"},{id:2,mcu:1,name:"1.1",description:null,providers:[1,2],device_versions:[1,2],from_bootloader_version:"1.0",from_bootloader_version_id:2,se_firmware_final_versions:[7,12,13,14,15],date_creation:"2018-09-20T13:30:50.339966Z",date_last_modified:"2018-09-20T13:30:50.340031Z"}])));const e=await r.getMcuList();expect(e).toEqual(t([{id:1,name:"1.0",fromBootloaderVersion:"1.0",providers:[1]},{id:2,name:"1.1",fromBootloaderVersion:"1.0",providers:[1,2]}]))}),it("should return an error when the payload don't match the dto",async()=>{vi.spyOn(globalThis,"fetch").mockResolvedValue(new Response(JSON.stringify([{id:"invalid id",mcu:1,name:"1.0",description:null,providers:[],se_firmware_final_versions:[7,12,13,14,15],date_creation:"2018-09-20T13:30:50.156394Z",date_last_modified:"2018-09-20T13:30:50.156453Z"}])));const e=await r.getMcuList();expect(e.isRight()).toEqual(!1)}),it("should return an error if the request fails",async()=>{const e=new Error("fetch error");vi.spyOn(globalThis,"fetch").mockRejectedValue(e);const a=await r.getMcuList();expect(a).toEqual(o(new i(e)))})}),describe("getProvider",()=>{let r;beforeEach(()=>{r=new s({managerApiUrl:"http://fake-url.com",provider:123})}),afterEach(()=>{vi.restoreAllMocks()}),it("should return the initial provider",()=>{expect(r.getProvider()).toBe(123)}),it("should return the updated provider after setProvider is called",()=>{r.setProvider(321),expect(r.getProvider()).toBe(321)})})});
2
2
  //# sourceMappingURL=HttpManagerApiDataSource.test.js.map