@ledgerhq/device-management-kit 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +63 -28
- package/lib/cjs/package.json +1 -1
- package/lib/cjs/src/api/DeviceManagementKit.js +1 -1
- package/lib/cjs/src/api/DeviceManagementKit.js.map +2 -2
- package/lib/cjs/src/api/apdu/utils/ApduBuilder.js +1 -1
- package/lib/cjs/src/api/apdu/utils/ApduBuilder.js.map +3 -3
- package/lib/cjs/src/api/command/os/GetBackgroundImageSizeCommand.js +2 -0
- package/lib/cjs/src/api/command/os/GetBackgroundImageSizeCommand.js.map +7 -0
- package/lib/cjs/src/api/command/os/GetBackgroundImageSizeCommand.test.js +2 -0
- package/lib/cjs/src/api/command/os/GetBackgroundImageSizeCommand.test.js.map +7 -0
- package/lib/cjs/src/api/device-action/DeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/DeviceAction.js.map +1 -1
- package/lib/cjs/src/api/device-action/__test-utils__/makeInternalApi.js +1 -1
- package/lib/cjs/src/api/device-action/__test-utils__/makeInternalApi.js.map +3 -3
- package/lib/cjs/src/api/device-action/__test-utils__/setupTestMachine.js +1 -1
- package/lib/cjs/src/api/device-action/__test-utils__/setupTestMachine.js.map +3 -3
- package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js +1 -1
- package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.test.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceActionTypes.js +1 -1
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceActionTypes.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.test.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceMetadata/types.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/GetDeviceStatus/types.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.test.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/GoToDashboard/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/GoToDashboard/types.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.test.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/InstallOrUpdateApps/types.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/ListApps/ListAppsDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/ListApps/ListAppsDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/ListApps/ListAppsDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/ListApps/ListAppsDeviceAction.test.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/ListApps/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/ListApps/types.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.test.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/ListAppsWithMetadata/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/ListAppsWithMetadata/types.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppDeviceAction/types.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.test.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/OpenAppWithDependencies/types.js +1 -1
- package/lib/cjs/src/api/device-action/os/OpenAppWithDependencies/types.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.test.js.map +3 -3
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.js +1 -1
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.js.map +3 -3
- package/lib/cjs/src/api/device-action/task/GetFirmwareMetadataTask.js +1 -1
- package/lib/cjs/src/api/device-action/task/GetFirmwareMetadataTask.js.map +3 -3
- package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +3 -3
- package/lib/cjs/src/api/index.js +1 -1
- package/lib/cjs/src/api/index.js.map +3 -3
- package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.js +2 -0
- package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.js.map +7 -0
- package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.test.js +2 -0
- package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.test.js.map +7 -0
- package/lib/cjs/src/api/logger-subscriber/service/WebLogsExporterLogger.test.js +1 -1
- package/lib/cjs/src/api/logger-subscriber/service/WebLogsExporterLogger.test.js.map +2 -2
- package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
- package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
- package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
- package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js.map +3 -3
- package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.test.js +1 -1
- package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.test.js.map +3 -3
- package/lib/cjs/src/api/transport/model/Errors.js +1 -1
- package/lib/cjs/src/api/transport/model/Errors.js.map +3 -3
- package/lib/cjs/src/api/types.js +1 -1
- package/lib/cjs/src/api/types.js.map +1 -1
- package/lib/cjs/src/api/utils/ApplicationChecker.js +2 -0
- package/lib/cjs/src/api/utils/ApplicationChecker.js.map +7 -0
- package/lib/cjs/src/api/utils/ApplicationChecker.test.js +2 -0
- package/lib/cjs/src/api/utils/ApplicationChecker.test.js.map +7 -0
- package/lib/cjs/src/api/utils/ApplicationResolver.js +2 -0
- package/lib/cjs/src/api/utils/ApplicationResolver.js.map +7 -0
- package/lib/cjs/src/api/utils/Base64String.js +1 -1
- package/lib/cjs/src/api/utils/Base64String.js.map +3 -3
- package/lib/cjs/src/api/utils/Base64String.test.js +1 -1
- package/lib/cjs/src/api/utils/Base64String.test.js.map +3 -3
- package/lib/cjs/src/internal/device-session/di/deviceSessionModule.js +1 -1
- package/lib/cjs/src/internal/device-session/di/deviceSessionModule.js.map +3 -3
- package/lib/cjs/src/internal/device-session/di/deviceSessionTypes.js +1 -1
- package/lib/cjs/src/internal/device-session/di/deviceSessionTypes.js.map +2 -2
- package/lib/cjs/src/internal/device-session/model/DevicePinger.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DevicePinger.js.map +2 -2
- package/lib/cjs/src/internal/device-session/model/DevicePinger.test.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DevicePinger.test.js.map +2 -2
- package/lib/cjs/src/internal/device-session/model/DeviceSession.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DeviceSession.js.map +3 -3
- package/lib/cjs/src/internal/device-session/model/DeviceSession.test.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DeviceSession.test.js.map +3 -3
- package/lib/cjs/src/internal/device-session/model/DeviceSessionEventDispatcher.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DeviceSessionEventDispatcher.js.map +2 -2
- package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.js.map +3 -3
- package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.test.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DeviceSessionRefresher.test.js.map +2 -2
- package/lib/cjs/src/internal/device-session/model/DeviceSessionStateHandler.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DeviceSessionStateHandler.js.map +3 -3
- package/lib/cjs/src/internal/device-session/model/DeviceSessionStateHandler.test.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DeviceSessionStateHandler.test.js.map +2 -2
- package/lib/cjs/src/internal/device-session/service/IntentQueueService.js +2 -0
- package/lib/cjs/src/internal/device-session/service/IntentQueueService.js.map +7 -0
- package/lib/cjs/src/internal/device-session/service/IntentQueueService.test.js +2 -0
- package/lib/cjs/src/internal/device-session/service/IntentQueueService.test.js.map +7 -0
- package/lib/cjs/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.js +2 -0
- package/lib/cjs/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.js.map +7 -0
- package/lib/cjs/src/internal/discovery/use-case/ConnectUseCase.test.js +1 -1
- package/lib/cjs/src/internal/discovery/use-case/ConnectUseCase.test.js.map +3 -3
- package/lib/cjs/src/internal/send/use-case/SendApduUseCase.test.js +1 -1
- package/lib/cjs/src/internal/send/use-case/SendApduUseCase.test.js.map +3 -3
- package/lib/esm/package.json +1 -1
- package/lib/esm/src/api/DeviceManagementKit.js +1 -1
- package/lib/esm/src/api/DeviceManagementKit.js.map +2 -2
- package/lib/esm/src/api/apdu/utils/ApduBuilder.js +1 -1
- package/lib/esm/src/api/apdu/utils/ApduBuilder.js.map +3 -3
- package/lib/esm/src/api/command/os/GetBackgroundImageSizeCommand.js +2 -0
- package/lib/esm/src/api/command/os/GetBackgroundImageSizeCommand.js.map +7 -0
- package/lib/esm/src/api/command/os/GetBackgroundImageSizeCommand.test.js +2 -0
- package/lib/esm/src/api/command/os/GetBackgroundImageSizeCommand.test.js.map +7 -0
- package/lib/esm/src/api/device-action/__test-utils__/makeInternalApi.js +1 -1
- package/lib/esm/src/api/device-action/__test-utils__/makeInternalApi.js.map +3 -3
- package/lib/esm/src/api/device-action/__test-utils__/setupTestMachine.js +1 -1
- package/lib/esm/src/api/device-action/__test-utils__/setupTestMachine.js.map +3 -3
- package/lib/esm/src/api/device-action/model/UserInteractionRequired.js +1 -1
- package/lib/esm/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceActionTypes.js +1 -0
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceActionTypes.js.map +4 -4
- package/lib/esm/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/GetDeviceMetadata/types.js +1 -0
- package/lib/esm/src/api/device-action/os/GetDeviceMetadata/types.js.map +4 -4
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/types.js +1 -0
- package/lib/esm/src/api/device-action/os/GetDeviceStatus/types.js.map +4 -4
- package/lib/esm/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/GoToDashboard/types.js +1 -0
- package/lib/esm/src/api/device-action/os/GoToDashboard/types.js.map +4 -4
- package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/types.js +1 -0
- package/lib/esm/src/api/device-action/os/InstallOrUpdateApps/types.js.map +4 -4
- package/lib/esm/src/api/device-action/os/ListApps/ListAppsDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/ListApps/ListAppsDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/ListApps/ListAppsDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/ListApps/ListAppsDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/ListApps/types.js +1 -0
- package/lib/esm/src/api/device-action/os/ListApps/types.js.map +4 -4
- package/lib/esm/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/ListAppsWithMetadata/types.js +1 -0
- package/lib/esm/src/api/device-action/os/ListAppsWithMetadata/types.js.map +4 -4
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/types.js +1 -0
- package/lib/esm/src/api/device-action/os/OpenAppDeviceAction/types.js.map +4 -4
- package/lib/esm/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/OpenAppWithDependencies/types.js +1 -0
- package/lib/esm/src/api/device-action/os/OpenAppWithDependencies/types.js.map +4 -4
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.js.map +3 -3
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.test.js.map +3 -3
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.js +1 -0
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.js.map +4 -4
- package/lib/esm/src/api/device-action/task/GetFirmwareMetadataTask.js +1 -1
- package/lib/esm/src/api/device-action/task/GetFirmwareMetadataTask.js.map +3 -3
- package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +3 -3
- package/lib/esm/src/api/index.js +1 -1
- package/lib/esm/src/api/index.js.map +3 -3
- package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.js +2 -0
- package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.js.map +7 -0
- package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.test.js +2 -0
- package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.test.js.map +7 -0
- package/lib/esm/src/api/logger-subscriber/service/WebLogsExporterLogger.test.js +1 -1
- package/lib/esm/src/api/logger-subscriber/service/WebLogsExporterLogger.test.js.map +3 -3
- package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
- package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +3 -3
- package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
- package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js.map +3 -3
- package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.test.js +1 -1
- package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.test.js.map +3 -3
- package/lib/esm/src/api/transport/model/Errors.js +1 -1
- package/lib/esm/src/api/transport/model/Errors.js.map +3 -3
- package/lib/esm/src/api/utils/ApplicationChecker.js +2 -0
- package/lib/esm/src/api/utils/ApplicationChecker.js.map +7 -0
- package/lib/esm/src/api/utils/ApplicationChecker.test.js +2 -0
- package/lib/esm/src/api/utils/ApplicationChecker.test.js.map +7 -0
- package/lib/esm/src/api/utils/ApplicationResolver.js +1 -0
- package/lib/esm/src/api/utils/ApplicationResolver.js.map +7 -0
- package/lib/esm/src/api/utils/Base64String.js +1 -1
- package/lib/esm/src/api/utils/Base64String.js.map +3 -3
- package/lib/esm/src/api/utils/Base64String.test.js +1 -1
- package/lib/esm/src/api/utils/Base64String.test.js.map +3 -3
- package/lib/esm/src/internal/device-session/di/deviceSessionModule.js +1 -1
- package/lib/esm/src/internal/device-session/di/deviceSessionModule.js.map +3 -3
- package/lib/esm/src/internal/device-session/di/deviceSessionTypes.js +1 -1
- package/lib/esm/src/internal/device-session/di/deviceSessionTypes.js.map +2 -2
- package/lib/esm/src/internal/device-session/model/DevicePinger.js +1 -1
- package/lib/esm/src/internal/device-session/model/DevicePinger.js.map +2 -2
- package/lib/esm/src/internal/device-session/model/DevicePinger.test.js +1 -1
- package/lib/esm/src/internal/device-session/model/DevicePinger.test.js.map +2 -2
- package/lib/esm/src/internal/device-session/model/DeviceSession.js +1 -1
- package/lib/esm/src/internal/device-session/model/DeviceSession.js.map +3 -3
- package/lib/esm/src/internal/device-session/model/DeviceSession.test.js +1 -1
- package/lib/esm/src/internal/device-session/model/DeviceSession.test.js.map +3 -3
- package/lib/esm/src/internal/device-session/model/DeviceSessionEventDispatcher.js +1 -1
- package/lib/esm/src/internal/device-session/model/DeviceSessionEventDispatcher.js.map +2 -2
- package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.js +1 -1
- package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.js.map +3 -3
- package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.test.js +1 -1
- package/lib/esm/src/internal/device-session/model/DeviceSessionRefresher.test.js.map +2 -2
- package/lib/esm/src/internal/device-session/model/DeviceSessionStateHandler.js +1 -1
- package/lib/esm/src/internal/device-session/model/DeviceSessionStateHandler.js.map +3 -3
- package/lib/esm/src/internal/device-session/model/DeviceSessionStateHandler.test.js +1 -1
- package/lib/esm/src/internal/device-session/model/DeviceSessionStateHandler.test.js.map +2 -2
- package/lib/esm/src/internal/device-session/service/IntentQueueService.js +2 -0
- package/lib/esm/src/internal/device-session/service/IntentQueueService.js.map +7 -0
- package/lib/esm/src/internal/device-session/service/IntentQueueService.test.js +2 -0
- package/lib/esm/src/internal/device-session/service/IntentQueueService.test.js.map +7 -0
- package/lib/esm/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.js +2 -0
- package/lib/esm/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.js.map +7 -0
- package/lib/esm/src/internal/discovery/use-case/ConnectUseCase.test.js +1 -1
- package/lib/esm/src/internal/discovery/use-case/ConnectUseCase.test.js.map +3 -3
- package/lib/esm/src/internal/send/use-case/SendApduUseCase.test.js +1 -1
- package/lib/esm/src/internal/send/use-case/SendApduUseCase.test.js.map +3 -3
- package/lib/types/src/api/DeviceManagementKit.d.ts +10 -0
- package/lib/types/src/api/DeviceManagementKit.d.ts.map +1 -1
- package/lib/types/src/api/apdu/utils/ApduBuilder.d.ts +7 -0
- package/lib/types/src/api/apdu/utils/ApduBuilder.d.ts.map +1 -1
- package/lib/types/src/api/command/os/GetBackgroundImageSizeCommand.d.ts +17 -0
- package/lib/types/src/api/command/os/GetBackgroundImageSizeCommand.d.ts.map +1 -0
- package/lib/types/src/api/command/os/GetBackgroundImageSizeCommand.test.d.ts +2 -0
- package/lib/types/src/api/command/os/GetBackgroundImageSizeCommand.test.d.ts.map +1 -0
- package/lib/types/src/api/device-action/DeviceAction.d.ts +2 -1
- package/lib/types/src/api/device-action/DeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/__test-utils__/makeInternalApi.d.ts.map +1 -1
- package/lib/types/src/api/device-action/__test-utils__/setupTestMachine.d.ts.map +1 -1
- package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts +4 -1
- package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceActionTypes.d.ts +9 -1
- package/lib/types/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceActionTypes.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GetDeviceMetadata/types.d.ts +13 -2
- package/lib/types/src/api/device-action/os/GetDeviceMetadata/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GetDeviceStatus/types.d.ts +6 -0
- package/lib/types/src/api/device-action/os/GetDeviceStatus/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.d.ts +1 -1
- package/lib/types/src/api/device-action/os/GoToDashboard/GoToDashboardDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/GoToDashboard/types.d.ts +9 -1
- package/lib/types/src/api/device-action/os/GoToDashboard/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/InstallOrUpdateApps/types.d.ts +9 -1
- package/lib/types/src/api/device-action/os/InstallOrUpdateApps/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/ListApps/ListAppsDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/ListApps/types.d.ts +6 -0
- package/lib/types/src/api/device-action/os/ListApps/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/ListAppsWithMetadata/types.d.ts +8 -1
- package/lib/types/src/api/device-action/os/ListAppsWithMetadata/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/OpenAppDeviceAction/types.d.ts +12 -2
- package/lib/types/src/api/device-action/os/OpenAppDeviceAction/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/OpenAppWithDependencies/types.d.ts +8 -0
- package/lib/types/src/api/device-action/os/OpenAppWithDependencies/types.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.d.ts +9 -1
- package/lib/types/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceActionTypes.d.ts.map +1 -1
- package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts +10 -1
- package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/index.d.ts +11 -4
- package/lib/types/src/api/index.d.ts.map +1 -1
- package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.d.ts +12 -0
- package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.d.ts.map +1 -0
- package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.test.d.ts +2 -0
- package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.test.d.ts.map +1 -0
- package/lib/types/src/api/secure-channel/task/ConnectToSecureChannelTask.d.ts.map +1 -1
- package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.d.ts +1 -0
- package/lib/types/src/api/transport/model/DeviceConnectionStateMachine.d.ts.map +1 -1
- package/lib/types/src/api/transport/model/Errors.d.ts +5 -0
- package/lib/types/src/api/transport/model/Errors.d.ts.map +1 -1
- package/lib/types/src/api/types.d.ts +1 -0
- package/lib/types/src/api/types.d.ts.map +1 -1
- package/lib/types/src/api/utils/ApplicationChecker.d.ts +14 -0
- package/lib/types/src/api/utils/ApplicationChecker.d.ts.map +1 -0
- package/lib/types/src/api/utils/ApplicationChecker.test.d.ts +2 -0
- package/lib/types/src/api/utils/ApplicationChecker.test.d.ts.map +1 -0
- package/lib/types/src/api/utils/ApplicationResolver.d.ts +12 -0
- package/lib/types/src/api/utils/ApplicationResolver.d.ts.map +1 -0
- package/lib/types/src/api/utils/Base64String.d.ts +1 -0
- package/lib/types/src/api/utils/Base64String.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/di/deviceSessionModule.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/di/deviceSessionTypes.d.ts +1 -0
- package/lib/types/src/internal/device-session/di/deviceSessionTypes.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/model/DeviceSession.d.ts +13 -2
- package/lib/types/src/internal/device-session/model/DeviceSession.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/model/DeviceSessionEventDispatcher.d.ts +3 -1
- package/lib/types/src/internal/device-session/model/DeviceSessionEventDispatcher.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/model/DeviceSessionRefresher.d.ts +0 -1
- package/lib/types/src/internal/device-session/model/DeviceSessionRefresher.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/model/DeviceSessionStateHandler.d.ts +1 -0
- package/lib/types/src/internal/device-session/model/DeviceSessionStateHandler.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/service/IntentQueueService.d.ts +101 -0
- package/lib/types/src/internal/device-session/service/IntentQueueService.d.ts.map +1 -0
- package/lib/types/src/internal/device-session/service/IntentQueueService.test.d.ts +2 -0
- package/lib/types/src/internal/device-session/service/IntentQueueService.test.d.ts.map +1 -0
- package/lib/types/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.d.ts +19 -0
- package/lib/types/src/internal/device-session/use-case/UnsafeBypassIntentQueueUseCase.d.ts.map +1 -0
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +4 -4
- package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.js +0 -2
- package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.js.map +0 -7
- package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.test.js +0 -2
- package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.test.js.map +0 -7
- package/lib/cjs/src/internal/device-session/service/MutexService.js +0 -2
- package/lib/cjs/src/internal/device-session/service/MutexService.js.map +0 -7
- package/lib/cjs/src/internal/device-session/service/MutexService.test.js +0 -2
- package/lib/cjs/src/internal/device-session/service/MutexService.test.js.map +0 -7
- package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.js +0 -2
- package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.js.map +0 -7
- package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.test.js +0 -2
- package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.test.js.map +0 -7
- package/lib/esm/src/internal/device-session/service/MutexService.js +0 -2
- package/lib/esm/src/internal/device-session/service/MutexService.js.map +0 -7
- package/lib/esm/src/internal/device-session/service/MutexService.test.js +0 -2
- package/lib/esm/src/internal/device-session/service/MutexService.test.js.map +0 -7
- package/lib/types/src/api/command/os/GetCustomImageSizeCommand.d.ts +0 -17
- package/lib/types/src/api/command/os/GetCustomImageSizeCommand.d.ts.map +0 -1
- package/lib/types/src/api/command/os/GetCustomImageSizeCommand.test.d.ts +0 -2
- package/lib/types/src/api/command/os/GetCustomImageSizeCommand.test.d.ts.map +0 -1
- package/lib/types/src/internal/device-session/service/MutexService.d.ts +0 -6
- package/lib/types/src/internal/device-session/service/MutexService.d.ts.map +0 -1
- package/lib/types/src/internal/device-session/service/MutexService.test.d.ts +0 -2
- package/lib/types/src/internal/device-session/service/MutexService.test.d.ts.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService"),GetDeviceSessionStateUseCase:Symbol.for("GetDeviceSessionStateUseCase"),DisableDeviceSessionRefresherUseCase:Symbol.for("DisableDeviceSessionRefresherUseCase"),CloseSessionsUseCase:Symbol.for("CloseSessionsUseCase")};export{e as deviceSessionTypes};
|
|
1
|
+
const e={ApduSenderServiceFactory:Symbol.for("ApduSenderServiceFactory"),ApduReceiverServiceFactory:Symbol.for("ApduReceiverServiceFactory"),DeviceSessionService:Symbol.for("DeviceSessionService"),GetDeviceSessionStateUseCase:Symbol.for("GetDeviceSessionStateUseCase"),DisableDeviceSessionRefresherUseCase:Symbol.for("DisableDeviceSessionRefresherUseCase"),CloseSessionsUseCase:Symbol.for("CloseSessionsUseCase"),UnsafeBypassIntentQueueUseCase:Symbol.for("UnsafeBypassIntentQueueUseCase")};export{e as deviceSessionTypes};
|
|
2
2
|
//# sourceMappingURL=deviceSessionTypes.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/di/deviceSessionTypes.ts"],
|
|
4
|
-
"sourcesContent": ["export const deviceSessionTypes = {\n ApduSenderServiceFactory: Symbol.for(\"ApduSenderServiceFactory\"),\n ApduReceiverServiceFactory: Symbol.for(\"ApduReceiverServiceFactory\"),\n DeviceSessionService: Symbol.for(\"DeviceSessionService\"),\n GetDeviceSessionStateUseCase: Symbol.for(\"GetDeviceSessionStateUseCase\"),\n DisableDeviceSessionRefresherUseCase: Symbol.for(\n \"DisableDeviceSessionRefresherUseCase\",\n ),\n CloseSessionsUseCase: Symbol.for(\"CloseSessionsUseCase\"),\n};\n"],
|
|
5
|
-
"mappings": "AAAO,MAAMA,EAAqB,CAChC,yBAA0B,OAAO,IAAI,0BAA0B,EAC/D,2BAA4B,OAAO,IAAI,4BAA4B,EACnE,qBAAsB,OAAO,IAAI,sBAAsB,EACvD,6BAA8B,OAAO,IAAI,8BAA8B,EACvE,qCAAsC,OAAO,IAC3C,sCACF,EACA,qBAAsB,OAAO,IAAI,sBAAsB,
|
|
4
|
+
"sourcesContent": ["export const deviceSessionTypes = {\n ApduSenderServiceFactory: Symbol.for(\"ApduSenderServiceFactory\"),\n ApduReceiverServiceFactory: Symbol.for(\"ApduReceiverServiceFactory\"),\n DeviceSessionService: Symbol.for(\"DeviceSessionService\"),\n GetDeviceSessionStateUseCase: Symbol.for(\"GetDeviceSessionStateUseCase\"),\n DisableDeviceSessionRefresherUseCase: Symbol.for(\n \"DisableDeviceSessionRefresherUseCase\",\n ),\n CloseSessionsUseCase: Symbol.for(\"CloseSessionsUseCase\"),\n UnsafeBypassIntentQueueUseCase: Symbol.for(\"UnsafeBypassIntentQueueUseCase\"),\n};\n"],
|
|
5
|
+
"mappings": "AAAO,MAAMA,EAAqB,CAChC,yBAA0B,OAAO,IAAI,0BAA0B,EAC/D,2BAA4B,OAAO,IAAI,4BAA4B,EACnE,qBAAsB,OAAO,IAAI,sBAAsB,EACvD,6BAA8B,OAAO,IAAI,8BAA8B,EACvE,qCAAsC,OAAO,IAC3C,sCACF,EACA,qBAAsB,OAAO,IAAI,sBAAsB,EACvD,+BAAgC,OAAO,IAAI,gCAAgC,CAC7E",
|
|
6
6
|
"names": ["deviceSessionTypes"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{DeviceModelId as c}from"../../../api/device/DeviceModel";import{GetAppAndVersionCommand as a,GetOsVersionCommand as m}from"../../../api/index";import{PINGER_TIMEOUT as o}from"../../device-session/data/ApduResponseConst";import{DEVICE_SESSION_REFRESHER_POLLING_INTERVAL as p}from"../../device-session/data/DeviceSessionRefresherConst";import{SessionEvents as i}from"../../device-session/model/DeviceSessionEventDispatcher";class D{constructor(e,t,r,n){this.connectedDevice=t;this._sessionEventDispatcher=r;this._sendCommandFunction=n,this._logger=e("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async s=>await this.mapEventAction(s))}_sendCommandFunction;_subscription;_logger;async ping(){try{return await this.mapDevicePingAction(this.connectedDevice.deviceModel.id)}catch(e){
|
|
1
|
+
import{DeviceModelId as c}from"../../../api/device/DeviceModel";import{GetAppAndVersionCommand as a,GetOsVersionCommand as m}from"../../../api/index";import{PINGER_TIMEOUT as o}from"../../device-session/data/ApduResponseConst";import{DEVICE_SESSION_REFRESHER_POLLING_INTERVAL as p}from"../../device-session/data/DeviceSessionRefresherConst";import{SessionEvents as i}from"../../device-session/model/DeviceSessionEventDispatcher";class D{constructor(e,t,r,n){this.connectedDevice=t;this._sessionEventDispatcher=r;this._sendCommandFunction=n,this._logger=e("device-pinger"),this._subscription=this._sessionEventDispatcher.listen().subscribe(async s=>await this.mapEventAction(s))}_sendCommandFunction;_subscription;_logger;async ping(){try{return await this.mapDevicePingAction(this.connectedDevice.deviceModel.id)}catch(e){return this._logger.error("Error while pinging device",{data:{error:e}}),null}}mapEventAction=async e=>{switch(e.eventName){case i.REFRESH_NEEDED:return await this.ping();default:return null}};async mapDevicePingAction(e){switch(e){case c.NANO_S:{const t=async()=>{const s=await this._sendCommandFunction(new a,o);return this._sendCommandFunction(new m,o),s},r=new Promise(s=>{setTimeout(()=>s(null),p*2+100)}),n=await Promise.race([t(),r]);return n?this._sessionEventDispatcher.dispatch({eventName:i.COMMAND_SUCCEEDED,eventData:n}):this._sessionEventDispatcher.dispatch({eventName:i.DEVICE_STATE_UPDATE_LOCKED}),n}default:{const t=await this._sendCommandFunction(new a,o);return this._sessionEventDispatcher.dispatch({eventName:i.COMMAND_SUCCEEDED,eventData:t}),t}}}unsubscribe(){this._subscription.unsubscribe()}}export{D as DevicePinger};
|
|
2
2
|
//# sourceMappingURL=DevicePinger.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/model/DevicePinger.ts"],
|
|
4
|
-
"sourcesContent": ["import { type Subscription } from \"rxjs\";\n\nimport { DeviceModelId } from \"@api/device/DeviceModel\";\nimport {\n GetAppAndVersionCommand,\n type GetAppAndVersionResponse,\n GetOsVersionCommand,\n type TransportConnectedDevice,\n} from \"@api/index\";\nimport {\n type Command,\n type CommandResult,\n type LoggerPublisherService,\n} from \"@api/types\";\nimport { PINGER_TIMEOUT } from \"@internal/device-session/data/ApduResponseConst\";\nimport { DEVICE_SESSION_REFRESHER_POLLING_INTERVAL } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport {\n type DeviceSessionEventDispatcher,\n type NewEvent,\n SessionEvents,\n} from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\n\ntype SendCommandFunction = <Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n) => Promise<CommandResult<Response, ErrorStatusCodes>>;\n\nexport class DevicePinger {\n private readonly _sendCommandFunction: SendCommandFunction;\n private _subscription: Subscription;\n private _logger: LoggerPublisherService;\n\n constructor(\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n private connectedDevice: TransportConnectedDevice,\n private _sessionEventDispatcher: DeviceSessionEventDispatcher,\n sendCommandFunction: SendCommandFunction,\n ) {\n this._sendCommandFunction = sendCommandFunction;\n this._logger = loggerModuleFactory(\"device-pinger\");\n this._subscription = this._sessionEventDispatcher\n .listen()\n .subscribe(async (event) => await this.mapEventAction(event));\n }\n\n public async ping(): Promise<CommandResult<GetAppAndVersionResponse> | null> {\n try {\n const result = await this.mapDevicePingAction(\n this.connectedDevice.deviceModel.id,\n );\n return result;\n } catch (error) {\n this._logger.error(\"Error while pinging device\", {\n data: {\n error,\n },\n });\n
|
|
5
|
-
"mappings": "AAEA,OAAS,iBAAAA,MAAqB,0BAC9B,OACE,2BAAAC,EAEA,uBAAAC,MAEK,aAMP,OAAS,kBAAAC,MAAsB,kDAC/B,OAAS,6CAAAC,MAAiD,4DAC1D,OAGE,iBAAAC,MACK,8DAOA,MAAMC,CAAa,CAKxB,YACEC,EACQC,EACAC,EACRC,EACA,CAHQ,qBAAAF,EACA,6BAAAC,EAGR,KAAK,qBAAuBC,EAC5B,KAAK,QAAUH,EAAoB,eAAe,EAClD,KAAK,cAAgB,KAAK,wBACvB,OAAO,EACP,UAAU,MAAOI,GAAU,MAAM,KAAK,eAAeA,CAAK,CAAC,CAChE,CAfiB,qBACT,cACA,QAeR,MAAa,MAAgE,CAC3E,GAAI,CAIF,OAHe,MAAM,KAAK,oBACxB,KAAK,gBAAgB,YAAY,EACnC,CAEF,OAASC,EAAO,CACd,
|
|
4
|
+
"sourcesContent": ["import { type Subscription } from \"rxjs\";\n\nimport { DeviceModelId } from \"@api/device/DeviceModel\";\nimport {\n GetAppAndVersionCommand,\n type GetAppAndVersionResponse,\n GetOsVersionCommand,\n type TransportConnectedDevice,\n} from \"@api/index\";\nimport {\n type Command,\n type CommandResult,\n type LoggerPublisherService,\n} from \"@api/types\";\nimport { PINGER_TIMEOUT } from \"@internal/device-session/data/ApduResponseConst\";\nimport { DEVICE_SESSION_REFRESHER_POLLING_INTERVAL } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport {\n type DeviceSessionEventDispatcher,\n type NewEvent,\n SessionEvents,\n} from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\n\ntype SendCommandFunction = <Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n) => Promise<CommandResult<Response, ErrorStatusCodes>>;\n\nexport class DevicePinger {\n private readonly _sendCommandFunction: SendCommandFunction;\n private _subscription: Subscription;\n private _logger: LoggerPublisherService;\n\n constructor(\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n private connectedDevice: TransportConnectedDevice,\n private _sessionEventDispatcher: DeviceSessionEventDispatcher,\n sendCommandFunction: SendCommandFunction,\n ) {\n this._sendCommandFunction = sendCommandFunction;\n this._logger = loggerModuleFactory(\"device-pinger\");\n this._subscription = this._sessionEventDispatcher\n .listen()\n .subscribe(async (event) => await this.mapEventAction(event));\n }\n\n public async ping(): Promise<CommandResult<GetAppAndVersionResponse> | null> {\n try {\n const result = await this.mapDevicePingAction(\n this.connectedDevice.deviceModel.id,\n );\n return result;\n } catch (error) {\n this._logger.error(\"Error while pinging device\", {\n data: {\n error,\n },\n });\n return null;\n }\n }\n\n private mapEventAction = async (event: NewEvent) => {\n switch (event.eventName) {\n case SessionEvents.REFRESH_NEEDED:\n return await this.ping();\n default:\n return null;\n }\n };\n\n private async mapDevicePingAction(deviceModelId: DeviceModelId) {\n switch (deviceModelId) {\n case DeviceModelId.NANO_S: {\n const chainPromise: () => Promise<\n CommandResult<GetAppAndVersionResponse>\n > = async () => {\n const appVersionResult = await this._sendCommandFunction(\n new GetAppAndVersionCommand(),\n PINGER_TIMEOUT,\n );\n\n this._sendCommandFunction(new GetOsVersionCommand(), PINGER_TIMEOUT);\n return appVersionResult;\n };\n\n const timeoutPromise: Promise<null> = new Promise((resolve) => {\n setTimeout(\n () => resolve(null),\n DEVICE_SESSION_REFRESHER_POLLING_INTERVAL * 2 + 100,\n );\n });\n\n const resultOrTimeout: CommandResult<GetAppAndVersionResponse> | null =\n await Promise.race([chainPromise(), timeoutPromise]);\n\n if (!resultOrTimeout) {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_LOCKED,\n });\n } else {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.COMMAND_SUCCEEDED,\n eventData: resultOrTimeout,\n });\n }\n return resultOrTimeout;\n }\n default: {\n const result = await this._sendCommandFunction(\n new GetAppAndVersionCommand(),\n PINGER_TIMEOUT,\n );\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.COMMAND_SUCCEEDED,\n eventData: result,\n });\n return result;\n }\n }\n }\n\n public unsubscribe(): void {\n this._subscription.unsubscribe();\n }\n}\n"],
|
|
5
|
+
"mappings": "AAEA,OAAS,iBAAAA,MAAqB,0BAC9B,OACE,2BAAAC,EAEA,uBAAAC,MAEK,aAMP,OAAS,kBAAAC,MAAsB,kDAC/B,OAAS,6CAAAC,MAAiD,4DAC1D,OAGE,iBAAAC,MACK,8DAOA,MAAMC,CAAa,CAKxB,YACEC,EACQC,EACAC,EACRC,EACA,CAHQ,qBAAAF,EACA,6BAAAC,EAGR,KAAK,qBAAuBC,EAC5B,KAAK,QAAUH,EAAoB,eAAe,EAClD,KAAK,cAAgB,KAAK,wBACvB,OAAO,EACP,UAAU,MAAOI,GAAU,MAAM,KAAK,eAAeA,CAAK,CAAC,CAChE,CAfiB,qBACT,cACA,QAeR,MAAa,MAAgE,CAC3E,GAAI,CAIF,OAHe,MAAM,KAAK,oBACxB,KAAK,gBAAgB,YAAY,EACnC,CAEF,OAASC,EAAO,CACd,YAAK,QAAQ,MAAM,6BAA8B,CAC/C,KAAM,CACJ,MAAAA,CACF,CACF,CAAC,EACM,IACT,CACF,CAEQ,eAAiB,MAAOD,GAAoB,CAClD,OAAQA,EAAM,UAAW,CACvB,KAAKN,EAAc,eACjB,OAAO,MAAM,KAAK,KAAK,EACzB,QACE,OAAO,IACX,CACF,EAEA,MAAc,oBAAoBQ,EAA8B,CAC9D,OAAQA,EAAe,CACrB,KAAKb,EAAc,OAAQ,CACzB,MAAMc,EAEF,SAAY,CACd,MAAMC,EAAmB,MAAM,KAAK,qBAClC,IAAId,EACJE,CACF,EAEA,YAAK,qBAAqB,IAAID,EAAuBC,CAAc,EAC5DY,CACT,EAEMC,EAAgC,IAAI,QAASC,GAAY,CAC7D,WACE,IAAMA,EAAQ,IAAI,EAClBb,EAA4C,EAAI,GAClD,CACF,CAAC,EAEKc,EACJ,MAAM,QAAQ,KAAK,CAACJ,EAAa,EAAGE,CAAc,CAAC,EAErD,OAAKE,EAKH,KAAK,wBAAwB,SAAS,CACpC,UAAWb,EAAc,kBACzB,UAAWa,CACb,CAAC,EAPD,KAAK,wBAAwB,SAAS,CACpC,UAAWb,EAAc,0BAC3B,CAAC,EAOIa,CACT,CACA,QAAS,CACP,MAAMC,EAAS,MAAM,KAAK,qBACxB,IAAIlB,EACJE,CACF,EACA,YAAK,wBAAwB,SAAS,CACpC,UAAWE,EAAc,kBACzB,UAAWc,CACb,CAAC,EACMA,CACT,CACF,CACF,CAEO,aAAoB,CACzB,KAAK,cAAc,YAAY,CACjC,CACF",
|
|
6
6
|
"names": ["DeviceModelId", "GetAppAndVersionCommand", "GetOsVersionCommand", "PINGER_TIMEOUT", "DEVICE_SESSION_REFRESHER_POLLING_INTERVAL", "SessionEvents", "DevicePinger", "loggerModuleFactory", "connectedDevice", "_sessionEventDispatcher", "sendCommandFunction", "event", "error", "deviceModelId", "chainPromise", "appVersionResult", "timeoutPromise", "resolve", "resultOrTimeout", "result"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Subject as D}from"rxjs";import{afterEach as f,beforeEach as C,describe as N,expect as n,it as r,vi as t}from"vitest";import{DeviceModelId as E}from"../../../api/device/DeviceModel";import{GetAppAndVersionCommand as S}from"../../../api/index";import{DEVICE_SESSION_REFRESHER_POLLING_INTERVAL as
|
|
1
|
+
import{Subject as D}from"rxjs";import{afterEach as f,beforeEach as C,describe as N,expect as n,it as r,vi as t}from"vitest";import{DeviceModelId as E}from"../../../api/device/DeviceModel";import{GetAppAndVersionCommand as S}from"../../../api/index";import{DEVICE_SESSION_REFRESHER_POLLING_INTERVAL as y}from"../../device-session/data/DeviceSessionRefresherConst";import{SessionEvents as i}from"../../device-session/model/DeviceSessionEventDispatcher";import{DevicePinger as p}from"./DevicePinger";N("DevicePinger",()=>{let e,u;const v=t.fn(()=>u);let c,a,l,s;C(()=>{c=new D,a={listen:()=>c.asObservable(),dispatch:t.fn()},e=t.fn(),u={info:t.fn(),warn:t.fn(),error:t.fn(),debug:t.fn(),subscribers:[]},l={deviceModel:{id:E.NANO_X}},s=new p(v,l,a,e)}),f(()=>{s.unsubscribe(),t.restoreAllMocks()}),r("should call sendCommandFunction and dispatch COMMAND_SUCCEEDED event on successful ping for non-NANO_S",async()=>{const o={status:"success",data:{foo:"bar"}};e.mockResolvedValue(o);const d=await s.ping();n(e).toHaveBeenCalledTimes(1);const m=e.mock.calls[0][0];n(m).toBeInstanceOf(S),n(a.dispatch).toHaveBeenCalledWith({eventName:i.COMMAND_SUCCEEDED,eventData:o}),n(d).toEqual(o)}),r("should log error and throw error on ping failure",async()=>{const o=new Error("ping failed");e.mockRejectedValue(o),n(await s.ping()).toBeNull(),n(e).toHaveBeenCalledTimes(1)}),r("should dispatch DEVICE_STATE_UPDATE_LOCKED and return null on timeout for NANO_S",async()=>{l.deviceModel.id=E.NANO_S,s.unsubscribe(),s=new p(v,l,a,e);const o=new Promise(()=>{});e.mockReturnValueOnce(o),t.useFakeTimers();const d=s.ping();t.advanceTimersByTime(y*4);const m=await d;n(m).toBeNull(),n(a.dispatch).toHaveBeenCalledWith({eventName:i.DEVICE_STATE_UPDATE_LOCKED}),n(e).toHaveBeenCalledTimes(1),t.useRealTimers()}),r("should call ping on REFRESH_NEEDED event",async()=>{const o={status:"success",data:{foo:"bar"}};e.mockResolvedValue(o),c.next({eventName:i.REFRESH_NEEDED,eventData:void 0}),await Promise.resolve(),n(e).toHaveBeenCalled(),n(a.dispatch).toHaveBeenCalledWith({eventName:i.COMMAND_SUCCEEDED,eventData:o})}),r("should not process events after unsubscribe is called",async()=>{s.unsubscribe(),e.mockClear(),c.next({eventName:i.REFRESH_NEEDED,eventData:void 0}),await Promise.resolve(),n(e).not.toHaveBeenCalled()})});
|
|
2
2
|
//# sourceMappingURL=DevicePinger.test.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/model/DevicePinger.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 {\n GetAppAndVersionCommand,\n type TransportConnectedDevice,\n} from \"@api/index\";\nimport type { LoggerPublisherService } from \"@api/types\";\nimport { DEVICE_SESSION_REFRESHER_POLLING_INTERVAL } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport {\n type DeviceSessionEventDispatcher,\n type NewEvent,\n SessionEvents,\n} from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\n\nimport { DevicePinger } from \"./DevicePinger\";\n\ndescribe(\"DevicePinger\", () => {\n let dummySendCommandFunction: ReturnType<typeof vi.fn>;\n let mockLogger: LoggerPublisherService & {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n };\n const mockedLoggerModuleFactory = vi.fn(() => mockLogger);\n let eventSubject: Subject<NewEvent>;\n let mockSessionEventDispatcher: DeviceSessionEventDispatcher;\n let dummyConnectedDevice: TransportConnectedDevice;\n let devicePinger: DevicePinger;\n\n beforeEach(() => {\n eventSubject = new Subject<NewEvent>();\n mockSessionEventDispatcher = {\n listen: () => eventSubject.asObservable(),\n dispatch: vi.fn(),\n } as unknown as DeviceSessionEventDispatcher;\n\n dummySendCommandFunction = vi.fn();\n mockLogger = {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n debug: vi.fn(),\n subscribers: [],\n };\n\n dummyConnectedDevice = {\n deviceModel: {\n id: DeviceModelId.NANO_X,\n },\n } as unknown as TransportConnectedDevice;\n\n devicePinger = new DevicePinger(\n mockedLoggerModuleFactory,\n dummyConnectedDevice,\n mockSessionEventDispatcher,\n dummySendCommandFunction,\n );\n });\n\n afterEach(() => {\n devicePinger.unsubscribe();\n vi.restoreAllMocks();\n });\n\n it(\"should call sendCommandFunction and dispatch COMMAND_SUCCEEDED event on successful ping for non-NANO_S\", async () => {\n // given\n const dummyResult = {\n status: \"success\",\n data: { foo: \"bar\" },\n };\n dummySendCommandFunction.mockResolvedValue(dummyResult);\n\n // when\n const result = await devicePinger.ping();\n\n // then\n expect(dummySendCommandFunction).toHaveBeenCalledTimes(1);\n const commandArg = dummySendCommandFunction.mock\n .calls[0]![0] as GetAppAndVersionCommand;\n expect(commandArg).toBeInstanceOf(GetAppAndVersionCommand);\n expect(mockSessionEventDispatcher.dispatch).toHaveBeenCalledWith({\n eventName: SessionEvents.COMMAND_SUCCEEDED,\n eventData: dummyResult,\n });\n expect(result).toEqual(dummyResult);\n });\n\n it(\"should log error and throw error on ping failure\", async () => {\n // given\n const dummyError = new Error(\"ping failed\");\n dummySendCommandFunction.mockRejectedValue(dummyError);\n\n // then\n await
|
|
5
|
-
"mappings": "AAAA,OAAS,WAAAA,MAAe,OACxB,OAAS,aAAAC,EAAW,cAAAC,EAAY,YAAAC,EAAU,UAAAC,EAAQ,MAAAC,EAAI,MAAAC,MAAU,SAEhE,OAAS,iBAAAC,MAAqB,0BAC9B,OACE,2BAAAC,MA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,CAAU,
|
|
4
|
+
"sourcesContent": ["import { Subject } from \"rxjs\";\nimport { afterEach, beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { DeviceModelId } from \"@api/device/DeviceModel\";\nimport {\n GetAppAndVersionCommand,\n type TransportConnectedDevice,\n} from \"@api/index\";\nimport type { LoggerPublisherService } from \"@api/types\";\nimport { DEVICE_SESSION_REFRESHER_POLLING_INTERVAL } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport {\n type DeviceSessionEventDispatcher,\n type NewEvent,\n SessionEvents,\n} from \"@internal/device-session/model/DeviceSessionEventDispatcher\";\n\nimport { DevicePinger } from \"./DevicePinger\";\n\ndescribe(\"DevicePinger\", () => {\n let dummySendCommandFunction: ReturnType<typeof vi.fn>;\n let mockLogger: LoggerPublisherService & {\n info: ReturnType<typeof vi.fn>;\n warn: ReturnType<typeof vi.fn>;\n error: ReturnType<typeof vi.fn>;\n };\n const mockedLoggerModuleFactory = vi.fn(() => mockLogger);\n let eventSubject: Subject<NewEvent>;\n let mockSessionEventDispatcher: DeviceSessionEventDispatcher;\n let dummyConnectedDevice: TransportConnectedDevice;\n let devicePinger: DevicePinger;\n\n beforeEach(() => {\n eventSubject = new Subject<NewEvent>();\n mockSessionEventDispatcher = {\n listen: () => eventSubject.asObservable(),\n dispatch: vi.fn(),\n } as unknown as DeviceSessionEventDispatcher;\n\n dummySendCommandFunction = vi.fn();\n mockLogger = {\n info: vi.fn(),\n warn: vi.fn(),\n error: vi.fn(),\n debug: vi.fn(),\n subscribers: [],\n };\n\n dummyConnectedDevice = {\n deviceModel: {\n id: DeviceModelId.NANO_X,\n },\n } as unknown as TransportConnectedDevice;\n\n devicePinger = new DevicePinger(\n mockedLoggerModuleFactory,\n dummyConnectedDevice,\n mockSessionEventDispatcher,\n dummySendCommandFunction,\n );\n });\n\n afterEach(() => {\n devicePinger.unsubscribe();\n vi.restoreAllMocks();\n });\n\n it(\"should call sendCommandFunction and dispatch COMMAND_SUCCEEDED event on successful ping for non-NANO_S\", async () => {\n // given\n const dummyResult = {\n status: \"success\",\n data: { foo: \"bar\" },\n };\n dummySendCommandFunction.mockResolvedValue(dummyResult);\n\n // when\n const result = await devicePinger.ping();\n\n // then\n expect(dummySendCommandFunction).toHaveBeenCalledTimes(1);\n const commandArg = dummySendCommandFunction.mock\n .calls[0]![0] as GetAppAndVersionCommand;\n expect(commandArg).toBeInstanceOf(GetAppAndVersionCommand);\n expect(mockSessionEventDispatcher.dispatch).toHaveBeenCalledWith({\n eventName: SessionEvents.COMMAND_SUCCEEDED,\n eventData: dummyResult,\n });\n expect(result).toEqual(dummyResult);\n });\n\n it(\"should log error and throw error on ping failure\", async () => {\n // given\n const dummyError = new Error(\"ping failed\");\n dummySendCommandFunction.mockRejectedValue(dummyError);\n\n // then\n expect(await devicePinger.ping()).toBeNull();\n expect(dummySendCommandFunction).toHaveBeenCalledTimes(1);\n });\n\n it(\"should dispatch DEVICE_STATE_UPDATE_LOCKED and return null on timeout for NANO_S\", async () => {\n // given\n dummyConnectedDevice.deviceModel.id = DeviceModelId.NANO_S;\n devicePinger.unsubscribe();\n devicePinger = new DevicePinger(\n mockedLoggerModuleFactory,\n dummyConnectedDevice,\n mockSessionEventDispatcher,\n dummySendCommandFunction,\n );\n const neverResolvingPromise = new Promise(() => {});\n dummySendCommandFunction.mockReturnValueOnce(neverResolvingPromise);\n vi.useFakeTimers();\n\n // when\n const pingPromise = devicePinger.ping();\n vi.advanceTimersByTime(DEVICE_SESSION_REFRESHER_POLLING_INTERVAL * 4);\n\n const result = await pingPromise;\n\n // then\n expect(result).toBeNull();\n expect(mockSessionEventDispatcher.dispatch).toHaveBeenCalledWith({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_LOCKED,\n });\n expect(dummySendCommandFunction).toHaveBeenCalledTimes(1);\n\n vi.useRealTimers();\n });\n\n it(\"should call ping on REFRESH_NEEDED event\", async () => {\n // given\n const dummyResult = {\n status: \"success\",\n data: { foo: \"bar\" },\n };\n dummySendCommandFunction.mockResolvedValue(dummyResult);\n\n // when\n eventSubject.next({\n eventName: SessionEvents.REFRESH_NEEDED,\n eventData: undefined,\n });\n await Promise.resolve();\n\n // then\n expect(dummySendCommandFunction).toHaveBeenCalled();\n expect(mockSessionEventDispatcher.dispatch).toHaveBeenCalledWith({\n eventName: SessionEvents.COMMAND_SUCCEEDED,\n eventData: dummyResult,\n });\n });\n\n it(\"should not process events after unsubscribe is called\", async () => {\n // given\n devicePinger.unsubscribe();\n dummySendCommandFunction.mockClear();\n\n // when\n eventSubject.next({\n eventName: SessionEvents.REFRESH_NEEDED,\n eventData: undefined,\n });\n await Promise.resolve();\n\n // then\n expect(dummySendCommandFunction).not.toHaveBeenCalled();\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,0BAC9B,OACE,2BAAAC,MAEK,aAEP,OAAS,6CAAAC,MAAiD,4DAC1D,OAGE,iBAAAC,MACK,8DAEP,OAAS,gBAAAC,MAAoB,iBAE7BR,EAAS,eAAgB,IAAM,CAC7B,IAAIS,EACAC,EAKJ,MAAMC,EAA4BR,EAAG,GAAG,IAAMO,CAAU,EACxD,IAAIE,EACAC,EACAC,EACAC,EAEJhB,EAAW,IAAM,CACfa,EAAe,IAAIf,EACnBgB,EAA6B,CAC3B,OAAQ,IAAMD,EAAa,aAAa,EACxC,SAAUT,EAAG,GAAG,CAClB,EAEAM,EAA2BN,EAAG,GAAG,EACjCO,EAAa,CACX,KAAMP,EAAG,GAAG,EACZ,KAAMA,EAAG,GAAG,EACZ,MAAOA,EAAG,GAAG,EACb,MAAOA,EAAG,GAAG,EACb,YAAa,CAAC,CAChB,EAEAW,EAAuB,CACrB,YAAa,CACX,GAAIV,EAAc,MACpB,CACF,EAEAW,EAAe,IAAIP,EACjBG,EACAG,EACA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EAAE,sBAAsB,CAAC,EAExDN,EAAG,cAAc,CACnB,CAAC,EAEDD,EAAG,2CAA4C,SAAY,CAEzD,MAAMc,EAAc,CAClB,OAAQ,UACR,KAAM,CAAE,IAAK,KAAM,CACrB,EACAP,EAAyB,kBAAkBO,CAAW,EAGtDJ,EAAa,KAAK,CAChB,UAAWL,EAAc,eACzB,UAAW,MACb,CAAC,EACD,MAAM,QAAQ,QAAQ,EAGtBN,EAAOQ,CAAwB,EAAE,iBAAiB,EAClDR,EAAOY,EAA2B,QAAQ,EAAE,qBAAqB,CAC/D,UAAWN,EAAc,kBACzB,UAAWS,CACb,CAAC,CACH,CAAC,EAEDd,EAAG,wDAAyD,SAAY,CAEtEa,EAAa,YAAY,EACzBN,EAAyB,UAAU,EAGnCG,EAAa,KAAK,CAChB,UAAWL,EAAc,eACzB,UAAW,MACb,CAAC,EACD,MAAM,QAAQ,QAAQ,EAGtBN,EAAOQ,CAAwB,EAAE,IAAI,iBAAiB,CACxD,CAAC,CACH,CAAC",
|
|
6
6
|
"names": ["Subject", "afterEach", "beforeEach", "describe", "expect", "it", "vi", "DeviceModelId", "GetAppAndVersionCommand", "DEVICE_SESSION_REFRESHER_POLLING_INTERVAL", "SessionEvents", "DevicePinger", "dummySendCommandFunction", "mockLogger", "mockedLoggerModuleFactory", "eventSubject", "mockSessionEventDispatcher", "dummyConnectedDevice", "devicePinger", "dummyResult", "result", "commandArg", "dummyError", "neverResolvingPromise", "pingPromise"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{BehaviorSubject as v}from"rxjs";import{v4 as
|
|
1
|
+
import{BehaviorSubject as h,from as d,lastValueFrom as p,timeout as v}from"rxjs";import{v4 as m}from"uuid";import{CommandUtils as S}from"../../../api/command/utils/CommandUtils";import{DeviceStatus as l}from"../../../api/device/DeviceStatus";import{DeviceSessionStateType as D}from"../../../api/device-session/DeviceSessionState";import{SendApduTimeoutError as _,SendCommandTimeoutError as g}from"../../../api/transport/model/Errors";import{formatApduReceivedLog as f,formatApduSendingLog as E}from"../../../api/utils/apduLogs";import{DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS as b}from"../../device-session/data/DeviceSessionRefresherConst";import{IntentQueueService as A}from"../../device-session/service/IntentQueueService";import{RefresherService as C}from"../../device-session/service/RefresherService";import{DevicePinger as R}from"./DevicePinger";import{DeviceSessionEventDispatcher as y,SessionEvents as c}from"./DeviceSessionEventDispatcher";import{DeviceSessionRefresher as I}from"./DeviceSessionRefresher";import{DeviceSessionStateHandler as O}from"./DeviceSessionStateHandler";class K{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_loggerModuleFactory;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new y;_bypassIntentQueue=!1;constructor({connectedDevice:e,id:t=m()},i,s,n,r,a=o=>new A(i,o)){this._id=t,this._connectedDevice=e,this._loggerModuleFactory=i,this._logger=i("device-session"),this._managerApiService=s,this._intentQueueService=a(this._sessionEventDispatcher),this._secureChannelService=n,this._refresherOptions={...b,...r},this._deviceState=new h({sessionStateType:D.Connected,deviceStatus:l.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new R(i,e,this._sessionEventDispatcher,(o,u)=>this.sendCommand(o,u)),this._deviceSessionRefresher=new I(i,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new O(i,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,o=>this.setDeviceSessionState(o)),this._refresherService=new C(i,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{this._refresherOptions.isRefresherDisabled?await this._pinger.ping():this._deviceSessionRefresher.startRefresher()}catch(e){throw this._logger.error("Error while initialising session",{data:{error:e}}),e}}get id(){return this._id}get connectedDevice(){return this._connectedDevice}get state(){return this._deviceState.asObservable()}getDeviceSessionState(){return this._deviceState.getValue()}setDeviceSessionState(e){this._deviceState.next(e)}sendApdu(e,t={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._bypassIntentQueue?this._unsafeInternalSendApdu(e,t):this._internalSendApdu(e,t)}_internalSendApdu(e,t){const i=t.abortTimeout,s=Date.now(),{observable:n,cancel:r}=this._intentQueueService.enqueue({type:"send-apdu",execute:()=>d((async()=>{const o=Date.now()-s;return await this._unsafeInternalSendApdu(e,{isPolling:t.isPolling,triggersDisconnection:t.triggersDisconnection,abortTimeout:i?i-o:void 0})})())}),a=i?n.pipe(v({each:i,with:()=>{throw r(),new _}})):n;return p(a)}async _unsafeInternalSendApdu(e,t={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){return this._logger.debug(E(e)),(await this._connectedDevice.sendApdu(e,t.triggersDisconnection,t.abortTimeout)).ifRight(s=>{this._logger.debug(f(s)),S.isLockedDeviceResponse(s)?this._sessionEventDispatcher.dispatch({eventName:c.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:c.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:c.DEVICE_STATE_UPDATE_UNKNOWN})})}sendCommand(e,t){return this._logger.debug(`[sendCommand] ${e.name}`),this._bypassIntentQueue?this._unsafeInternalSendCommand(e,t):this._internalSendCommand(e,t)}_internalSendCommand(e,t){const i=Date.now(),{observable:s,cancel:n}=this._intentQueueService.enqueue({type:"send-command",execute:()=>d((async()=>{const a=Date.now()-i;return await this._unsafeInternalSendCommand(e,t?t-a:void 0)})())}),r=t?s.pipe(v({each:t,with:()=>{throw n(),new g}})):s;return p(r)}async _unsafeInternalSendCommand(e,t){const i=e.getApdu();return(await this._unsafeInternalSendApdu(i.getRawApdu(),{isPolling:!1,triggersDisconnection:e.triggersDisconnection??!1,abortTimeout:t})).caseOf({Left:n=>{throw this._logger.error("[sendCommand] error",{data:{err:n}}),n},Right:n=>{const r=e.parseResponse(n,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:r}}),r}})}executeDeviceAction(e){return this._bypassIntentQueue?this._unsafeInternalExecuteDeviceAction(e):this._internalExecuteDeviceAction(e)}_internalExecuteDeviceAction(e){let t;const{observable:i,cancel:s}=this._intentQueueService.enqueue({type:"device-action",execute:()=>{const{observable:n,cancel:r}=this._unsafeInternalExecuteDeviceAction(e);return t=r,n}});return{observable:i,cancel:()=>{t?.(),s()}}}_unsafeInternalExecuteDeviceAction(e){const{observable:t,cancel:i}=e._execute({sendApdu:async s=>this._unsafeInternalSendApdu(s),sendCommand:async s=>this._unsafeInternalSendCommand(s),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:s=>(this.setDeviceSessionState(s),this._deviceState.getValue()),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService,loggerFactory:this._loggerModuleFactory});return{observable:t,cancel:i}}close(){this._updateDeviceStatus(l.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher(),this._pinger.unsubscribe()}disableRefresher(e){return this._refresherService.disableRefresher(e)}_unsafeBypassIntentQueue(e){this._bypassIntentQueue=e}_updateDeviceStatus(e){const t=this._deviceState.getValue();this._deviceState.next({...t,deviceStatus:e})}}export{K as DeviceSession};
|
|
2
2
|
//# sourceMappingURL=DeviceSession.js.map
|
|
@@ -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 { BehaviorSubject, type Observable } 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 { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { formatApduSendingLog } from \"@api/utils/apduLogs\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { MutexService } from \"@internal/device-session/service/MutexService\";\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 _refresherOptions: DeviceSessionRefresherOptions;\n private _pinger: DevicePinger;\n private _deviceSessionRefresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private _commandMutex = new MutexService();\n private _sessionEventDispatcher = new DeviceSessionEventDispatcher();\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n deviceSessionRefresherOptions: DeviceSessionRefresherOptions | undefined,\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._logger = loggerModuleFactory(\"device-session\");\n this._managerApiService = managerApiService;\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 await this._pinger.ping();\n } catch (error) {\n this._logger.error(\"Error while initialising session\", {\n data: { error },\n });\n throw error;\n } finally {\n if (!this._refresherOptions.isRefresherDisabled) {\n this._deviceSessionRefresher.startRefresher();\n }\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 async sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n const release = await this._commandMutex.lock();\n\n try {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_BUSY,\n });\n\n this._logger.debug(formatApduSendingLog(rawApdu));\n const result = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n options.abortTimeout,\n );\n\n result\n .ifRight((response: ApduResponse) => {\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_CONNECTED,\n });\n });\n return result;\n } finally {\n release();\n }\n }\n\n public async 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 const apdu = command.getApdu();\n\n const response = await this.sendApdu(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 const { observable, cancel } = deviceAction._execute({\n sendApdu: async (apdu: Uint8Array) => this.sendApdu(apdu),\n sendCommand: async <Response, ErrorStatusCodes, Args>(\n command: Command<Response, ErrorStatusCodes, Args>,\n abortTimeout?: number,\n ) => this.sendCommand(command, abortTimeout),\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 disableRefresher: (blockerId: string) =>\n this._refresherService.disableRefresher(blockerId),\n getManagerApiService: () => this._managerApiService,\n getSecureChannelService: () => this._secureChannelService,\n });\n return { observable, cancel };\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 private _updateDeviceStatus(deviceStatus: DeviceStatus): void {\n const state = this._deviceState.getValue();\n this._deviceState.next({ ...state, deviceStatus });\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,
|
|
6
|
-
"names": ["BehaviorSubject", "uuidv4", "CommandUtils", "DeviceStatus", "DeviceSessionStateType", "formatApduSendingLog", "DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS", "
|
|
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,QAAA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wBA,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"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Left as C,Right as g}from"purify-ts";import{of as b,Subject as x,throwError as A}from"rxjs";import{delay as f,take as T}from"rxjs/operators";import{CommandResultStatus as w}from"../../../api/command/model/CommandResult";import{DeviceStatus as S}from"../../../api/device/DeviceStatus";import{DeviceSessionStateType as y}from"../../../api/device-session/DeviceSessionState";import{connectedDeviceStubBuilder as R}from"../../../api/transport/model/TransportConnectedDevice.stub";import{DefaultLoggerPublisherService as E}from"../../logger-publisher/service/DefaultLoggerPublisherService";import{DeviceSession as v}from"./DeviceSession";describe("DeviceSession",()=>{let e,k,a,u,d,o,l,p;const r=R();beforeEach(()=>{k=new E([],"device-session-test"),a=vi.fn(()=>k),u={getAppList:vi.fn(),getAppsByHash:vi.fn(),getCurrentFirmware:vi.fn(),getLatestFirmware:vi.fn()},d={genuineCheck:vi.fn(),listInstalledApps:vi.fn(),updateMcu:vi.fn(),updateFirmware:vi.fn(),installApp:vi.fn(),uninstallApp:vi.fn()},o={enqueue:vi.fn().mockReturnValue({observable:b(null).pipe(f(1)),cancel:vi.fn()})},l=()=>o,p={isRefresherDisabled:!0}}),afterEach(()=>{e?.close(),vi.restoreAllMocks()}),describe("constructor",()=>{it("should create a device session with default id",()=>{e=new v({connectedDevice:r},a,u,d,p,l),expect(e).toBeDefined(),expect(e.id).toBeDefined(),expect(e.connectedDevice).toBe(r)}),it("should create a device session with custom id",()=>{const t="custom-session-id";e=new v({connectedDevice:r,id:t},a,u,d,p,l),expect(e.id).toBe(t)})}),describe("initialiseSession",()=>{it("should successfully initialize session",()=>{e=new v({connectedDevice:r},a,u,d,{isRefresherDisabled:!1,pollingInterval:1e3},l);const t=vi.spyOn(e._deviceSessionRefresher,"startRefresher");e.initialiseSession(),expect(t).toHaveBeenCalled()})}),describe("getters",()=>{beforeEach(()=>{e=new v({connectedDevice:r,id:"test-id"},a,u,d,p,l)}),it("should return session id",()=>{expect(e.id).toBe("test-id")}),it("should return connected device",()=>{expect(e.connectedDevice).toBe(r)}),it("should return state as observable",async()=>{const t=e.state;await new Promise(c=>{t.pipe(T(1)).subscribe(n=>{expect(n.sessionStateType).toBe(y.Connected),expect(n.deviceStatus).toBe(S.CONNECTED),c()})})})}),describe("getDeviceSessionState and setDeviceSessionState",()=>{beforeEach(()=>{e=new v({connectedDevice:r},a,u,d,p,l)}),it("should get current device session state",()=>{const t=e.getDeviceSessionState();expect(t.sessionStateType).toBe(y.Connected),expect(t.deviceStatus).toBe(S.CONNECTED)}),it("should set device session state",async()=>{const t={sessionStateType:y.ReadyWithoutSecureChannel,deviceStatus:S.LOCKED,deviceModelId:r.deviceModel.id,currentApp:{name:"Test",version:"1.0.0"},installedApps:[],isSecureConnectionAllowed:!1};await new Promise(c=>{let n=!1;const s=e.state.subscribe(i=>{i.sessionStateType===y.ReadyWithoutSecureChannel?(expect(i).toMatchObject({sessionStateType:y.ReadyWithoutSecureChannel,deviceStatus:S.LOCKED,deviceModelId:r.deviceModel.id}),s.unsubscribe(),c()):n||(n=!0)});e.setDeviceSessionState(t)})})}),describe("sendApdu",()=>{let t,c;beforeEach(()=>{t=new Uint8Array([224,1,0,0]),c={data:new Uint8Array([1,2]),statusCode:new Uint8Array([144,0])},e=new v({connectedDevice:r},a,u,d,p,l)}),it("should successfully send APDU",async()=>{const n=b(g(c)).pipe(f(1));o.enqueue.mockReturnValue({observable:n,cancel:vi.fn()});const s=await e.sendApdu(t);expect(o.enqueue).toHaveBeenCalledWith({type:"send-apdu",execute:expect.any(Function)}),expect(s.isRight()).toBe(!0),s.ifRight(i=>{expect(i).toEqual(c)})}),it("should handle APDU send error",async()=>{const n={_tag:"SendApduError"},s=b(C(n)).pipe(f(1));o.enqueue.mockReturnValue({observable:s,cancel:vi.fn()});const i=await e.sendApdu(t);expect(i.isLeft()).toBe(!0),i.ifLeft(m=>{expect(m).toEqual(n)})}),it("should handle APDU timeout",async()=>{const n=vi.fn(),s=new x;o.enqueue.mockReturnValue({observable:s.asObservable(),cancel:n}),vi.useFakeTimers();const i=e.sendApdu(t,{abortTimeout:1e3});vi.advanceTimersByTime(1100);let m;try{await i}catch(h){m=h}vi.useRealTimers(),expect(m).toBeDefined(),expect(o.enqueue).toHaveBeenCalled()})}),describe("sendCommand",()=>{let t,c;beforeEach(()=>{c={status:w.Success,data:{test:"data"}},t={getApdu:vi.fn().mockReturnValue({getRawApdu:()=>new Uint8Array([224,1,0,0])}),parseResponse:vi.fn().mockReturnValue(c),triggersDisconnection:!1},e=new v({connectedDevice:r},a,u,d,p,l)}),it("should successfully send command",async()=>{const n=b(c).pipe(f(1));o.enqueue.mockReturnValue({observable:n,cancel:vi.fn()});const s=await e.sendCommand(t);expect(o.enqueue).toHaveBeenCalledWith({type:"send-command",execute:expect.any(Function)}),expect(s).toEqual(c)}),it("should handle command timeout",async()=>{const n=vi.fn(),s=new x;o.enqueue.mockReturnValue({observable:s.asObservable(),cancel:n}),vi.useFakeTimers();const i=e.sendCommand(t,1e3);vi.advanceTimersByTime(1100);try{await i}catch{}vi.useRealTimers(),expect(o.enqueue).toHaveBeenCalled()}),it("should handle command error",async()=>{const n=new Error("Command failed"),s=A(()=>n);o.enqueue.mockReturnValue({observable:s,cancel:vi.fn()}),await expect(e.sendCommand(t)).rejects.toThrow("Command failed")})}),describe("executeDeviceAction",()=>{let t;beforeEach(()=>{const c=b({intermediateValue:"test",requiredUserInteraction:"SignTransaction"}).pipe(f(1));t={_execute:vi.fn().mockReturnValue({observable:c})},e=new v({connectedDevice:r},a,u,d,p,l)}),it("should execute device action",async()=>{const c=b({intermediateValue:"test",requiredUserInteraction:"SignTransaction"}).pipe(f(1)),n=vi.fn();o.enqueue.mockReturnValue({observable:c,cancel:n});const{observable:s,cancel:i}=e.executeDeviceAction(t);expect(o.enqueue).toHaveBeenCalledWith({type:"device-action",execute:expect.any(Function)}),expect(s).toBeDefined(),expect(i).toBeTypeOf("function");const m=[];await new Promise(h=>{s.subscribe({next:D=>m.push(D),complete:()=>h()})}),expect(m).toEqual([{intermediateValue:"test",requiredUserInteraction:"SignTransaction"}]),i(),expect(n).toHaveBeenCalled()}),it("should provide correct internal API to device action",()=>{const c=b({intermediateValue:"test",requiredUserInteraction:"SignTransaction"}).pipe(f(1));o.enqueue.mockImplementation(n=>(n.execute(),{observable:c,cancel:vi.fn()})),e.executeDeviceAction(t),expect(t._execute).toHaveBeenCalledWith({sendApdu:expect.any(Function),sendCommand:expect.any(Function),getDeviceModel:expect.any(Function),getDeviceSessionState:expect.any(Function),getDeviceSessionStateObservable:expect.any(Function),setDeviceSessionState:expect.any(Function),getManagerApiService:expect.any(Function),getSecureChannelService:expect.any(Function),loggerFactory:expect.any(Function)})}),it("should allow cancelling device action",()=>{const c=vi.fn(),n=new x;o.enqueue.mockReturnValue({observable:n.asObservable(),cancel:c});const{cancel:s}=e.executeDeviceAction(t);s(),expect(c).toHaveBeenCalled()})}),describe("close",()=>{it("should close the session and update device status",()=>{e=new v({connectedDevice:r},a,u,d,p,l);let t=!1;e.state.subscribe({complete:()=>{t=!0}}),e.close();const c=e.getDeviceSessionState();expect(c.deviceStatus).toBe(S.NOT_CONNECTED),expect(t).toBe(!0)})})});
|
|
2
2
|
//# sourceMappingURL=DeviceSession.test.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/model/DeviceSession.test.ts"],
|
|
4
|
-
"sourcesContent": ["import { type DmkConfig } from \"@api/DmkConfig\";\nimport { connectedDeviceStubBuilder } from \"@api/index\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { DefaultLoggerPublisherService } from \"@internal/logger-publisher/service/DefaultLoggerPublisherService\";\nimport { AxiosManagerApiDataSource } from \"@internal/manager-api/data/AxiosManagerApiDataSource\";\nimport { DefaultManagerApiService } from \"@internal/manager-api/service/DefaultManagerApiService\";\nimport { DefaultSecureChannelDataSource } from \"@internal/secure-channel/data/DefaultSecureChannelDataSource\";\nimport { DefaultSecureChannelService } from \"@internal/secure-channel/service/DefaultSecureChannelService\";\n\nimport { DeviceSession } from \"./DeviceSession\";\n\ndescribe(\"DeviceSession\", () => {\n it(\"should unsubscribe pinger from event subscriber when session is closed\", () => {\n // ARRANGE\n const logger = new DefaultLoggerPublisherService([], \"DeviceSession\");\n const managerApiDataSource = new AxiosManagerApiDataSource({} as DmkConfig);\n const managerApi = new DefaultManagerApiService(managerApiDataSource);\n const secureChannelDataSource = new DefaultSecureChannelDataSource(\n {} as DmkConfig,\n );\n const secureChannel = new DefaultSecureChannelService(\n secureChannelDataSource,\n );\n const deviceSessionRefresherOptions =\n DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS;\n const deviceSession = new DeviceSession(\n { connectedDevice: connectedDeviceStubBuilder() },\n () => logger,\n managerApi,\n secureChannel,\n deviceSessionRefresherOptions,\n );\n const unsubscribe = vi\n .spyOn(deviceSession[\"_pinger\"], \"unsubscribe\")\n .mockImplementation(() => {});\n\n // ACT\n deviceSession.close();\n\n // ASSERT\n expect(unsubscribe).toHaveBeenCalled();\n });\n});\n"],
|
|
5
|
-
"mappings": "AACA,OAAS,
|
|
6
|
-
"names": ["
|
|
4
|
+
"sourcesContent": ["/* eslint-disable @typescript-eslint/no-unsafe-assignment */\nimport { Left, Right } from \"purify-ts\";\nimport { of, Subject, throwError } from \"rxjs\";\nimport { delay, take } from \"rxjs/operators\";\nimport { type Mocked } from \"vitest\";\n\nimport { type Command } from \"@api/command/Command\";\nimport {\n type CommandResult,\n CommandResultStatus,\n} from \"@api/command/model/CommandResult\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport { type DeviceAction } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport { DeviceSessionStateType } from \"@api/device-session/DeviceSessionState\";\nimport { type DmkError } from \"@api/Error\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { connectedDeviceStubBuilder } from \"@api/transport/model/TransportConnectedDevice.stub\";\nimport { type IntentQueueService } from \"@internal/device-session/service/IntentQueueService\";\nimport { DefaultLoggerPublisherService } from \"@internal/logger-publisher/service/DefaultLoggerPublisherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport {\n DeviceSession,\n type DeviceSessionRefresherOptions,\n} from \"./DeviceSession\";\n\ndescribe(\"DeviceSession\", () => {\n let deviceSession: DeviceSession;\n let mockLogger: LoggerPublisherService;\n let mockLoggerFactory: ReturnType<typeof vi.fn>;\n let mockManagerApi: Mocked<ManagerApiService>;\n let mockSecureChannel: Mocked<SecureChannelService>;\n let mockIntentQueueService: Mocked<IntentQueueService>;\n let mockIntentQueueServiceFactory: () => IntentQueueService;\n let refresherOptions: DeviceSessionRefresherOptions;\n const mockConnectedDevice = connectedDeviceStubBuilder();\n\n beforeEach(() => {\n // Setup logger\n mockLogger = new DefaultLoggerPublisherService([], \"device-session-test\");\n mockLoggerFactory = vi.fn(() => mockLogger);\n\n // Setup mocks\n mockManagerApi = {\n getAppList: vi.fn(),\n getAppsByHash: vi.fn(),\n getCurrentFirmware: vi.fn(),\n getLatestFirmware: vi.fn(),\n } as unknown as Mocked<ManagerApiService>;\n\n mockSecureChannel = {\n genuineCheck: vi.fn(),\n listInstalledApps: vi.fn(),\n updateMcu: vi.fn(),\n updateFirmware: vi.fn(),\n installApp: vi.fn(),\n uninstallApp: vi.fn(),\n } as unknown as Mocked<SecureChannelService>;\n\n // Setup intent queue service with default mock\n mockIntentQueueService = {\n enqueue: vi.fn().mockReturnValue({\n observable: of(null).pipe(delay(1)),\n cancel: vi.fn(),\n }),\n } as unknown as Mocked<IntentQueueService>;\n\n mockIntentQueueServiceFactory = () => mockIntentQueueService;\n\n refresherOptions = {\n isRefresherDisabled: true,\n };\n });\n\n afterEach(() => {\n deviceSession?.close();\n vi.restoreAllMocks();\n });\n\n describe(\"constructor\", () => {\n it(\"should create a device session with default id\", () => {\n // when\n deviceSession = new DeviceSession(\n { connectedDevice: mockConnectedDevice },\n mockLoggerFactory,\n mockManagerApi,\n mockSecureChannel,\n refresherOptions,\n mockIntentQueueServiceFactory,\n );\n\n // then\n expect(deviceSession).toBeDefined();\n expect(deviceSession.id).toBeDefined();\n expect(deviceSession.connectedDevice).toBe(mockConnectedDevice);\n });\n\n it(\"should create a device session with custom id\", () => {\n // given\n const customId = \"custom-session-id\";\n\n // when\n deviceSession = new DeviceSession(\n { connectedDevice: mockConnectedDevice, id: customId },\n mockLoggerFactory,\n mockManagerApi,\n mockSecureChannel,\n refresherOptions,\n mockIntentQueueServiceFactory,\n );\n\n // then\n expect(deviceSession.id).toBe(customId);\n });\n });\n\n describe(\"initialiseSession\", () => {\n it(\"should successfully initialize session\", () => {\n // given\n deviceSession = new DeviceSession(\n { connectedDevice: mockConnectedDevice },\n mockLoggerFactory,\n mockManagerApi,\n mockSecureChannel,\n { isRefresherDisabled: false, pollingInterval: 1000 },\n mockIntentQueueServiceFactory,\n );\n\n const mockRefresherStartSpy = vi.spyOn(\n deviceSession[\"_deviceSessionRefresher\"],\n \"startRefresher\",\n );\n\n // when\n deviceSession.initialiseSession();\n\n // then\n expect(mockRefresherStartSpy).toHaveBeenCalled();\n });\n });\n\n describe(\"getters\", () => {\n beforeEach(() => {\n deviceSession = new DeviceSession(\n { connectedDevice: mockConnectedDevice, id: \"test-id\" },\n mockLoggerFactory,\n mockManagerApi,\n mockSecureChannel,\n refresherOptions,\n mockIntentQueueServiceFactory,\n );\n });\n\n it(\"should return session id\", () => {\n expect(deviceSession.id).toBe(\"test-id\");\n });\n\n it(\"should return connected device\", () => {\n expect(deviceSession.connectedDevice).toBe(mockConnectedDevice);\n });\n\n it(\"should return state as observable\", async () => {\n const stateObservable = deviceSession.state;\n\n await new Promise<void>((resolve) => {\n stateObservable.pipe(take(1)).subscribe((state) => {\n expect(state.sessionStateType).toBe(DeviceSessionStateType.Connected);\n expect(state.deviceStatus).toBe(DeviceStatus.CONNECTED);\n resolve();\n });\n });\n });\n });\n\n describe(\"getDeviceSessionState and setDeviceSessionState\", () => {\n beforeEach(() => {\n deviceSession = new DeviceSession(\n { connectedDevice: mockConnectedDevice },\n mockLoggerFactory,\n mockManagerApi,\n mockSecureChannel,\n refresherOptions,\n mockIntentQueueServiceFactory,\n );\n });\n\n it(\"should get current device session state\", () => {\n // when\n const state = deviceSession.getDeviceSessionState();\n\n // then\n expect(state.sessionStateType).toBe(DeviceSessionStateType.Connected);\n expect(state.deviceStatus).toBe(DeviceStatus.CONNECTED);\n });\n\n it(\"should set device session state\", async () => {\n // given\n const newState = {\n sessionStateType: DeviceSessionStateType.ReadyWithoutSecureChannel,\n deviceStatus: DeviceStatus.LOCKED,\n deviceModelId: mockConnectedDevice.deviceModel.id,\n currentApp: { name: \"Test\", version: \"1.0.0\" },\n installedApps: [],\n isSecureConnectionAllowed: false,\n };\n\n // when\n await new Promise<void>((resolve) => {\n let subscriptionStarted = false;\n const subscription = deviceSession.state.subscribe((state) => {\n if (\n state.sessionStateType ===\n DeviceSessionStateType.ReadyWithoutSecureChannel\n ) {\n expect(state).toMatchObject({\n sessionStateType:\n DeviceSessionStateType.ReadyWithoutSecureChannel,\n deviceStatus: DeviceStatus.LOCKED,\n deviceModelId: mockConnectedDevice.deviceModel.id,\n });\n subscription.unsubscribe();\n resolve();\n } else if (!subscriptionStarted) {\n subscriptionStarted = true;\n }\n });\n\n deviceSession.setDeviceSessionState(newState);\n });\n });\n });\n\n describe(\"sendApdu\", () => {\n let mockApdu: Uint8Array;\n let mockResponse: ApduResponse;\n\n beforeEach(() => {\n mockApdu = new Uint8Array([0xe0, 0x01, 0x00, 0x00]);\n mockResponse = {\n data: new Uint8Array([0x01, 0x02]),\n statusCode: new Uint8Array([0x90, 0x00]),\n };\n\n deviceSession = new DeviceSession(\n { connectedDevice: mockConnectedDevice },\n mockLoggerFactory,\n mockManagerApi,\n mockSecureChannel,\n refresherOptions,\n mockIntentQueueServiceFactory,\n );\n });\n\n it(\"should successfully send APDU\", async () => {\n // given\n const mockObservable = of(Right(mockResponse)).pipe(delay(1));\n mockIntentQueueService.enqueue.mockReturnValue({\n observable: mockObservable,\n cancel: vi.fn(),\n });\n\n // when\n const result = await deviceSession.sendApdu(mockApdu);\n\n // then\n expect(mockIntentQueueService.enqueue).toHaveBeenCalledWith({\n type: \"send-apdu\",\n execute: expect.any(Function),\n });\n expect(result.isRight()).toBe(true);\n result.ifRight((response) => {\n expect(response).toEqual(mockResponse);\n });\n });\n\n it(\"should handle APDU send error\", async () => {\n // given\n const error = { _tag: \"SendApduError\" } as DmkError;\n const mockObservable = of(Left(error)).pipe(delay(1));\n mockIntentQueueService.enqueue.mockReturnValue({\n observable: mockObservable,\n cancel: vi.fn(),\n });\n\n // when\n const result = await deviceSession.sendApdu(mockApdu);\n\n // then\n expect(result.isLeft()).toBe(true);\n result.ifLeft((err) => {\n expect(err).toEqual(error);\n });\n });\n\n it(\"should handle APDU timeout\", async () => {\n // given\n const mockCancel = vi.fn();\n const subject = new Subject();\n\n mockIntentQueueService.enqueue.mockReturnValue({\n observable: subject.asObservable(),\n cancel: mockCancel,\n });\n\n vi.useFakeTimers();\n\n // when\n const sendPromise = deviceSession.sendApdu(mockApdu, {\n abortTimeout: 1000,\n });\n\n // Advance timers to trigger timeout\n vi.advanceTimersByTime(1100);\n\n let caughtError: Error | undefined;\n try {\n await sendPromise;\n } catch (error) {\n caughtError = error as Error;\n }\n\n vi.useRealTimers();\n\n // then\n expect(caughtError).toBeDefined();\n expect(mockIntentQueueService.enqueue).toHaveBeenCalled();\n });\n });\n\n describe(\"sendCommand\", () => {\n type TestData = { test: string };\n type TestArgs = Record<string, never>;\n type TestErrorCodes = number;\n\n let mockCommand: Mocked<Command<TestData, TestArgs, TestErrorCodes>>;\n let mockCommandResult: CommandResult<TestData, TestErrorCodes>;\n\n beforeEach(() => {\n mockCommandResult = {\n status: CommandResultStatus.Success,\n data: { test: \"data\" },\n };\n\n mockCommand = {\n getApdu: vi.fn().mockReturnValue({\n getRawApdu: () => new Uint8Array([0xe0, 0x01, 0x00, 0x00]),\n }),\n parseResponse: vi.fn().mockReturnValue(mockCommandResult),\n triggersDisconnection: false,\n } as unknown as Mocked<Command<TestData, TestArgs, TestErrorCodes>>;\n\n deviceSession = new DeviceSession(\n { connectedDevice: mockConnectedDevice },\n mockLoggerFactory,\n mockManagerApi,\n mockSecureChannel,\n refresherOptions,\n mockIntentQueueServiceFactory,\n );\n });\n\n it(\"should successfully send command\", async () => {\n // given\n const mockObservable = of(mockCommandResult).pipe(delay(1));\n mockIntentQueueService.enqueue.mockReturnValue({\n observable: mockObservable,\n cancel: vi.fn(),\n });\n\n // when\n const result = await deviceSession.sendCommand(mockCommand);\n\n // then\n expect(mockIntentQueueService.enqueue).toHaveBeenCalledWith({\n type: \"send-command\",\n execute: expect.any(Function),\n });\n expect(result).toEqual(mockCommandResult);\n });\n\n it(\"should handle command timeout\", async () => {\n // given\n const mockCancel = vi.fn();\n const subject = new Subject();\n\n mockIntentQueueService.enqueue.mockReturnValue({\n observable: subject.asObservable(),\n cancel: mockCancel,\n });\n\n vi.useFakeTimers();\n\n // when\n const commandPromise = deviceSession.sendCommand(mockCommand, 1000);\n\n // Advance timers to trigger timeout\n vi.advanceTimersByTime(1100);\n\n try {\n await commandPromise;\n } catch {\n // Expected to timeout\n }\n\n vi.useRealTimers();\n\n // then\n expect(mockIntentQueueService.enqueue).toHaveBeenCalled();\n });\n\n it(\"should handle command error\", async () => {\n // given\n const error = new Error(\"Command failed\");\n const mockObservable = throwError(() => error);\n mockIntentQueueService.enqueue.mockReturnValue({\n observable: mockObservable,\n cancel: vi.fn(),\n });\n\n // when/then\n await expect(deviceSession.sendCommand(mockCommand)).rejects.toThrow(\n \"Command failed\",\n );\n });\n });\n\n describe(\"executeDeviceAction\", () => {\n type TestOutput = { result: string };\n type TestInput = { input: string };\n type TestError = DmkError;\n type TestIntermediateValue = {\n intermediateValue: string;\n requiredUserInteraction:\n | \"UnlockDevice\"\n | \"ConfirmOpenApp\"\n | \"ConfirmCloseApp\"\n | \"AllowListAccess\"\n | \"AllowSecureChannelConnection\"\n | \"AllowedDataRecording\"\n | \"SignTransaction\";\n };\n\n let mockDeviceAction: Mocked<\n DeviceAction<TestOutput, TestInput, TestError, TestIntermediateValue>\n >;\n\n beforeEach(() => {\n const mockActionObservable = of({\n intermediateValue: \"test\",\n requiredUserInteraction: \"SignTransaction\" as const,\n }).pipe(delay(1));\n\n mockDeviceAction = {\n _execute: vi.fn().mockReturnValue({\n observable: mockActionObservable,\n }),\n } as unknown as Mocked<\n DeviceAction<TestOutput, TestInput, TestError, TestIntermediateValue>\n >;\n\n deviceSession = new DeviceSession(\n { connectedDevice: mockConnectedDevice },\n mockLoggerFactory,\n mockManagerApi,\n mockSecureChannel,\n refresherOptions,\n mockIntentQueueServiceFactory,\n );\n });\n\n it(\"should execute device action\", async () => {\n // given\n const mockActionObservable = of({\n intermediateValue: \"test\",\n requiredUserInteraction: \"SignTransaction\" as const,\n }).pipe(delay(1));\n const mockCancel = vi.fn();\n\n mockIntentQueueService.enqueue.mockReturnValue({\n observable: mockActionObservable,\n cancel: mockCancel,\n });\n\n // when\n const { observable, cancel } =\n deviceSession.executeDeviceAction(mockDeviceAction);\n\n // then\n expect(mockIntentQueueService.enqueue).toHaveBeenCalledWith({\n type: \"device-action\",\n execute: expect.any(Function),\n });\n expect(observable).toBeDefined();\n expect(cancel).toBeTypeOf(\"function\");\n\n // Verify observable emits values\n const values: unknown[] = [];\n await new Promise<void>((resolve) => {\n observable.subscribe({\n next: (value) => values.push(value),\n complete: () => resolve(),\n });\n });\n\n expect(values).toEqual([\n {\n intermediateValue: \"test\",\n requiredUserInteraction: \"SignTransaction\",\n },\n ]);\n\n // Verify cancel is called\n cancel();\n expect(mockCancel).toHaveBeenCalled();\n });\n\n it(\"should provide correct internal API to device action\", () => {\n // given\n const mockActionObservable = of({\n intermediateValue: \"test\",\n requiredUserInteraction: \"SignTransaction\" as const,\n }).pipe(delay(1));\n\n mockIntentQueueService.enqueue.mockImplementation((intent) => {\n // Execute the device action to verify the internal API\n void intent.execute();\n\n return {\n observable: mockActionObservable,\n cancel: vi.fn(),\n };\n });\n\n // when\n deviceSession.executeDeviceAction(mockDeviceAction);\n\n // then\n expect(mockDeviceAction._execute).toHaveBeenCalledWith({\n sendApdu: expect.any(Function),\n sendCommand: expect.any(Function),\n getDeviceModel: expect.any(Function),\n getDeviceSessionState: expect.any(Function),\n getDeviceSessionStateObservable: expect.any(Function),\n setDeviceSessionState: expect.any(Function),\n getManagerApiService: expect.any(Function),\n getSecureChannelService: expect.any(Function),\n loggerFactory: expect.any(Function),\n });\n });\n\n it(\"should allow cancelling device action\", () => {\n // given\n const mockCancel = vi.fn();\n const subject = new Subject();\n\n mockIntentQueueService.enqueue.mockReturnValue({\n observable: subject.asObservable(),\n cancel: mockCancel,\n });\n\n // when\n const { cancel } = deviceSession.executeDeviceAction(mockDeviceAction);\n cancel();\n\n // then\n expect(mockCancel).toHaveBeenCalled();\n });\n });\n\n describe(\"close\", () => {\n it(\"should close the session and update device status\", () => {\n // given\n deviceSession = new DeviceSession(\n { connectedDevice: mockConnectedDevice },\n mockLoggerFactory,\n mockManagerApi,\n mockSecureChannel,\n refresherOptions,\n mockIntentQueueServiceFactory,\n );\n\n let isComplete = false;\n deviceSession.state.subscribe({\n complete: () => {\n isComplete = true;\n },\n });\n\n // when\n deviceSession.close();\n\n // then\n const state = deviceSession.getDeviceSessionState();\n expect(state.deviceStatus).toBe(DeviceStatus.NOT_CONNECTED);\n expect(isComplete).toBe(true);\n });\n });\n});\n"],
|
|
5
|
+
"mappings": "AACA,OAAS,QAAAA,EAAM,SAAAC,MAAa,YAC5B,OAAS,MAAAC,EAAI,WAAAC,EA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,CAE5DxB,EAAgB,IAAID,EAClB,CAAE,gBAAiBS,CAAoB,EACvCN,EACAC,EACAC,EACAG,EACAD,CACF,EAEA,IAAIgC,EAAa,GACjBtC,EAAc,MAAM,UAAU,CAC5B,SAAU,IAAM,CACdsC,EAAa,EACf,CACF,CAAC,EAGDtC,EAAc,MAAM,EAGpB,MAAMa,EAAQb,EAAc,sBAAsB,EAClD,OAAOa,EAAM,YAAY,EAAE,KAAKlB,EAAa,aAAa,EAC1D,OAAO2C,CAAU,EAAE,KAAK,EAAI,CAC9B,CAAC,CACH,CAAC,CACH,CAAC",
|
|
6
|
+
"names": ["Left", "Right", "of", "Subject", "throwError", "delay", "take", "CommandResultStatus", "DeviceStatus", "DeviceSessionStateType", "connectedDeviceStubBuilder", "DefaultLoggerPublisherService", "DeviceSession", "deviceSession", "mockLogger", "mockLoggerFactory", "mockManagerApi", "mockSecureChannel", "mockIntentQueueService", "mockIntentQueueServiceFactory", "refresherOptions", "mockConnectedDevice", "customId", "mockRefresherStartSpy", "stateObservable", "resolve", "state", "newState", "subscriptionStarted", "subscription", "mockApdu", "mockResponse", "mockObservable", "result", "response", "error", "err", "mockCancel", "subject", "sendPromise", "caughtError", "mockCommand", "mockCommandResult", "commandPromise", "mockDeviceAction", "mockActionObservable", "observable", "cancel", "values", "value", "intent", "isComplete"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Subject as n}from"rxjs";var t=(
|
|
1
|
+
import{Subject as n}from"rxjs";var t=(E=>(E.NEW_STATE="NEW_STATE",E.REFRESH_NEEDED="REFRESH_NEEDED",E.COMMAND_SUCCEEDED="COMMAND_SUCCEEDED",E.DEVICE_STATE_UPDATE_BUSY="DEVICE_STATE_UPDATE_BUSY",E.DEVICE_STATE_UPDATE_LOCKED="DEVICE_STATE_UPDATE_LOCKED",E.DEVICE_STATE_UPDATE_CONNECTED="DEVICE_STATE_UPDATE_CONNECTED",E.DEVICE_STATE_UPDATE_UNKNOWN="DEVICE_STATE_UPDATE_UNKNOWN",E))(t||{});class T{_eventEmitter=new n;listen(){return this._eventEmitter.asObservable()}dispatch(e){this._eventEmitter.next(e)}}export{T as DeviceSessionEventDispatcher,t as SessionEvents};
|
|
2
2
|
//# sourceMappingURL=DeviceSessionEventDispatcher.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/model/DeviceSessionEventDispatcher.ts"],
|
|
4
|
-
"sourcesContent": ["import { type Observable, Subject } from \"rxjs\";\n\nimport { type GetAppAndVersionResponse } from \"@api/index\";\nimport { type CommandResult } from \"@api/types\";\n\nexport enum SessionEvents {\n NEW_STATE = \"NEW_STATE\",\n REFRESH_NEEDED = \"REFRESH_NEEDED\",\n COMMAND_SUCCEEDED = \"COMMAND_SUCCEEDED\",\n DEVICE_STATE_UPDATE_BUSY = \"DEVICE_STATE_UPDATE_BUSY\",\n DEVICE_STATE_UPDATE_LOCKED = \"DEVICE_STATE_UPDATE_LOCKED\",\n DEVICE_STATE_UPDATE_CONNECTED = \"DEVICE_STATE_UPDATE_CONNECTED\",\n}\n\ninterface SessionEventPayloads {\n [SessionEvents.NEW_STATE]: undefined;\n [SessionEvents.REFRESH_NEEDED]: undefined;\n [SessionEvents.DEVICE_STATE_UPDATE_BUSY]: undefined;\n [SessionEvents.DEVICE_STATE_UPDATE_LOCKED]: undefined;\n [SessionEvents.DEVICE_STATE_UPDATE_CONNECTED]: undefined;\n [SessionEvents.COMMAND_SUCCEEDED]: CommandResult<GetAppAndVersionResponse>;\n}\n\nexport type NewEvent = {\n [K in SessionEvents]: SessionEventPayloads[K] extends undefined\n ? { eventName: K; eventData?: undefined }\n : { eventName: K; eventData: SessionEventPayloads[K] };\n}[SessionEvents];\n\nexport class DeviceSessionEventDispatcher {\n private _eventEmitter: Subject<NewEvent> = new Subject();\n\n public listen(): Observable<NewEvent> {\n return this._eventEmitter.asObservable();\n }\n\n public dispatch(event: NewEvent): void {\n this._eventEmitter.next(event);\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,OAA0B,WAAAA,MAAe,OAKlC,IAAKC,OACVA,EAAA,UAAY,YACZA,EAAA,eAAiB,iBACjBA,EAAA,kBAAoB,oBACpBA,EAAA,yBAA2B,2BAC3BA,EAAA,2BAA6B,6BAC7BA,EAAA,8BAAgC,
|
|
4
|
+
"sourcesContent": ["import { type Observable, Subject } from \"rxjs\";\n\nimport { type GetAppAndVersionResponse } from \"@api/index\";\nimport { type CommandResult } from \"@api/types\";\n\nexport enum SessionEvents {\n NEW_STATE = \"NEW_STATE\",\n REFRESH_NEEDED = \"REFRESH_NEEDED\",\n COMMAND_SUCCEEDED = \"COMMAND_SUCCEEDED\",\n DEVICE_STATE_UPDATE_BUSY = \"DEVICE_STATE_UPDATE_BUSY\",\n DEVICE_STATE_UPDATE_LOCKED = \"DEVICE_STATE_UPDATE_LOCKED\",\n DEVICE_STATE_UPDATE_CONNECTED = \"DEVICE_STATE_UPDATE_CONNECTED\",\n DEVICE_STATE_UPDATE_UNKNOWN = \"DEVICE_STATE_UPDATE_UNKNOWN\",\n}\n\ninterface SessionEventPayloads {\n [SessionEvents.NEW_STATE]: undefined;\n [SessionEvents.REFRESH_NEEDED]: undefined;\n [SessionEvents.DEVICE_STATE_UPDATE_BUSY]: undefined;\n [SessionEvents.DEVICE_STATE_UPDATE_LOCKED]: undefined;\n [SessionEvents.DEVICE_STATE_UPDATE_CONNECTED]: undefined;\n [SessionEvents.DEVICE_STATE_UPDATE_UNKNOWN]: undefined;\n [SessionEvents.COMMAND_SUCCEEDED]: CommandResult<GetAppAndVersionResponse>;\n}\n\nexport type NewEvent = {\n [K in SessionEvents]: SessionEventPayloads[K] extends undefined\n ? { eventName: K; eventData?: undefined }\n : { eventName: K; eventData: SessionEventPayloads[K] };\n}[SessionEvents];\n\nexport class DeviceSessionEventDispatcher {\n private _eventEmitter: Subject<NewEvent> = new Subject();\n\n public listen(): Observable<NewEvent> {\n return this._eventEmitter.asObservable();\n }\n\n public dispatch(event: NewEvent): void {\n this._eventEmitter.next(event);\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAA0B,WAAAA,MAAe,OAKlC,IAAKC,OACVA,EAAA,UAAY,YACZA,EAAA,eAAiB,iBACjBA,EAAA,kBAAoB,oBACpBA,EAAA,yBAA2B,2BAC3BA,EAAA,2BAA6B,6BAC7BA,EAAA,8BAAgC,gCAChCA,EAAA,4BAA8B,8BAPpBA,OAAA,IA0BL,MAAMC,CAA6B,CAChC,cAAmC,IAAIF,EAExC,QAA+B,CACpC,OAAO,KAAK,cAAc,aAAa,CACzC,CAEO,SAASG,EAAuB,CACrC,KAAK,cAAc,KAAKA,CAAK,CAC/B,CACF",
|
|
6
6
|
"names": ["Subject", "SessionEvents", "DeviceSessionEventDispatcher", "event"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{timer as
|
|
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};
|
|
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 {
|
|
5
|
-
"mappings": "AAAA,
|
|
6
|
-
"names": ["timer", "DeviceModelId", "DEVICE_SESSION_REFRESHER_MINIMUM_POLLING_INTERVAL", "DEVICE_SESSION_REFRESHER_POLLING_INTERVAL", "SessionEvents", "DeviceSessionRefresher", "loggerModuleFactory", "refresherOptions", "_sessionEventDispatcher", "connectedDevice", "pollingInterval", "logger", "defaultNanoPollingInterval"]
|
|
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,mBA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L,CAAe,sCAAsCR,CAAiD,EAC/H,EACOA,GAGFQ,GAAmBP,CAC9B,CACF,CACF",
|
|
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
|
|
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)})});
|
|
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?.
|
|
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,EACnC,SAAUN,EAAG,GAAG,CAClB,EACAQ,EAAa,CACX,KAAMR,EAAG,GAAG,EACZ,KAAMA,EAAG,GAAG,EACZ,MAAOA,EAAG,GAAG,EACb,MAAOA,EAAG,GAAG,EACb,YAAa,CAAC,CAChB,CACF,CAAC,EAEDL,EAAU,IAAM,CACdiB,GAAW,
|
|
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,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ACAE,CACF,EACAG,EAAU,eAAe,EAEvBL,EAA2B,SAC3B,UAAU,EAEZK,EAAU,cAAc,EACxBZ,EAAG,oBAAoB,GAAI,EAE3BF,EAAOS,EAA2B,QAAQ,EAAE,IAAI,iBAAiB,EACjET,EAAOU,EAAW,IAAI,EAAE,qBAAqB,oBAAoB,CACnE,CAAC,EAEDT,EAAG,2BAA4B,IAAM,CACnC,MAAMc,EAAyC,CAC7C,oBAAqB,GACrB,gBAAiB,GACnB,EACAD,EAAY,IAAIP,EACdM,EACAE,EACAN,EACAE,CACF,EACAG,EAAU,eAAe,EAEvBL,EAA2B,SAC3B,UAAU,EACZP,EAAG,eAAe,EAElBY,EAAU,iBAAiB,EAC3Bd,EAAOU,EAAW,IAAI,EAAE,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",
|
|
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
|
-
import{DeviceSessionStateType as o,DeviceStatus as i,isSuccessCommandResult as v}from"../../../api/index";import{SessionEvents as s}from"../../device-session/model/DeviceSessionEventDispatcher";class
|
|
1
|
+
import{DeviceSessionStateType as o,DeviceStatus as i,isSuccessCommandResult as v}from"../../../api/index";import{SessionEvents as s}from"../../device-session/model/DeviceSessionEventDispatcher";class D{constructor(e,n,t,a,r){this._sessionEventDispatcher=n;this._connectedDevice=t;this._deviceState=a;this.setDeviceSessionState=r;this._subscription=this._sessionEventDispatcher.listen().subscribe(c=>this.mapEventAction(c)),this._logger=e("device-session-state-handler")}_subscription;_logger;_pendingDeviceStatus=i.BUSY;_updateDeviceState(e){const n=this._parseDeviceStatus(e);if(n){const{sessionStateType:t,deviceStatus:a,currentApp:r}=n,c=this._deviceState.getValue();c.sessionStateType===o.Connected?this.setDeviceSessionState({sessionStateType:t,deviceStatus:a,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:r,installedApps:[],isSecureConnectionAllowed:!1}):this.setDeviceSessionState({...c,sessionStateType:t,deviceStatus:a,deviceModelId:this._connectedDevice.deviceModel.id,currentApp:r})}}mapEventAction=e=>{const{eventName:n}=e;switch(n){case s.COMMAND_SUCCEEDED:return this._updateDeviceState(e.eventData);case s.DEVICE_STATE_UPDATE_BUSY:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:i.BUSY});case s.DEVICE_STATE_UPDATE_LOCKED:this._pendingDeviceStatus=i.LOCKED;return;case s.DEVICE_STATE_UPDATE_CONNECTED:this._pendingDeviceStatus=i.CONNECTED;return;case s.NEW_STATE:{const t=this._pendingDeviceStatus;return this._pendingDeviceStatus=i.BUSY,this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:t})}case s.DEVICE_STATE_UPDATE_UNKNOWN:return this.setDeviceSessionState({...this._deviceState.getValue(),deviceStatus:i.BUSY});case s.REFRESH_NEEDED:return;default:{const t=n;throw new Error(`Unhandled context type ${t}`)}}};_parseDeviceStatus(e){return v(e)?{sessionStateType:o.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:e.data.name,version:e.data.version}}:(this._logger.debug("Error while parsing APDU response",{data:{parsedResponse:e}}),null)}unsubscribe(){this._subscription.unsubscribe()}}export{D as DeviceSessionStateHandler};
|
|
2
2
|
//# sourceMappingURL=DeviceSessionStateHandler.js.map
|