@ledgerhq/device-management-kit 0.0.0-develop-20260209001501 → 0.0.0-develop-20260211001836

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/lib/cjs/package.json +1 -1
  2. package/lib/cjs/src/api/device-action/DeviceAction.js +1 -1
  3. package/lib/cjs/src/api/device-action/DeviceAction.js.map +1 -1
  4. package/lib/cjs/src/api/device-action/__test-utils__/makeInternalApi.js +1 -1
  5. package/lib/cjs/src/api/device-action/__test-utils__/makeInternalApi.js.map +3 -3
  6. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js +1 -1
  7. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  8. package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
  9. package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +3 -3
  10. package/lib/cjs/src/api/index.js +1 -1
  11. package/lib/cjs/src/api/index.js.map +3 -3
  12. package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.js +2 -0
  13. package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.js.map +7 -0
  14. package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.test.js +2 -0
  15. package/lib/cjs/src/api/logger-publisher/utils/noopLoggerFactory.test.js.map +7 -0
  16. package/lib/cjs/src/internal/device-session/model/DeviceSession.js +1 -1
  17. package/lib/cjs/src/internal/device-session/model/DeviceSession.js.map +2 -2
  18. package/lib/cjs/src/internal/device-session/model/DeviceSession.test.js +1 -1
  19. package/lib/cjs/src/internal/device-session/model/DeviceSession.test.js.map +2 -2
  20. package/lib/esm/package.json +1 -1
  21. package/lib/esm/src/api/device-action/__test-utils__/makeInternalApi.js +1 -1
  22. package/lib/esm/src/api/device-action/__test-utils__/makeInternalApi.js.map +3 -3
  23. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js +1 -1
  24. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  25. package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
  26. package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +3 -3
  27. package/lib/esm/src/api/index.js +1 -1
  28. package/lib/esm/src/api/index.js.map +3 -3
  29. package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.js +2 -0
  30. package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.js.map +7 -0
  31. package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.test.js +2 -0
  32. package/lib/esm/src/api/logger-publisher/utils/noopLoggerFactory.test.js.map +7 -0
  33. package/lib/esm/src/internal/device-session/model/DeviceSession.js +1 -1
  34. package/lib/esm/src/internal/device-session/model/DeviceSession.js.map +2 -2
  35. package/lib/esm/src/internal/device-session/model/DeviceSession.test.js +1 -1
  36. package/lib/esm/src/internal/device-session/model/DeviceSession.test.js.map +2 -2
  37. package/lib/types/src/api/device-action/DeviceAction.d.ts +2 -0
  38. package/lib/types/src/api/device-action/DeviceAction.d.ts.map +1 -1
  39. package/lib/types/src/api/device-action/__test-utils__/makeInternalApi.d.ts.map +1 -1
  40. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts +4 -1
  41. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts.map +1 -1
  42. package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts +10 -1
  43. package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts.map +1 -1
  44. package/lib/types/src/api/index.d.ts +4 -0
  45. package/lib/types/src/api/index.d.ts.map +1 -1
  46. package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.d.ts +12 -0
  47. package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.d.ts.map +1 -0
  48. package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.test.d.ts +2 -0
  49. package/lib/types/src/api/logger-publisher/utils/noopLoggerFactory.test.d.ts.map +1 -0
  50. package/lib/types/src/internal/device-session/model/DeviceSession.d.ts +1 -0
  51. package/lib/types/src/internal/device-session/model/DeviceSession.d.ts.map +1 -1
  52. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  53. package/package.json +2 -2
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/internal/device-session/model/DeviceSession.test.ts"],
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 });\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,IAAAA,EAA4B,qBAC5BC,EAAwC,gBACxCC,EAA4B,0BAI5BC,EAGO,4CACPC,EAA6B,oCAG7BC,EAAuC,kDAGvCC,EAA2C,8DAE3CC,EAA8C,4EAI9CC,EAGO,2BAEP,SAAS,gBAAiB,IAAM,CAC9B,IAAIC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACJ,MAAMC,KAAsB,8BAA2B,EAEvD,WAAW,IAAM,CAEfP,EAAa,IAAI,gCAA8B,CAAC,EAAG,qBAAqB,EACxEC,EAAoB,GAAG,GAAG,IAAMD,CAAU,EAG1CE,EAAiB,CACf,WAAY,GAAG,GAAG,EAClB,cAAe,GAAG,GAAG,EACrB,mBAAoB,GAAG,GAAG,EAC1B,kBAAmB,GAAG,GAAG,CAC3B,EAEAC,EAAoB,CAClB,aAAc,GAAG,GAAG,EACpB,kBAAmB,GAAG,GAAG,EACzB,UAAW,GAAG,GAAG,EACjB,eAAgB,GAAG,GAAG,EACtB,WAAY,GAAG,GAAG,EAClB,aAAc,GAAG,GAAG,CACtB,EAGAC,EAAyB,CACvB,QAAS,GAAG,GAAG,EAAE,gBAAgB,CAC/B,cAAY,MAA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AAC,EAED,GAAG,wCAAyC,IAAM,CAEhD,MAAMP,EAAa,GAAG,GAAG,EACnBC,EAAU,IAAI,UAEpBpB,EAAuB,QAAQ,gBAAgB,CAC7C,WAAYoB,EAAQ,aAAa,EACjC,OAAQD,CACV,CAAC,EAGD,KAAM,CAAE,OAAAU,CAAO,EAAIlC,EAAc,oBAAoB+B,CAAgB,EACrEG,EAAO,EAGP,OAAOV,CAAU,EAAE,iBAAiB,CACtC,CAAC,CACH,CAAC,EAED,SAAS,QAAS,IAAM,CACtB,GAAG,oDAAqD,IAAM,CAE5DxB,EAAgB,IAAI,gBAClB,CAAE,gBAAiBQ,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,KAAK,eAAa,aAAa,EAC1D,OAAOyB,CAAU,EAAE,KAAK,EAAI,CAC9B,CAAC,CACH,CAAC,CACH,CAAC",
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,IAAAA,EAA4B,qBAC5BC,EAAwC,gBACxCC,EAA4B,0BAI5BC,EAGO,4CACPC,EAA6B,oCAG7BC,EAAuC,kDAGvCC,EAA2C,8DAE3CC,EAA8C,4EAI9CC,EAGO,2BAEP,SAAS,gBAAiB,IAAM,CAC9B,IAAIC,EACAC,EACAC,EACAC,EACAC,EACAC,EAC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,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["import_purify_ts", "import_rxjs", "import_operators", "import_CommandResult", "import_DeviceStatus", "import_DeviceSessionState", "import_TransportConnectedDevice", "import_DefaultLoggerPublisherService", "import_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
  }
@@ -64,5 +64,5 @@
64
64
  "watch:builds": "pnpm ldmk-tool watch --entryPoints index.ts,src/**/*.ts --tsconfig tsconfig.prod.json",
65
65
  "watch:types": "concurrently \"tsc --watch -p tsconfig.prod.json\" \"tsc-alias --watch -p tsconfig.prod.json\""
66
66
  },
67
- "version": "0.0.0-develop-20260209001501"
67
+ "version": "0.0.0-develop-20260211001836"
68
68
  }
@@ -1,2 +1,2 @@
1
- const e=vi.fn(),n=vi.fn(),t=vi.fn(),i=vi.fn(),c=vi.fn(),o=vi.fn(),s=vi.fn(),a=vi.fn();function v(){return{sendApdu:e,sendCommand:n,getDeviceModel:t,getDeviceSessionState:i,getDeviceSessionStateObservable:c,setDeviceSessionState:o,getManagerApiService:s,getSecureChannelService:a}}export{v as makeDeviceActionInternalApiMock};
1
+ import{DefaultLoggerPublisherService as t}from"../../../internal/logger-publisher/service/DefaultLoggerPublisherService";const n=vi.fn(),o=vi.fn(),i=vi.fn(),c=vi.fn(),s=vi.fn(),r=vi.fn(),a=vi.fn(),v=vi.fn(),S=vi.fn(e=>new t([],e));function M(){return{sendApdu:n,sendCommand:o,getDeviceModel:i,getDeviceSessionState:c,getDeviceSessionStateObservable:s,setDeviceSessionState:r,getManagerApiService:a,getSecureChannelService:v,loggerFactory:S}}export{M as makeDeviceActionInternalApiMock};
2
2
  //# sourceMappingURL=makeInternalApi.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/device-action/__test-utils__/makeInternalApi.ts"],
4
- "sourcesContent": ["import { type Mocked } from \"vitest\";\n\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\n\nconst sendApduMock = vi.fn();\nconst sendCommandMock = vi.fn();\nconst apiGetDeviceModelMock = vi.fn();\nconst apiGetDeviceSessionStateMock = vi.fn();\nconst apiGetDeviceSessionStateObservableMock = vi.fn();\nconst setDeviceSessionStateMock = vi.fn();\nconst getManagerApiServiceMock = vi.fn();\nconst getSecureChannelServiceMock = vi.fn();\n\nexport function makeDeviceActionInternalApiMock(): Mocked<InternalApi> {\n return {\n sendApdu: sendApduMock,\n sendCommand: sendCommandMock,\n getDeviceModel: apiGetDeviceModelMock,\n getDeviceSessionState: apiGetDeviceSessionStateMock,\n getDeviceSessionStateObservable: apiGetDeviceSessionStateObservableMock,\n setDeviceSessionState: setDeviceSessionStateMock,\n getManagerApiService: getManagerApiServiceMock,\n getSecureChannelService: getSecureChannelServiceMock,\n };\n}\n"],
5
- "mappings": "AAIA,MAAMA,EAAe,GAAG,GAAG,EACrBC,EAAkB,GAAG,GAAG,EACxBC,EAAwB,GAAG,GAAG,EAC9BC,EAA+B,GAAG,GAAG,EACrCC,EAAyC,GAAG,GAAG,EAC/CC,EAA4B,GAAG,GAAG,EAClCC,EAA2B,GAAG,GAAG,EACjCC,EAA8B,GAAG,GAAG,EAEnC,SAASC,GAAuD,CACrE,MAAO,CACL,SAAUR,EACV,YAAaC,EACb,eAAgBC,EAChB,sBAAuBC,EACvB,gCAAiCC,EACjC,sBAAuBC,EACvB,qBAAsBC,EACtB,wBAAyBC,CAC3B,CACF",
6
- "names": ["sendApduMock", "sendCommandMock", "apiGetDeviceModelMock", "apiGetDeviceSessionStateMock", "apiGetDeviceSessionStateObservableMock", "setDeviceSessionStateMock", "getManagerApiServiceMock", "getSecureChannelServiceMock", "makeDeviceActionInternalApiMock"]
4
+ "sourcesContent": ["import { type Mocked } from \"vitest\";\n\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { DefaultLoggerPublisherService } from \"@internal/logger-publisher/service/DefaultLoggerPublisherService\";\n\nconst sendApduMock = vi.fn();\nconst sendCommandMock = vi.fn();\nconst apiGetDeviceModelMock = vi.fn();\nconst apiGetDeviceSessionStateMock = vi.fn();\nconst apiGetDeviceSessionStateObservableMock = vi.fn();\nconst setDeviceSessionStateMock = vi.fn();\nconst getManagerApiServiceMock = vi.fn();\nconst getSecureChannelServiceMock = vi.fn();\nconst loggerFactoryMock = vi.fn(\n (tag) => new DefaultLoggerPublisherService([], tag),\n);\n\nexport function makeDeviceActionInternalApiMock(): Mocked<InternalApi> {\n return {\n sendApdu: sendApduMock,\n sendCommand: sendCommandMock,\n getDeviceModel: apiGetDeviceModelMock,\n getDeviceSessionState: apiGetDeviceSessionStateMock,\n getDeviceSessionStateObservable: apiGetDeviceSessionStateObservableMock,\n setDeviceSessionState: setDeviceSessionStateMock,\n getManagerApiService: getManagerApiServiceMock,\n getSecureChannelService: getSecureChannelServiceMock,\n loggerFactory: loggerFactoryMock,\n };\n}\n"],
5
+ "mappings": "AAGA,OAAS,iCAAAA,MAAqC,mEAE9C,MAAMC,EAAe,GAAG,GAAG,EACrBC,EAAkB,GAAG,GAAG,EACxBC,EAAwB,GAAG,GAAG,EAC9BC,EAA+B,GAAG,GAAG,EACrCC,EAAyC,GAAG,GAAG,EAC/CC,EAA4B,GAAG,GAAG,EAClCC,EAA2B,GAAG,GAAG,EACjCC,EAA8B,GAAG,GAAG,EACpCC,EAAoB,GAAG,GAC1BC,GAAQ,IAAIV,EAA8B,CAAC,EAAGU,CAAG,CACpD,EAEO,SAASC,GAAuD,CACrE,MAAO,CACL,SAAUV,EACV,YAAaC,EACb,eAAgBC,EAChB,sBAAuBC,EACvB,gCAAiCC,EACjC,sBAAuBC,EACvB,qBAAsBC,EACtB,wBAAyBC,EACzB,cAAeC,CACjB,CACF",
6
+ "names": ["DefaultLoggerPublisherService", "sendApduMock", "sendCommandMock", "apiGetDeviceModelMock", "apiGetDeviceSessionStateMock", "apiGetDeviceSessionStateObservableMock", "setDeviceSessionStateMock", "getManagerApiServiceMock", "getSecureChannelServiceMock", "loggerFactoryMock", "tag", "makeDeviceActionInternalApiMock"]
7
7
  }
@@ -1,2 +1,2 @@
1
- var s=(l=>(l.None="none",l.UnlockDevice="unlock-device",l.AllowSecureConnection="allow-secure-connection",l.ConfirmOpenApp="confirm-open-app",l.SignTransaction="sign-transaction",l.SignTypedData="sign-typed-data",l.AllowListApps="allow-list-apps",l.VerifyAddress="verify-address",l.SignPersonalMessage="sign-personal-message",l.SignDelegationAuthorization="sign-delegation-authorization",l.Web3ChecksOptIn="web3-checks-opt-in",l.VerifySafeAddress="verify-safe-address",l.RegisterWallet="register-wallet",l))(s||{});export{s as UserInteractionRequired};
1
+ var m=(o=>(o.None="none",o.UnlockDevice="unlock-device",o.AllowSecureConnection="allow-secure-connection",o.ConfirmOpenApp="confirm-open-app",o.SignTransaction="sign-transaction",o.SignTypedData="sign-typed-data",o.AllowListApps="allow-list-apps",o.VerifyAddress="verify-address",o.SignPersonalMessage="sign-personal-message",o.SignDelegationAuthorization="sign-delegation-authorization",o.Web3ChecksOptIn="web3-checks-opt-in",o.VerifySafeAddress="verify-safe-address",o.RegisterWallet="register-wallet",o.ConfirmLoadImage="confirm-load-image",o.ConfirmCommitImage="confirm-commit-image",o.ConfirmRemoveImage="confirm-remove-image",o))(m||{});export{m as UserInteractionRequired};
2
2
  //# sourceMappingURL=UserInteractionRequired.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/device-action/model/UserInteractionRequired.ts"],
4
- "sourcesContent": ["/**\n * The user interaction required on the device to move further in a device action.\n * This is used to inform the users about the action they need to take on the device.\n */\nexport enum UserInteractionRequired {\n None = \"none\",\n UnlockDevice = \"unlock-device\",\n AllowSecureConnection = \"allow-secure-connection\",\n ConfirmOpenApp = \"confirm-open-app\",\n SignTransaction = \"sign-transaction\",\n SignTypedData = \"sign-typed-data\",\n AllowListApps = \"allow-list-apps\",\n VerifyAddress = \"verify-address\",\n SignPersonalMessage = \"sign-personal-message\",\n SignDelegationAuthorization = \"sign-delegation-authorization\",\n Web3ChecksOptIn = \"web3-checks-opt-in\",\n VerifySafeAddress = \"verify-safe-address\",\n RegisterWallet = \"register-wallet\",\n}\n"],
5
- "mappings": "AAIO,IAAKA,OACVA,EAAA,KAAO,OACPA,EAAA,aAAe,gBACfA,EAAA,sBAAwB,0BACxBA,EAAA,eAAiB,mBACjBA,EAAA,gBAAkB,mBAClBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,iBAChBA,EAAA,oBAAsB,wBACtBA,EAAA,4BAA8B,gCAC9BA,EAAA,gBAAkB,qBAClBA,EAAA,kBAAoB,sBACpBA,EAAA,eAAiB,kBAbPA,OAAA",
4
+ "sourcesContent": ["/**\n * The user interaction required on the device to move further in a device action.\n * This is used to inform the users about the action they need to take on the device.\n */\nexport enum UserInteractionRequired {\n None = \"none\",\n UnlockDevice = \"unlock-device\",\n AllowSecureConnection = \"allow-secure-connection\",\n ConfirmOpenApp = \"confirm-open-app\",\n SignTransaction = \"sign-transaction\",\n SignTypedData = \"sign-typed-data\",\n AllowListApps = \"allow-list-apps\",\n VerifyAddress = \"verify-address\",\n SignPersonalMessage = \"sign-personal-message\",\n SignDelegationAuthorization = \"sign-delegation-authorization\",\n Web3ChecksOptIn = \"web3-checks-opt-in\",\n VerifySafeAddress = \"verify-safe-address\",\n RegisterWallet = \"register-wallet\",\n ConfirmLoadImage = \"confirm-load-image\",\n ConfirmCommitImage = \"confirm-commit-image\",\n ConfirmRemoveImage = \"confirm-remove-image\",\n}\n"],
5
+ "mappings": "AAIO,IAAKA,OACVA,EAAA,KAAO,OACPA,EAAA,aAAe,gBACfA,EAAA,sBAAwB,0BACxBA,EAAA,eAAiB,mBACjBA,EAAA,gBAAkB,mBAClBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,iBAChBA,EAAA,oBAAsB,wBACtBA,EAAA,4BAA8B,gCAC9BA,EAAA,gBAAkB,qBAClBA,EAAA,kBAAoB,sBACpBA,EAAA,eAAiB,kBACjBA,EAAA,iBAAmB,qBACnBA,EAAA,mBAAqB,uBACrBA,EAAA,mBAAqB,uBAhBXA,OAAA",
6
6
  "names": ["UserInteractionRequired"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{Observable as h,ReplaySubject as d,share as b}from"rxjs";import{createActor as I}from"xstate";import{DeviceActionStatus as o}from"../../device-action/model/DeviceActionState";class D{input;inspect=!1;logger;constructor(e){this.input=e.input,this.inspect=!!e.inspect,this.logger=e.logger}_execute(e){const r=this.makeStateMachine(e);return this._subscribeToStateMachine(r)}_subscribeToStateMachine(e){const r=I(e,{input:this.input}),t=new d;let c=!1;const p=a=>{const{context:n,status:u,output:m,error:S}=a;if(this.logger&&!c&&(c=!0,this.logger.debug("[XStateDeviceAction] Input",{data:{input:n.input}})),this.logger&&u==="active"){const i=typeof a.value=="string"?a.value:JSON.stringify(a.value);this.logger.debug(`[XStateDeviceAction] State: ${i}`,{data:{internalState:n._internalState}})}switch(u){case"active":t.next({status:o.Pending,intermediateValue:n.intermediateValue});break;case"done":m.caseOf({Left:i=>{t.next({status:o.Error,error:i})},Right:i=>{t.next({status:o.Completed,output:i})}}),t.complete();break;case"error":t.error(S),t.complete();break;case"stopped":t.next({status:o.Stopped}),t.complete();break;default:this._exhaustiveMatchingGuard(u)}},l=new h(a=>{const n=t.subscribe(a);return()=>{s.unsubscribe(),n.unsubscribe(),r.stop()}}),s=r.subscribe(p);return r.start(),{observable:l.pipe(b()),cancel:()=>{r.stop(),s.unsubscribe(),p(r.getSnapshot())}}}_exhaustiveMatchingGuard(e){throw console.log("_exhaustiveMatchingGuard status",e),new Error(`Unhandled status: ${e}`)}}export{D as XStateDeviceAction};
1
+ import{Observable as S,ReplaySubject as m,share as d}from"rxjs";import{createActor as y}from"xstate";import{DeviceActionStatus as o}from"../../device-action/model/DeviceActionState";import{noopLoggerFactory as b}from"../../logger-publisher/utils/noopLoggerFactory";class f{input;inspect=!1;logger;loggerFactory;constructor(e){this.input=e.input,this.inspect=!!e.inspect,this.logger=e.logger,this.loggerFactory=e.loggerFactory}getLoggerFactory(e){return this.loggerFactory??e.loggerFactory??b}_execute(e){const t=this.makeStateMachine(e);return!this.logger&&t.id&&(this.logger=this.getLoggerFactory(e)(t.id)),this._subscribeToStateMachine(t)}_subscribeToStateMachine(e){const t=y(e,{input:this.input}),r=new m;let u=!1;const s=a=>{const{context:n,status:c,output:g,error:h}=a;if(this.logger&&!u&&(u=!0,this.logger.debug("[XStateDeviceAction] Input",{data:{input:n.input}})),this.logger&&c==="active"){const i=typeof a.value=="string"?a.value:JSON.stringify(a.value);this.logger.debug(`[XStateDeviceAction] State: ${i}`,{data:{internalState:n._internalState}})}switch(c){case"active":r.next({status:o.Pending,intermediateValue:n.intermediateValue});break;case"done":g.caseOf({Left:i=>{r.next({status:o.Error,error:i})},Right:i=>{r.next({status:o.Completed,output:i})}}),r.complete();break;case"error":r.error(h),r.complete();break;case"stopped":r.next({status:o.Stopped}),r.complete();break;default:this._exhaustiveMatchingGuard(c)}},l=new S(a=>{const n=r.subscribe(a);return()=>{p.unsubscribe(),n.unsubscribe(),t.stop()}}),p=t.subscribe(s);return t.start(),{observable:l.pipe(d()),cancel:()=>{t.stop(),p.unsubscribe(),s(t.getSnapshot())}}}_exhaustiveMatchingGuard(e){throw console.log("_exhaustiveMatchingGuard status",e),new Error(`Unhandled status: ${e}`)}}export{f as XStateDeviceAction};
2
2
  //# sourceMappingURL=XStateDeviceAction.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/device-action/xstate-utils/XStateDeviceAction.ts"],
4
- "sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { Observable, ReplaySubject, share } from \"rxjs\";\nimport {\n createActor,\n type SnapshotFrom,\n type StateMachine,\n type StateSchema,\n} from \"xstate\";\n\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n type InternalApi,\n} from \"@api/device-action/DeviceAction\";\nimport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nimport { type DmkError } from \"@api/Error\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\n\nimport { type StateMachineTypes } from \"./StateMachineTypes\";\n\nexport type DeviceActionStateMachine<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n InternalState,\n> = StateMachine<\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"context\"], // context\n /**\n * The following usages `any` are OK because this is just a wrapper around the\n * state machine and we are not directly going to use these types.\n */\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any, // event\n any, // children\n any, // actor\n any, // action\n any, // guard\n any, // delay\n any, // state value\n any, // tag\n /* eslint-enable @typescript-eslint/no-explicit-any */\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"input\"],\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"output\"],\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n any,\n /* eslint-enable @typescript-eslint/no-explicit-any */\n StateSchema\n>;\n\n/**\n * A DeviceAction that uses an XState state machine to execute.\n * It maps the state machine snapshots to the DeviceActionState.\n * This class is abstract and should be extended to implement the state machine.\n */\nexport abstract class XStateDeviceAction<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n InternalState,\n> implements DeviceAction<Output, Input, Error, IntermediateValue>\n{\n readonly input: Input;\n readonly inspect: boolean = false;\n protected readonly logger?: LoggerPublisherService;\n\n /**\n *\n * @param input The input for the DeviceAction\n * @param inspect If true, the state machine will be inspected in the browser\n * @param logger Optional logger for debugging. If provided, input and internal state will be logged on state transitions.\n */\n constructor(args: {\n input: Input;\n inspect?: boolean;\n logger?: LoggerPublisherService;\n }) {\n this.input = args.input;\n this.inspect = Boolean(args.inspect);\n this.logger = args.logger;\n }\n\n protected abstract makeStateMachine(\n internalAPI: InternalApi,\n ): DeviceActionStateMachine<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >;\n\n _execute(\n internalApi: InternalApi,\n ): ExecuteDeviceActionReturnType<Output, Error, IntermediateValue> {\n const stateMachine = this.makeStateMachine(internalApi);\n return this._subscribeToStateMachine(stateMachine);\n }\n\n protected _subscribeToStateMachine(\n stateMachine: DeviceActionStateMachine<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >,\n ): ExecuteDeviceActionReturnType<Output, Error, IntermediateValue> {\n const actor = createActor(stateMachine, {\n input: this.input,\n // optional inspector for debugging\n // inspect: this.inspect ? createBrowserInspector().inspect : undefined,\n });\n\n /**\n * Using a ReplaySubject is important because the first snapshots might be\n * emitted before the observable is subscribed (if the machine goes through\n * those states fully synchronously).\n * This way, we ensure that the subscriber always receives the latest snapshot.\n * */\n const subject = new ReplaySubject<\n DeviceActionState<Output, Error, IntermediateValue>\n >();\n\n let hasLoggedInput = false;\n\n const handleActorSnapshot = (\n snapshot: SnapshotFrom<typeof stateMachine>,\n ) => {\n const { context, status, output, error } = snapshot;\n\n // Log input once at the beginning\n if (this.logger && !hasLoggedInput) {\n hasLoggedInput = true;\n this.logger.debug(\"[XStateDeviceAction] Input\", {\n data: { input: context.input },\n });\n }\n\n // Log internal state on each state transition\n if (this.logger && status === \"active\") {\n const stateValue =\n typeof snapshot.value === \"string\"\n ? snapshot.value\n : JSON.stringify(snapshot.value);\n this.logger.debug(`[XStateDeviceAction] State: ${stateValue}`, {\n data: { internalState: context._internalState },\n });\n }\n\n switch (status) {\n case \"active\":\n subject.next({\n status: DeviceActionStatus.Pending,\n intermediateValue: context.intermediateValue,\n });\n break;\n case \"done\":\n output.caseOf({\n Left: (err) => {\n subject.next({\n status: DeviceActionStatus.Error,\n error: err,\n });\n },\n Right: (result) => {\n subject.next({\n status: DeviceActionStatus.Completed,\n output: result,\n });\n },\n });\n subject.complete();\n break;\n case \"error\":\n // this is an error in the execution of the state machine, it should not happen\n subject.error(error);\n subject.complete();\n break;\n case \"stopped\":\n subject.next({\n status: DeviceActionStatus.Stopped,\n });\n subject.complete();\n break;\n default:\n this._exhaustiveMatchingGuard(status);\n }\n };\n\n const observable = new Observable<\n DeviceActionState<Output, Error, IntermediateValue>\n >((subscriber) => {\n const subjectSubscription = subject.subscribe(subscriber);\n return () => {\n actorSubscription.unsubscribe();\n subjectSubscription.unsubscribe();\n actor.stop(); // stop the actor when the observable is unsubscribed\n };\n });\n\n const actorSubscription = actor.subscribe(handleActorSnapshot);\n actor.start();\n\n return {\n observable: observable.pipe(share()), // share to garantee that once there is no more observer, the actor is stopped\n cancel: () => {\n actor.stop();\n actorSubscription.unsubscribe();\n handleActorSnapshot(actor.getSnapshot());\n },\n };\n }\n\n private _exhaustiveMatchingGuard(status: never): never {\n console.log(\"_exhaustiveMatchingGuard status\", status);\n throw new Error(`Unhandled status: ${status}`);\n }\n}\n"],
5
- "mappings": "AACA,OAAS,cAAAA,EAAY,iBAAAC,EAAe,SAAAC,MAAa,OACjD,OACE,eAAAC,MAIK,SAQP,OAEE,sBAAAC,MACK,6CA4DA,MAAeC,CAOtB,CACW,MACA,QAAmB,GACT,OAQnB,YAAYC,EAIT,CACD,KAAK,MAAQA,EAAK,MAClB,KAAK,QAAU,EAAQA,EAAK,QAC5B,KAAK,OAASA,EAAK,MACrB,CAYA,SACEC,EACiE,CACjE,MAAMC,EAAe,KAAK,iBAAiBD,CAAW,EACtD,OAAO,KAAK,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xD,MAAO,IAAM,CACXE,EAAkB,YAAY,EAC9BD,EAAoB,YAAY,EAChCd,EAAM,KAAK,CACb,CACF,CAAC,EAEKe,EAAoBf,EAAM,UAAUG,CAAmB,EAC7D,OAAAH,EAAM,MAAM,EAEL,CACL,WAAYY,EAAW,KAAKnB,EAAM,CAAC,EACnC,OAAQ,IAAM,CACZO,EAAM,KAAK,EACXe,EAAkB,YAAY,EAC9BZ,EAAoBH,EAAM,YAAY,CAAC,CACzC,CACF,CACF,CAEQ,yBAAyBM,EAAsB,CACrD,cAAQ,IAAI,kCAAmCA,CAAM,EAC/C,IAAI,MAAM,qBAAqBA,CAAM,EAAE,CAC/C,CACF",
6
- "names": ["Observable", "ReplaySubject", "share", "createActor", "DeviceActionStatus", "XStateDeviceAction", "args", "internalApi", "stateMachine", "actor", "subject", "hasLoggedInput", "handleActorSnapshot", "snapshot", "context", "status", "output", "error", "stateValue", "err", "result", "observable", "subscriber", "subjectSubscription", "actorSubscription"]
4
+ "sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { Observable, ReplaySubject, share } from \"rxjs\";\nimport {\n createActor,\n type SnapshotFrom,\n type StateMachine,\n type StateSchema,\n} from \"xstate\";\n\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n type InternalApi,\n} from \"@api/device-action/DeviceAction\";\nimport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nimport { type DmkError } from \"@api/Error\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { noopLoggerFactory } from \"@api/logger-publisher/utils/noopLoggerFactory\";\n\nimport { type StateMachineTypes } from \"./StateMachineTypes\";\n\nexport type DeviceActionStateMachine<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n InternalState,\n> = StateMachine<\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"context\"], // context\n /**\n * The following usages `any` are OK because this is just a wrapper around the\n * state machine and we are not directly going to use these types.\n */\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any, // event\n any, // children\n any, // actor\n any, // action\n any, // guard\n any, // delay\n any, // state value\n any, // tag\n /* eslint-enable @typescript-eslint/no-explicit-any */\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"input\"],\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"output\"],\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n any,\n /* eslint-enable @typescript-eslint/no-explicit-any */\n StateSchema\n>;\n\n/**\n * A DeviceAction that uses an XState state machine to execute.\n * It maps the state machine snapshots to the DeviceActionState.\n * This class is abstract and should be extended to implement the state machine.\n */\nexport abstract class XStateDeviceAction<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n InternalState,\n> implements DeviceAction<Output, Input, Error, IntermediateValue>\n{\n readonly input: Input;\n readonly inspect: boolean = false;\n protected logger?: LoggerPublisherService;\n protected loggerFactory?: (tag: string) => LoggerPublisherService;\n\n /**\n *\n * @param input The input for the DeviceAction\n * @param inspect If true, the state machine will be inspected in the browser\n * @param logger Optional logger for debugging. If provided, input and internal state will be logged on state transitions.\n * @param loggerFactory Optional logger factory for creating loggers with prefixed tags. Takes precedence over logger.\n */\n constructor(args: {\n input: Input;\n inspect?: boolean;\n logger?: LoggerPublisherService;\n loggerFactory?: (tag: string) => LoggerPublisherService;\n }) {\n this.input = args.input;\n this.inspect = Boolean(args.inspect);\n this.logger = args.logger;\n this.loggerFactory = args.loggerFactory;\n }\n\n /**\n * Returns the logger factory to use for creating loggers.\n * Prefers the instance loggerFactory, then internalApi.loggerFactory,\n * and falls back to a no-op logger factory if neither is available.\n */\n protected getLoggerFactory(\n internalApi: InternalApi,\n ): (tag: string) => LoggerPublisherService {\n return this.loggerFactory ?? internalApi.loggerFactory ?? noopLoggerFactory;\n }\n\n protected abstract makeStateMachine(\n internalAPI: InternalApi,\n ): DeviceActionStateMachine<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >;\n\n _execute(\n internalApi: InternalApi,\n ): ExecuteDeviceActionReturnType<Output, Error, IntermediateValue> {\n const stateMachine = this.makeStateMachine(internalApi);\n\n // Create logger from machine ID if not explicitly provided\n // Prefer loggerFactory (prefixed) over internalApi.loggerFactory (unprefixed)\n if (!this.logger && stateMachine.id) {\n this.logger = this.getLoggerFactory(internalApi)(stateMachine.id);\n }\n\n return this._subscribeToStateMachine(stateMachine);\n }\n\n protected _subscribeToStateMachine(\n stateMachine: DeviceActionStateMachine<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >,\n ): ExecuteDeviceActionReturnType<Output, Error, IntermediateValue> {\n const actor = createActor(stateMachine, {\n input: this.input,\n // optional inspector for debugging\n // inspect: this.inspect ? createBrowserInspector().inspect : undefined,\n });\n\n /**\n * Using a ReplaySubject is important because the first snapshots might be\n * emitted before the observable is subscribed (if the machine goes through\n * those states fully synchronously).\n * This way, we ensure that the subscriber always receives the latest snapshot.\n * */\n const subject = new ReplaySubject<\n DeviceActionState<Output, Error, IntermediateValue>\n >();\n\n let hasLoggedInput = false;\n\n const handleActorSnapshot = (\n snapshot: SnapshotFrom<typeof stateMachine>,\n ) => {\n const { context, status, output, error } = snapshot;\n\n // Log input once at the beginning\n if (this.logger && !hasLoggedInput) {\n hasLoggedInput = true;\n this.logger.debug(\"[XStateDeviceAction] Input\", {\n data: { input: context.input },\n });\n }\n\n // Log internal state on each state transition\n if (this.logger && status === \"active\") {\n const stateValue =\n typeof snapshot.value === \"string\"\n ? snapshot.value\n : JSON.stringify(snapshot.value);\n this.logger.debug(`[XStateDeviceAction] State: ${stateValue}`, {\n data: { internalState: context._internalState },\n });\n }\n\n switch (status) {\n case \"active\":\n subject.next({\n status: DeviceActionStatus.Pending,\n intermediateValue: context.intermediateValue,\n });\n break;\n case \"done\":\n output.caseOf({\n Left: (err) => {\n subject.next({\n status: DeviceActionStatus.Error,\n error: err,\n });\n },\n Right: (result) => {\n subject.next({\n status: DeviceActionStatus.Completed,\n output: result,\n });\n },\n });\n subject.complete();\n break;\n case \"error\":\n // this is an error in the execution of the state machine, it should not happen\n subject.error(error);\n subject.complete();\n break;\n case \"stopped\":\n subject.next({\n status: DeviceActionStatus.Stopped,\n });\n subject.complete();\n break;\n default:\n this._exhaustiveMatchingGuard(status);\n }\n };\n\n const observable = new Observable<\n DeviceActionState<Output, Error, IntermediateValue>\n >((subscriber) => {\n const subjectSubscription = subject.subscribe(subscriber);\n return () => {\n actorSubscription.unsubscribe();\n subjectSubscription.unsubscribe();\n actor.stop(); // stop the actor when the observable is unsubscribed\n };\n });\n\n const actorSubscription = actor.subscribe(handleActorSnapshot);\n actor.start();\n\n return {\n observable: observable.pipe(share()), // share to garantee that once there is no more observer, the actor is stopped\n cancel: () => {\n actor.stop();\n actorSubscription.unsubscribe();\n handleActorSnapshot(actor.getSnapshot());\n },\n };\n }\n\n private _exhaustiveMatchingGuard(status: never): never {\n console.log(\"_exhaustiveMatchingGuard status\", status);\n throw new Error(`Unhandled status: ${status}`);\n }\n}\n"],
5
+ "mappings": "AACA,OAAS,cAAAA,EAAY,iBAAAC,EAAe,SAAAC,MAAa,OACjD,OACE,eAAAC,MAIK,SAQP,OAEE,sBAAAC,MACK,6CAGP,OAAS,qBAAAC,MAAyB,gDA0D3B,MAAeC,CAOtB,CACW,MACA,QAAmB,GAClB,OACA,cASV,YAAYC,EAKT,CACD,KAAK,MAAQA,EAAK,MAClB,KAAK,QAAU,EAAQA,EAAK,QAC5B,KAAK,OAASA,EAAK,OACnB,KAAK,cAAgBA,EAAK,aAC5B,CAOU,iBACRC,EACyC,CACzC,OAAO,KAAK,eAAiBA,EAAY,eAAiBH,CAC5D,CAYA,SACEG,EACiE,CACjE,MAAMC,EAAe,KAAK,iBAAiBD,CAAW,EAItD,MAAI,CAAC,KAAK,QAAUC,EAAa,K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AAa,IAAItB,EAEpBuB,GAAe,CAChB,MAAMC,EAAsBb,EAAQ,UAAUY,CAAU,EACxD,MAAO,IAAM,CACXE,EAAkB,YAAY,EAC9BD,EAAoB,YAAY,EAChCd,EAAM,KAAK,CACb,CACF,CAAC,EAEKe,EAAoBf,EAAM,UAAUG,CAAmB,EAC7D,OAAAH,EAAM,MAAM,EAEL,CACL,WAAYY,EAAW,KAAKpB,EAAM,CAAC,EACnC,OAAQ,IAAM,CACZQ,EAAM,KAAK,EACXe,EAAkB,YAAY,EAC9BZ,EAAoBH,EAAM,YAAY,CAAC,CACzC,CACF,CACF,CAEQ,yBAAyBM,EAAsB,CACrD,cAAQ,IAAI,kCAAmCA,CAAM,EAC/C,IAAI,MAAM,qBAAqBA,CAAM,EAAE,CAC/C,CACF",
6
+ "names": ["Observable", "ReplaySubject", "share", "createActor", "DeviceActionStatus", "noopLoggerFactory", "XStateDeviceAction", "args", "internalApi", "stateMachine", "actor", "subject", "hasLoggedInput", "handleActorSnapshot", "snapshot", "context", "status", "output", "error", "stateValue", "err", "result", "observable", "subscriber", "subjectSubscription", "actorSubscription"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{Apdu as o}from"./apdu/model/Apdu";import{APDU_MAX_PAYLOAD as p,ApduBuilder as i}from"./apdu/utils/ApduBuilder";import{ApduParser as n}from"./apdu/utils/ApduParser";export*from"./apdu/utils/AppBuilderError";import{ByteArrayBuilder as f}from"./apdu/utils/ByteArrayBuilder";import{ByteArrayParser as x}from"./apdu/utils/ByteArrayParser";import{InvalidGetFirmwareMetadataResponseError as A,InvalidStatusWordError as D}from"./command/Errors";import{CommandResultFactory as u,CommandResultStatus as v,isSuccessCommandResult as S}from"./command/model/CommandResult";import{CloseAppCommand as C}from"./command/os/CloseAppCommand";import{GetAppAndVersionCommand as g}from"./command/os/GetAppAndVersionCommand";import{BatteryStatusType as B,GetBatteryStatusCommand as R}from"./command/os/GetBatteryStatusCommand";import{GetOsVersionCommand as M}from"./command/os/GetOsVersionCommand";import{ListAppsCommand as I}from"./command/os/ListAppsCommand";import{LoadCertificateCommand as b}from"./command/os/LoadCertificateCommand";import{OpenAppCommand as U}from"./command/os/OpenAppCommand";import{isCommandErrorCode as P}from"./command/utils/CommandErrors";import{CommandUtils as _}from"./command/utils/CommandUtils";import{GLOBAL_ERRORS as W,GlobalCommandError as w,GlobalCommandErrorHandler as H}from"./command/utils/GlobalCommandError";import{DeviceModel as N,DeviceModelId as X,LEDGER_VENDOR_ID as q}from"./device/DeviceModel";import{DeviceStatus as j}from"./device/DeviceStatus";import{DeviceActionStatus as J}from"./device-action/model/DeviceActionState";import{UserInteractionRequired as Z}from"./device-action/model/UserInteractionRequired";import{CallTaskInAppDeviceAction as ee}from"./device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction";import{AppAlreadyInstalledDAError as oe,DeviceLockedError as te,DeviceNotOnboardedError as pe,OutOfMemoryDAError as ie,RefusedByUserDAError as me,UnknownDAError as ne,UnsupportedFirmwareDAError as ae}from"./device-action/os/Errors";import{GetDeviceMetadataDeviceAction as fe}from"./device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction";import{GetDeviceStatusDeviceAction as xe}from"./device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction";import{GoToDashboardDeviceAction as Ae}from"./device-action/os/GoToDashboard/GoToDashboardDeviceAction";import{InstallOrUpdateAppsDeviceAction as le}from"./device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction";import{ListAppsDeviceAction as ve}from"./device-action/os/ListApps/ListAppsDeviceAction";import{ListAppsWithMetadataDeviceAction as ye}from"./device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction";import{OpenAppDeviceAction as Le}from"./device-action/os/OpenAppDeviceAction/OpenAppDeviceAction";import{OpenAppWithDependenciesDeviceAction as Ee}from"./device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction";import{SendCommandInAppDeviceAction as Re}from"./device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction";import{XStateDeviceAction as Me}from"./device-action/xstate-utils/XStateDeviceAction";import{StaticDeviceModelDataSource as Ie}from"./device-model/data/StaticDeviceModelDataSource";import{BleDeviceInfos as be}from"./device-model/model/BleDeviceInfos";import{TransportDeviceModel as Ue}from"./device-model/model/DeviceModel";import{ApduResponse as Pe}from"./device-session/ApduResponse";export*from"./device-session/data/FramerConst";import{DeviceSessionStateType as ke}from"./device-session/DeviceSessionState";import{GenuineCheckDeviceAction as we}from"./secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction";import{InstallAppDeviceAction as Ke}from"./secure-channel/device-action/InstallApp/InstallAppDeviceAction";import{ListInstalledAppsDeviceAction as Xe}from"./secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction";import{UninstallAppDeviceAction as Ye}from"./secure-channel/device-action/UninstallApp/UninstallAppDeviceAction";import{SecureChannelError as ze}from"../internal/secure-channel/model/Errors";import{defaultApduReceiverServiceStubBuilder as Qe}from"./device-session/service/DefaultApduReceiverService.stub";import{defaultApduSenderServiceStubBuilder as $e}from"./device-session/service/DefaultApduSenderService.stub";import{FramerUtils as rr}from"./device-session/utils/FramerUtils";import{DeviceManagementKit as tr}from"./DeviceManagementKit";import{DeviceManagementKitBuilder as ir}from"./DeviceManagementKitBuilder";export*from"./Error";import{LogLevel as ar}from"./logger-subscriber/model/LogLevel";import{ConsoleLogger as fr}from"./logger-subscriber/service/ConsoleLogger";import{DefaultLogTagFormatter as xr}from"./logger-subscriber/service/DefaultLogTagFormatter";import{WebLogsExporterLogger as Ar}from"./logger-subscriber/service/WebLogsExporterLogger";import{ConnectedDevice as lr}from"./transport/model/ConnectedDevice";import{DeviceConnectionStateMachine as vr}from"./transport/model/DeviceConnectionStateMachine";export*from"./transport/model/Errors";import{TransportConnectedDevice as Cr}from"./transport/model/TransportConnectedDevice";import{connectedDeviceStubBuilder as gr}from"./transport/model/TransportConnectedDevice.stub";export*from"./types";import{formatApduReceivedLog as Rr,formatApduSentLog as Gr}from"./utils/apduLogs";import{base64StringToBuffer as Or,isBase64String as Ir}from"./utils/Base64String";import{bufferToHexaString as br,hexaStringToBuffer as hr,isHexaString as Ur}from"./utils/HexaString";export{p as APDU_MAX_PAYLOAD,o as Apdu,i as ApduBuilder,n as ApduParser,Pe as ApduResponse,oe as AppAlreadyInstalledDAError,B as BatteryStatusType,be as BleDeviceInfos,f as ByteArrayBuilder,x as ByteArrayParser,ee as CallTaskInAppDeviceAction,C as CloseAppCommand,u as CommandResultFactory,v as CommandResultStatus,_ as CommandUtils,lr as ConnectedDevice,fr as ConsoleLogger,xr as DefaultLogTagFormatter,J as DeviceActionStatus,vr as DeviceConnectionStateMachine,te as DeviceLockedError,tr as DeviceManagementKit,ir as DeviceManagementKitBuilder,N as DeviceModel,X as DeviceModelId,pe as DeviceNotOnboardedError,ke as DeviceSessionStateType,j as DeviceStatus,rr as FramerUtils,W as GLOBAL_ERRORS,we as GenuineCheckDeviceAction,g as GetAppAndVersionCommand,R as GetBatteryStatusCommand,fe as GetDeviceMetadataDeviceAction,xe as GetDeviceStatusDeviceAction,M as GetOsVersionCommand,w as GlobalCommandError,H as GlobalCommandErrorHandler,Ae as GoToDashboardDeviceAction,Ke as InstallAppDeviceAction,le as InstallOrUpdateAppsDeviceAction,A as InvalidGetFirmwareMetadataResponseError,D as InvalidStatusWordError,q as LEDGER_VENDOR_ID,I as ListAppsCommand,ve as ListAppsDeviceAction,ye as ListAppsWithMetadataDeviceAction,Xe as ListInstalledAppsDeviceAction,b as LoadCertificateCommand,ar as LogLevel,U as OpenAppCommand,Le as OpenAppDeviceAction,Ee as OpenAppWithDependenciesDeviceAction,ie as OutOfMemoryDAError,me as RefusedByUserDAError,ze as SecureChannelError,Re as SendCommandInAppDeviceAction,Ie as StaticDeviceModelDataSource,Cr as TransportConnectedDevice,Ue as TransportDeviceModel,Ye as UninstallAppDeviceAction,ne as UnknownDAError,ae as UnsupportedFirmwareDAError,Z as UserInteractionRequired,Ar as WebLogsExporterLogger,Me as XStateDeviceAction,Or as base64StringToBuffer,br as bufferToHexaString,gr as connectedDeviceStubBuilder,Qe as defaultApduReceiverServiceStubBuilder,$e as defaultApduSenderServiceStubBuilder,Rr as formatApduReceivedLog,Gr as formatApduSentLog,hr as hexaStringToBuffer,Ir as isBase64String,P as isCommandErrorCode,Ur as isHexaString,S as isSuccessCommandResult};
1
+ import{Apdu as r}from"./apdu/model/Apdu";import{APDU_MAX_PAYLOAD as p,ApduBuilder as a}from"./apdu/utils/ApduBuilder";import{ApduParser as m}from"./apdu/utils/ApduParser";export*from"./apdu/utils/AppBuilderError";import{ByteArrayBuilder as c}from"./apdu/utils/ByteArrayBuilder";import{ByteArrayParser as f}from"./apdu/utils/ByteArrayParser";import{InvalidGetFirmwareMetadataResponseError as A,InvalidStatusWordError as D}from"./command/Errors";import{CommandResultFactory as l,CommandResultStatus as v,isSuccessCommandResult as S}from"./command/model/CommandResult";import{CloseAppCommand as y}from"./command/os/CloseAppCommand";import{GetAppAndVersionCommand as G}from"./command/os/GetAppAndVersionCommand";import{GetBackgroundImageSizeCommand as E,GetBackgroundImageSizeCommandError as B}from"./command/os/GetBackgroundImageSizeCommand";import{BatteryStatusType as R,GetBatteryStatusCommand as T}from"./command/os/GetBatteryStatusCommand";import{GetOsVersionCommand as O}from"./command/os/GetOsVersionCommand";import{ListAppsCommand as M}from"./command/os/ListAppsCommand";import{LoadCertificateCommand as k}from"./command/os/LoadCertificateCommand";import{OpenAppCommand as _}from"./command/os/OpenAppCommand";import{isCommandErrorCode as z}from"./command/utils/CommandErrors";import{CommandUtils as W}from"./command/utils/CommandUtils";import{GLOBAL_ERRORS as H,GlobalCommandError as K,GlobalCommandErrorHandler as N}from"./command/utils/GlobalCommandError";import{DeviceModel as X,DeviceModelId as Y,LEDGER_VENDOR_ID as j}from"./device/DeviceModel";import{DeviceStatus as Q}from"./device/DeviceStatus";import{DeviceActionStatus as $}from"./device-action/model/DeviceActionState";import{UserInteractionRequired as oe}from"./device-action/model/UserInteractionRequired";import{CallTaskInAppDeviceAction as te}from"./device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction";import{DEFAULT_UNLOCK_TIMEOUT_MS as ae}from"./device-action/os/Const";import{AppAlreadyInstalledDAError as me,DeviceLockedError as ne,DeviceNotOnboardedError as se,OutOfMemoryDAError as ce,RefusedByUserDAError as de,UnknownDAError as fe,UnsupportedFirmwareDAError as xe}from"./device-action/os/Errors";import{GetDeviceMetadataDeviceAction as De}from"./device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction";import{GetDeviceStatusDeviceAction as le}from"./device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction";import{GoToDashboardDeviceAction as Se}from"./device-action/os/GoToDashboard/GoToDashboardDeviceAction";import{InstallOrUpdateAppsDeviceAction as ye}from"./device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction";import{ListAppsDeviceAction as Ge}from"./device-action/os/ListApps/ListAppsDeviceAction";import{ListAppsWithMetadataDeviceAction as Ee}from"./device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction";import{OpenAppDeviceAction as Ie}from"./device-action/os/OpenAppDeviceAction/OpenAppDeviceAction";import{OpenAppWithDependenciesDeviceAction as Te}from"./device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction";import{SendCommandInAppDeviceAction as Oe}from"./device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction";import{XStateDeviceAction as Me}from"./device-action/xstate-utils/XStateDeviceAction";import{StaticDeviceModelDataSource as ke}from"./device-model/data/StaticDeviceModelDataSource";import{BleDeviceInfos as _e}from"./device-model/model/BleDeviceInfos";import{TransportDeviceModel as ze}from"./device-model/model/DeviceModel";import{ApduResponse as We}from"./device-session/ApduResponse";export*from"./device-session/data/FramerConst";import{DeviceSessionStateType as Ke}from"./device-session/DeviceSessionState";import{GenuineCheckDeviceAction as qe}from"./secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction";import{InstallAppDeviceAction as Ye}from"./secure-channel/device-action/InstallApp/InstallAppDeviceAction";import{ListInstalledAppsDeviceAction as Je}from"./secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction";import{UninstallAppDeviceAction as Ze}from"./secure-channel/device-action/UninstallApp/UninstallAppDeviceAction";import{SecureChannelError as eo}from"../internal/secure-channel/model/Errors";import{defaultApduReceiverServiceStubBuilder as ro}from"./device-session/service/DefaultApduReceiverService.stub";import{defaultApduSenderServiceStubBuilder as po}from"./device-session/service/DefaultApduSenderService.stub";import{FramerUtils as io}from"./device-session/utils/FramerUtils";import{DeviceManagementKit as no}from"./DeviceManagementKit";import{DeviceManagementKitBuilder as co}from"./DeviceManagementKitBuilder";export*from"./Error";import{noopLogger as Ao,noopLoggerFactory as Do}from"./logger-publisher/utils/noopLoggerFactory";import{LogLevel as lo}from"./logger-subscriber/model/LogLevel";import{ConsoleLogger as So}from"./logger-subscriber/service/ConsoleLogger";import{DefaultLogTagFormatter as yo}from"./logger-subscriber/service/DefaultLogTagFormatter";import{WebLogsExporterLogger as Go}from"./logger-subscriber/service/WebLogsExporterLogger";import{ConnectedDevice as Eo}from"./transport/model/ConnectedDevice";import{DeviceConnectionStateMachine as Io}from"./transport/model/DeviceConnectionStateMachine";export*from"./transport/model/Errors";import{TransportConnectedDevice as bo}from"./transport/model/TransportConnectedDevice";import{connectedDeviceStubBuilder as ho}from"./transport/model/TransportConnectedDevice.stub";export*from"./types";import{formatApduReceivedLog as ko,formatApduSentLog as Fo}from"./utils/apduLogs";import{base64StringToBuffer as Vo,isBase64String as zo}from"./utils/Base64String";import{bufferToHexaString as Wo,hexaStringToBuffer as wo,isHexaString as Ho}from"./utils/HexaString";export{p as APDU_MAX_PAYLOAD,r as Apdu,a as ApduBuilder,m as ApduParser,We as ApduResponse,me as AppAlreadyInstalledDAError,R as BatteryStatusType,_e as BleDeviceInfos,c as ByteArrayBuilder,f as ByteArrayParser,te as CallTaskInAppDeviceAction,y as CloseAppCommand,l as CommandResultFactory,v as CommandResultStatus,W as CommandUtils,Eo as ConnectedDevice,So as ConsoleLogger,ae as DEFAULT_UNLOCK_TIMEOUT_MS,yo as DefaultLogTagFormatter,$ as DeviceActionStatus,Io as DeviceConnectionStateMachine,ne as DeviceLockedError,no as DeviceManagementKit,co as DeviceManagementKitBuilder,X as DeviceModel,Y as DeviceModelId,se as DeviceNotOnboardedError,Ke as DeviceSessionStateType,Q as DeviceStatus,io as FramerUtils,H as GLOBAL_ERRORS,qe as GenuineCheckDeviceAction,G as GetAppAndVersionCommand,E as GetBackgroundImageSizeCommand,B as GetBackgroundImageSizeCommandError,T as GetBatteryStatusCommand,De as GetDeviceMetadataDeviceAction,le as GetDeviceStatusDeviceAction,O as GetOsVersionCommand,K as GlobalCommandError,N as GlobalCommandErrorHandler,Se as GoToDashboardDeviceAction,Ye as InstallAppDeviceAction,ye as InstallOrUpdateAppsDeviceAction,A as InvalidGetFirmwareMetadataResponseError,D as InvalidStatusWordError,j as LEDGER_VENDOR_ID,M as ListAppsCommand,Ge as ListAppsDeviceAction,Ee as ListAppsWithMetadataDeviceAction,Je as ListInstalledAppsDeviceAction,k as LoadCertificateCommand,lo as LogLevel,_ as OpenAppCommand,Ie as OpenAppDeviceAction,Te as OpenAppWithDependenciesDeviceAction,ce as OutOfMemoryDAError,de as RefusedByUserDAError,eo as SecureChannelError,Oe as SendCommandInAppDeviceAction,ke as StaticDeviceModelDataSource,bo as TransportConnectedDevice,ze as TransportDeviceModel,Ze as UninstallAppDeviceAction,fe as UnknownDAError,xe as UnsupportedFirmwareDAError,oe as UserInteractionRequired,Go as WebLogsExporterLogger,Me as XStateDeviceAction,Vo as base64StringToBuffer,Wo as bufferToHexaString,ho as connectedDeviceStubBuilder,ro as defaultApduReceiverServiceStubBuilder,po as defaultApduSenderServiceStubBuilder,ko as formatApduReceivedLog,Fo as formatApduSentLog,wo as hexaStringToBuffer,zo as isBase64String,z as isCommandErrorCode,Ho as isHexaString,S as isSuccessCommandResult,Ao as noopLogger,Do as noopLoggerFactory};
2
2
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/api/index.ts"],
4
- "sourcesContent": ["\"use strict\";\n\nexport { Apdu } from \"@api/apdu/model/Apdu\";\nexport { APDU_MAX_PAYLOAD, ApduBuilder } from \"@api/apdu/utils/ApduBuilder\";\nexport { ApduParser } from \"@api/apdu/utils/ApduParser\";\nexport * from \"@api/apdu/utils/AppBuilderError\";\nexport { ByteArrayBuilder } from \"@api/apdu/utils/ByteArrayBuilder\";\nexport { ByteArrayParser } from \"@api/apdu/utils/ByteArrayParser\";\nexport { type Command } from \"@api/command/Command\";\nexport {\n InvalidGetFirmwareMetadataResponseError,\n InvalidStatusWordError,\n} from \"@api/command/Errors\";\nexport {\n CommandResultFactory,\n CommandResultStatus,\n isSuccessCommandResult,\n} from \"@api/command/model/CommandResult\";\nexport { CloseAppCommand } from \"@api/command/os/CloseAppCommand\";\nexport {\n GetAppAndVersionCommand,\n type GetAppAndVersionResponse,\n} from \"@api/command/os/GetAppAndVersionCommand\";\nexport {\n BatteryStatusType,\n type GetBatteryStatusArgs,\n GetBatteryStatusCommand,\n type GetBatteryStatusResponse,\n} from \"@api/command/os/GetBatteryStatusCommand\";\nexport {\n GetOsVersionCommand,\n type GetOsVersionResponse,\n} from \"@api/command/os/GetOsVersionCommand\";\nexport {\n type ListAppsArgs,\n ListAppsCommand,\n type ListAppsErrorCodes,\n type ListAppsResponse,\n} from \"@api/command/os/ListAppsCommand\";\nexport {\n type LoadCertificateArgs,\n LoadCertificateCommand,\n type LoadCertificateErrorCodes,\n} from \"@api/command/os/LoadCertificateCommand\";\nexport {\n type OpenAppArgs,\n OpenAppCommand,\n} from \"@api/command/os/OpenAppCommand\";\nexport { isCommandErrorCode } from \"@api/command/utils/CommandErrors\";\nexport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nexport {\n GLOBAL_ERRORS,\n GlobalCommandError,\n GlobalCommandErrorHandler,\n} from \"@api/command/utils/GlobalCommandError\";\nexport {\n DeviceModel,\n DeviceModelId,\n LEDGER_VENDOR_ID,\n} from \"@api/device/DeviceModel\";\nexport { DeviceStatus } from \"@api/device/DeviceStatus\";\nexport { type InternalApi } from \"@api/device-action/DeviceAction\";\nexport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nexport { UserInteractionRequired } from \"@api/device-action/model/UserInteractionRequired\";\nexport { CallTaskInAppDeviceAction } from \"@api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction\";\nexport {\n AppAlreadyInstalledDAError,\n DeviceLockedError,\n DeviceNotOnboardedError,\n OutOfMemoryDAError,\n RefusedByUserDAError,\n UnknownDAError,\n UnsupportedFirmwareDAError,\n} from \"@api/device-action/os/Errors\";\nexport { GetDeviceMetadataDeviceAction } from \"@api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction\";\nexport { GetDeviceStatusDeviceAction } from \"@api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction\";\nexport { GoToDashboardDeviceAction } from \"@api/device-action/os/GoToDashboard/GoToDashboardDeviceAction\";\nexport { InstallOrUpdateAppsDeviceAction } from \"@api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction\";\nexport { ListAppsDeviceAction } from \"@api/device-action/os/ListApps/ListAppsDeviceAction\";\nexport { ListAppsWithMetadataDeviceAction } from \"@api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction\";\nexport { OpenAppDeviceAction } from \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\";\nexport { OpenAppWithDependenciesDeviceAction } from \"@api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction\";\nexport { SendCommandInAppDeviceAction } from \"@api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction\";\nexport {\n type DeviceActionStateMachine,\n XStateDeviceAction,\n} from \"@api/device-action/xstate-utils/XStateDeviceAction\";\nexport { StaticDeviceModelDataSource } from \"@api/device-model/data/StaticDeviceModelDataSource\";\nexport { BleDeviceInfos } from \"@api/device-model/model/BleDeviceInfos\";\nexport { TransportDeviceModel } from \"@api/device-model/model/DeviceModel\";\nexport { ApduResponse } from \"@api/device-session/ApduResponse\";\nexport * from \"@api/device-session/data/FramerConst\";\nexport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nexport { GenuineCheckDeviceAction } from \"@api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction\";\nexport { InstallAppDeviceAction } from \"@api/secure-channel/device-action/InstallApp/InstallAppDeviceAction\";\nexport { ListInstalledAppsDeviceAction } from \"@api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction\";\nexport { UninstallAppDeviceAction } from \"@api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction\";\nexport { SecureChannelError } from \"@internal/secure-channel/model/Errors\";\n// TODO: remove from exported\nexport { defaultApduReceiverServiceStubBuilder } from \"@api/device-session/service/DefaultApduReceiverService.stub\";\nexport { defaultApduSenderServiceStubBuilder } from \"@api/device-session/service/DefaultApduSenderService.stub\";\nexport { FramerUtils } from \"@api/device-session/utils/FramerUtils\";\nexport { DeviceManagementKit } from \"@api/DeviceManagementKit\";\nexport { DeviceManagementKitBuilder } from \"@api/DeviceManagementKitBuilder\";\nexport * from \"@api/Error\";\nexport { LogLevel } from \"@api/logger-subscriber/model/LogLevel\";\nexport { ConsoleLogger } from \"@api/logger-subscriber/service/ConsoleLogger\";\nexport { DefaultLogTagFormatter } from \"@api/logger-subscriber/service/DefaultLogTagFormatter\";\nexport { type LogTagFormatter } from \"@api/logger-subscriber/service/LogTagFormatter\";\nexport { WebLogsExporterLogger } from \"@api/logger-subscriber/service/WebLogsExporterLogger\";\nexport { ConnectedDevice } from \"@api/transport/model/ConnectedDevice\";\nexport {\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n} from \"@api/transport/model/DeviceConnectionStateMachine\";\nexport * from \"@api/transport/model/Errors\";\nexport { TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nexport { connectedDeviceStubBuilder } from \"@api/transport/model/TransportConnectedDevice.stub\";\nexport * from \"@api/types\";\nexport { formatApduReceivedLog, formatApduSentLog } from \"@api/utils/apduLogs\";\nexport { base64StringToBuffer, isBase64String } from \"@api/utils/Base64String\";\nexport {\n bufferToHexaString,\n hexaStringToBuffer,\n isHexaString,\n} from \"@api/utils/HexaString\";\n"],
5
- "mappings": "AAEA,OAAS,QAAAA,MAAY,uBACrB,OAAS,oBAAAC,EAAkB,eAAAC,MAAmB,8BAC9C,OAAS,cAAAC,MAAkB,6BAC3B,WAAc,kCACd,OAAS,oBAAAC,MAAwB,mCACjC,OAAS,mBAAAC,MAAuB,kCAEhC,OACE,2CAAAC,EACA,0BAAAC,MACK,sBACP,OACE,wBAAAC,EACA,uBAAAC,EACA,0BAAAC,MACK,mCACP,OAAS,mBAAAC,MAAuB,kCAChC,OACE,2BAAAC,MAEK,0CACP,OACE,qBAAAC,EAEA,2BAAAC,MAEK,0CACP,OACE,uBAAAC,MAEK,sCACP,OAEE,mBAAAC,MAGK,kCACP,OAEE,0BAAAC,MAEK,yCACP,OAEE,kBAAAC,MACK,iCACP,OAAS,sBAAAC,MAA0B,mCACnC,OAAS,gBAAAC,MAAoB,kCAC7B,OACE,iBAAAC,EACA,sBAAAC,EACA,6BAAAC,MACK,wCACP,OACE,eAAAC,EACA,iBAAAC,EACA,oBAAAC,MACK,0BACP,OAAS,gBAAAC,MAAoB,2BAE7B,OAEE,sBAAAC,MACK,6CACP,OAAS,2BAAAC,MAA+B,mDACxC,OAAS,6BAAAC,OAAiC,4EAC1C,OACE,8BAAAC,GACA,qBAAAC,GACA,2BAAAC,GACA,sBAAAC,GACA,wBAAAC,GACA,kBAAAC,GACA,8BAAAC,OACK,+BACP,OAAS,iCAAAC,OAAqC,wEAC9C,OAAS,+BAAAC,OAAmC,oEAC5C,OAAS,6BAAAC,OAAiC,gEAC1C,OAAS,mCAAAC,OAAuC,4EAChD,OAAS,wBAAAC,OAA4B,sDACrC,OAAS,oCAAAC,OAAwC,8EACjD,OAAS,uBAAAC,OAA2B,gEACpC,OAAS,uCAAAC,OAA2C,oFACpD,OAAS,gCAAAC,OAAoC,kFAC7C,OAEE,sBAAAC,OACK,qDACP,OAAS,+BAAAC,OAAmC,qDAC5C,OAAS,kBAAAC,OAAsB,yCAC/B,OAAS,wBAAAC,OAA4B,sCACrC,OAAS,gBAAAC,OAAoB,mCAC7B,WAAc,uCACd,OAEE,0BAAAC,OACK,yCACP,OAAS,4BAAAC,OAAgC,0EACzC,OAAS,0BAAAC,OAA8B,sEACvC,OAAS,iCAAAC,OAAqC,oFAC9C,OAAS,4BAAAC,OAAgC,0EACzC,OAAS,sBAAAC,OAA0B,wCAEnC,OAAS,yCAAAC,OAA6C,8DACtD,OAAS,uCAAAC,OAA2C,4DACpD,OAAS,eAAAC,OAAmB,wCAC5B,OAAS,uBAAAC,OAA2B,2BACpC,OAAS,8BAAAC,OAAkC,kCAC3C,WAAc,aACd,OAAS,YAAAC,OAAgB,wCACzB,OAAS,iBAAAC,OAAqB,+CAC9B,OAAS,0BAAAC,OAA8B,wDAEvC,OAAS,yBAAAC,OAA6B,uDACtC,OAAS,mBAAAC,OAAuB,uCAChC,OACE,gCAAAC,OAEK,oDACP,WAAc,8BACd,OAAS,4BAAAC,OAAgC,gDACzC,OAAS,8BAAAC,OAAkC,qDAC3C,WAAc,aACd,OAAS,yBAAAC,GAAuB,qBAAAC,OAAyB,sBACzD,OAAS,wBAAAC,GAAsB,kBAAAC,OAAsB,0BACrD,OACE,sBAAAC,GACA,sBAAAC,GACA,gBAAAC,OACK",
6
- "names": ["Apdu", "APDU_MAX_PAYLOAD", "ApduBuilder", "ApduParser", "ByteArrayBuilder", "ByteArrayParser", "InvalidGetFirmwareMetadataResponseError", "InvalidStatusWordError", "CommandResultFactory", "CommandResultStatus", "isSuccessCommandResult", "CloseAppCommand", "GetAppAndVersionCommand", "BatteryStatusType", "GetBatteryStatusCommand", "GetOsVersionCommand", "ListAppsCommand", "LoadCertificateCommand", "OpenAppCommand", "isCommandErrorCode", "CommandUtils", "GLOBAL_ERRORS", "GlobalCommandError", "GlobalCommandErrorHandler", "DeviceModel", "DeviceModelId", "LEDGER_VENDOR_ID", "DeviceStatus", "DeviceActionStatus", "UserInteractionRequired", "CallTaskInAppDeviceAction", "AppAlreadyInstalledDAError", "DeviceLockedError", "DeviceNotOnboardedError", "OutOfMemoryDAError", "RefusedByUserDAError", "UnknownDAError", "UnsupportedFirmwareDAError", "GetDeviceMetadataDeviceAction", "GetDeviceStatusDeviceAction", "GoToDashboardDeviceAction", "InstallOrUpdateAppsDeviceAction", "ListAppsDeviceAction", "ListAppsWithMetadataDeviceAction", "OpenAppDeviceAction", "OpenAppWithDependenciesDeviceAction", "SendCommandInAppDeviceAction", "XStateDeviceAction", "StaticDeviceModelDataSource", "BleDeviceInfos", "TransportDeviceModel", "ApduResponse", "DeviceSessionStateType", "GenuineCheckDeviceAction", "InstallAppDeviceAction", "ListInstalledAppsDeviceAction", "UninstallAppDeviceAction", "SecureChannelError", "defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "FramerUtils", "DeviceManagementKit", "DeviceManagementKitBuilder", "LogLevel", "ConsoleLogger", "DefaultLogTagFormatter", "WebLogsExporterLogger", "ConnectedDevice", "DeviceConnectionStateMachine", "TransportConnectedDevice", "connectedDeviceStubBuilder", "formatApduReceivedLog", "formatApduSentLog", "base64StringToBuffer", "isBase64String", "bufferToHexaString", "hexaStringToBuffer", "isHexaString"]
4
+ "sourcesContent": ["\"use strict\";\n\nexport { Apdu } from \"@api/apdu/model/Apdu\";\nexport { APDU_MAX_PAYLOAD, ApduBuilder } from \"@api/apdu/utils/ApduBuilder\";\nexport { ApduParser } from \"@api/apdu/utils/ApduParser\";\nexport * from \"@api/apdu/utils/AppBuilderError\";\nexport { ByteArrayBuilder } from \"@api/apdu/utils/ByteArrayBuilder\";\nexport { ByteArrayParser } from \"@api/apdu/utils/ByteArrayParser\";\nexport { type Command } from \"@api/command/Command\";\nexport {\n InvalidGetFirmwareMetadataResponseError,\n InvalidStatusWordError,\n} from \"@api/command/Errors\";\nexport {\n CommandResultFactory,\n CommandResultStatus,\n isSuccessCommandResult,\n} from \"@api/command/model/CommandResult\";\nexport { CloseAppCommand } from \"@api/command/os/CloseAppCommand\";\nexport {\n GetAppAndVersionCommand,\n type GetAppAndVersionResponse,\n} from \"@api/command/os/GetAppAndVersionCommand\";\nexport {\n GetBackgroundImageSizeCommand,\n GetBackgroundImageSizeCommandError,\n type GetBackgroundImageSizeCommandResult,\n type GetBackgroundImageSizeErrorCodes,\n type GetBackgroundImageSizeResponse,\n} from \"@api/command/os/GetBackgroundImageSizeCommand\";\nexport {\n BatteryStatusType,\n type GetBatteryStatusArgs,\n GetBatteryStatusCommand,\n type GetBatteryStatusResponse,\n} from \"@api/command/os/GetBatteryStatusCommand\";\nexport {\n GetOsVersionCommand,\n type GetOsVersionResponse,\n} from \"@api/command/os/GetOsVersionCommand\";\nexport {\n type ListAppsArgs,\n ListAppsCommand,\n type ListAppsErrorCodes,\n type ListAppsResponse,\n} from \"@api/command/os/ListAppsCommand\";\nexport {\n type LoadCertificateArgs,\n LoadCertificateCommand,\n type LoadCertificateErrorCodes,\n} from \"@api/command/os/LoadCertificateCommand\";\nexport {\n type OpenAppArgs,\n OpenAppCommand,\n} from \"@api/command/os/OpenAppCommand\";\nexport { isCommandErrorCode } from \"@api/command/utils/CommandErrors\";\nexport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nexport {\n GLOBAL_ERRORS,\n GlobalCommandError,\n GlobalCommandErrorHandler,\n} from \"@api/command/utils/GlobalCommandError\";\nexport {\n DeviceModel,\n DeviceModelId,\n LEDGER_VENDOR_ID,\n} from \"@api/device/DeviceModel\";\nexport { DeviceStatus } from \"@api/device/DeviceStatus\";\nexport { type InternalApi } from \"@api/device-action/DeviceAction\";\nexport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nexport { UserInteractionRequired } from \"@api/device-action/model/UserInteractionRequired\";\nexport { CallTaskInAppDeviceAction } from \"@api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction\";\nexport { DEFAULT_UNLOCK_TIMEOUT_MS } from \"@api/device-action/os/Const\";\nexport {\n AppAlreadyInstalledDAError,\n DeviceLockedError,\n DeviceNotOnboardedError,\n OutOfMemoryDAError,\n RefusedByUserDAError,\n UnknownDAError,\n UnsupportedFirmwareDAError,\n} from \"@api/device-action/os/Errors\";\nexport { GetDeviceMetadataDeviceAction } from \"@api/device-action/os/GetDeviceMetadata/GetDeviceMetadataDeviceAction\";\nexport { GetDeviceStatusDeviceAction } from \"@api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction\";\nexport { GoToDashboardDeviceAction } from \"@api/device-action/os/GoToDashboard/GoToDashboardDeviceAction\";\nexport type {\n GoToDashboardDAError,\n GoToDashboardDAInput,\n GoToDashboardDAIntermediateValue,\n GoToDashboardDAOutput,\n GoToDashboardDARequiredInteraction,\n GoToDashboardDAState,\n} from \"@api/device-action/os/GoToDashboard/types\";\nexport { InstallOrUpdateAppsDeviceAction } from \"@api/device-action/os/InstallOrUpdateApps/InstallOrUpdateAppsDeviceAction\";\nexport { ListAppsDeviceAction } from \"@api/device-action/os/ListApps/ListAppsDeviceAction\";\nexport { ListAppsWithMetadataDeviceAction } from \"@api/device-action/os/ListAppsWithMetadata/ListAppsWithMetadataDeviceAction\";\nexport { OpenAppDeviceAction } from \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\";\nexport { OpenAppWithDependenciesDeviceAction } from \"@api/device-action/os/OpenAppWithDependencies/OpenAppWithDependenciesDeviceAction\";\nexport { SendCommandInAppDeviceAction } from \"@api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction\";\nexport {\n type DeviceActionStateMachine,\n XStateDeviceAction,\n} from \"@api/device-action/xstate-utils/XStateDeviceAction\";\nexport { StaticDeviceModelDataSource } from \"@api/device-model/data/StaticDeviceModelDataSource\";\nexport { BleDeviceInfos } from \"@api/device-model/model/BleDeviceInfos\";\nexport { TransportDeviceModel } from \"@api/device-model/model/DeviceModel\";\nexport { ApduResponse } from \"@api/device-session/ApduResponse\";\nexport * from \"@api/device-session/data/FramerConst\";\nexport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nexport { GenuineCheckDeviceAction } from \"@api/secure-channel/device-action/GenuineCheck/GenuineCheckDeviceAction\";\nexport { InstallAppDeviceAction } from \"@api/secure-channel/device-action/InstallApp/InstallAppDeviceAction\";\nexport { ListInstalledAppsDeviceAction } from \"@api/secure-channel/device-action/ListInstalledApps/ListInstalledAppsDeviceAction\";\nexport { UninstallAppDeviceAction } from \"@api/secure-channel/device-action/UninstallApp/UninstallAppDeviceAction\";\nexport { SecureChannelError } from \"@internal/secure-channel/model/Errors\";\n// TODO: remove from exported\nexport { defaultApduReceiverServiceStubBuilder } from \"@api/device-session/service/DefaultApduReceiverService.stub\";\nexport { defaultApduSenderServiceStubBuilder } from \"@api/device-session/service/DefaultApduSenderService.stub\";\nexport { FramerUtils } from \"@api/device-session/utils/FramerUtils\";\nexport { DeviceManagementKit } from \"@api/DeviceManagementKit\";\nexport { DeviceManagementKitBuilder } from \"@api/DeviceManagementKitBuilder\";\nexport * from \"@api/Error\";\nexport {\n noopLogger,\n noopLoggerFactory,\n} from \"@api/logger-publisher/utils/noopLoggerFactory\";\nexport { LogLevel } from \"@api/logger-subscriber/model/LogLevel\";\nexport { ConsoleLogger } from \"@api/logger-subscriber/service/ConsoleLogger\";\nexport { DefaultLogTagFormatter } from \"@api/logger-subscriber/service/DefaultLogTagFormatter\";\nexport { type LogTagFormatter } from \"@api/logger-subscriber/service/LogTagFormatter\";\nexport { WebLogsExporterLogger } from \"@api/logger-subscriber/service/WebLogsExporterLogger\";\nexport { ConnectedDevice } from \"@api/transport/model/ConnectedDevice\";\nexport {\n DeviceConnectionStateMachine,\n type DeviceConnectionStateMachineParams,\n} from \"@api/transport/model/DeviceConnectionStateMachine\";\nexport * from \"@api/transport/model/Errors\";\nexport { TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nexport { connectedDeviceStubBuilder } from \"@api/transport/model/TransportConnectedDevice.stub\";\nexport * from \"@api/types\";\nexport { formatApduReceivedLog, formatApduSentLog } from \"@api/utils/apduLogs\";\nexport { base64StringToBuffer, isBase64String } from \"@api/utils/Base64String\";\nexport {\n bufferToHexaString,\n hexaStringToBuffer,\n isHexaString,\n} from \"@api/utils/HexaString\";\n"],
5
+ "mappings": "AAEA,OAAS,QAAAA,MAAY,uBACrB,OAAS,oBAAAC,EAAkB,eAAAC,MAAmB,8BAC9C,OAAS,cAAAC,MAAkB,6BAC3B,WAAc,kCACd,OAAS,oBAAAC,MAAwB,mCACjC,OAAS,mBAAAC,MAAuB,kCAEhC,OACE,2CAAAC,EACA,0BAAAC,MACK,sBACP,OACE,wBAAAC,EACA,uBAAAC,EACA,0BAAAC,MACK,mCACP,OAAS,mBAAAC,MAAuB,kCAChC,OACE,2BAAAC,MAEK,0CACP,OACE,iCAAAC,EACA,sCAAAC,MAIK,gDACP,OACE,qBAAAC,EAEA,2BAAAC,MAEK,0CACP,OACE,uBAAAC,MAEK,sCACP,OAEE,mBAAAC,MAGK,kCACP,OAEE,0BAAAC,MAEK,yCACP,OAEE,kBAAAC,MACK,iCACP,OAAS,sBAAAC,MAA0B,mCACnC,OAAS,gBAAAC,MAAoB,kCAC7B,OACE,iBAAAC,EACA,sBAAAC,EACA,6BAAAC,MACK,wCACP,OACE,eAAAC,EACA,iBAAAC,EACA,oBAAAC,MACK,0BACP,OAAS,gBAAAC,MAAoB,2BAE7B,OAEE,sBAAAC,MACK,6CACP,OAAS,2BAAAC,OAA+B,mDACxC,OAAS,6BAAAC,OAAiC,4EAC1C,OAAS,6BA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AAC,OAAsB,0BACrD,OACE,sBAAAC,GACA,sBAAAC,GACA,gBAAAC,OACK",
6
+ "names": ["Apdu", "APDU_MAX_PAYLOAD", "ApduBuilder", "ApduParser", "ByteArrayBuilder", "ByteArrayParser", "InvalidGetFirmwareMetadataResponseError", "InvalidStatusWordError", "CommandResultFactory", "CommandResultStatus", "isSuccessCommandResult", "CloseAppCommand", "GetAppAndVersionCommand", "GetBackgroundImageSizeCommand", "GetBackgroundImageSizeCommandError", "BatteryStatusType", "GetBatteryStatusCommand", "GetOsVersionCommand", "ListAppsCommand", "LoadCertificateCommand", "OpenAppCommand", "isCommandErrorCode", "CommandUtils", "GLOBAL_ERRORS", "GlobalCommandError", "GlobalCommandErrorHandler", "DeviceModel", "DeviceModelId", "LEDGER_VENDOR_ID", "DeviceStatus", "DeviceActionStatus", "UserInteractionRequired", "CallTaskInAppDeviceAction", "DEFAULT_UNLOCK_TIMEOUT_MS", "AppAlreadyInstalledDAError", "DeviceLockedError", "DeviceNotOnboardedError", "OutOfMemoryDAError", "RefusedByUserDAError", "UnknownDAError", "UnsupportedFirmwareDAError", "GetDeviceMetadataDeviceAction", "GetDeviceStatusDeviceAction", "GoToDashboardDeviceAction", "InstallOrUpdateAppsDeviceAction", "ListAppsDeviceAction", "ListAppsWithMetadataDeviceAction", "OpenAppDeviceAction", "OpenAppWithDependenciesDeviceAction", "SendCommandInAppDeviceAction", "XStateDeviceAction", "StaticDeviceModelDataSource", "BleDeviceInfos", "TransportDeviceModel", "ApduResponse", "DeviceSessionStateType", "GenuineCheckDeviceAction", "InstallAppDeviceAction", "ListInstalledAppsDeviceAction", "UninstallAppDeviceAction", "SecureChannelError", "defaultApduReceiverServiceStubBuilder", "defaultApduSenderServiceStubBuilder", "FramerUtils", "DeviceManagementKit", "DeviceManagementKitBuilder", "noopLogger", "noopLoggerFactory", "LogLevel", "ConsoleLogger", "DefaultLogTagFormatter", "WebLogsExporterLogger", "ConnectedDevice", "DeviceConnectionStateMachine", "TransportConnectedDevice", "connectedDeviceStubBuilder", "formatApduReceivedLog", "formatApduSentLog", "base64StringToBuffer", "isBase64String", "bufferToHexaString", "hexaStringToBuffer", "isHexaString"]
7
7
  }
@@ -0,0 +1,2 @@
1
+ const r={subscribers:[],error:()=>{},warn:()=>{},info:()=>{},debug:()=>{}},o=e=>r;export{r as noopLogger,o as noopLoggerFactory};
2
+ //# sourceMappingURL=noopLoggerFactory.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/api/logger-publisher/utils/noopLoggerFactory.ts"],
4
+ "sourcesContent": ["import { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\n\n/**\n * A no-op logger that silently discards all log messages.\n * Useful as a default when no logger is configured.\n */\nexport const noopLogger: LoggerPublisherService = {\n subscribers: [],\n error: () => {},\n warn: () => {},\n info: () => {},\n debug: () => {},\n};\n\n/**\n * A logger factory that always returns a no-op logger, regardless of the tag.\n * Use this as a fallback when no logger factory is provided.\n */\nexport const noopLoggerFactory = (_tag: string): LoggerPublisherService =>\n noopLogger;\n"],
5
+ "mappings": "AAMO,MAAMA,EAAqC,CAChD,YAAa,CAAC,EACd,MAAO,IAAM,CAAC,EACd,KAAM,IAAM,CAAC,EACb,KAAM,IAAM,CAAC,EACb,MAAO,IAAM,CAAC,CAChB,EAMaC,EAAqBC,GAChCF",
6
+ "names": ["noopLogger", "noopLoggerFactory", "_tag"]
7
+ }
@@ -0,0 +1,2 @@
1
+ import{describe as s,expect as o,it as r}from"vitest";import{noopLogger as e,noopLoggerFactory as n}from"./noopLoggerFactory";s("noopLogger",()=>{r("should have an empty subscribers array",()=>{o(e.subscribers).toEqual([])}),r("should not throw when calling error",()=>{o(()=>e.error("test")).not.toThrow()}),r("should not throw when calling warn",()=>{o(()=>e.warn("test")).not.toThrow()}),r("should not throw when calling info",()=>{o(()=>e.info("test")).not.toThrow()}),r("should not throw when calling debug",()=>{o(()=>e.debug("test")).not.toThrow()}),r("should not throw when calling methods with options",()=>{const t={data:{key:"value"}};o(()=>e.error("test",t)).not.toThrow(),o(()=>e.warn("test",t)).not.toThrow(),o(()=>e.info("test",t)).not.toThrow(),o(()=>e.debug("test",t)).not.toThrow()})});s("noopLoggerFactory",()=>{r("should return a LoggerPublisherService regardless of tag",()=>{const t=n("any-tag");o(t).toBeDefined(),o(t.subscribers).toEqual([]),o(typeof t.error).toBe("function"),o(typeof t.warn).toBe("function"),o(typeof t.info).toBe("function"),o(typeof t.debug).toBe("function")}),r("should always return the same noopLogger instance",()=>{const t=n("tag-a"),a=n("tag-b");o(t).toBe(a),o(t).toBe(e)})});
2
+ //# sourceMappingURL=noopLoggerFactory.test.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/api/logger-publisher/utils/noopLoggerFactory.test.ts"],
4
+ "sourcesContent": ["import { describe, expect, it } from \"vitest\";\n\nimport { noopLogger, noopLoggerFactory } from \"./noopLoggerFactory\";\n\ndescribe(\"noopLogger\", () => {\n it(\"should have an empty subscribers array\", () => {\n expect(noopLogger.subscribers).toEqual([]);\n });\n\n it(\"should not throw when calling error\", () => {\n expect(() => noopLogger.error(\"test\")).not.toThrow();\n });\n\n it(\"should not throw when calling warn\", () => {\n expect(() => noopLogger.warn(\"test\")).not.toThrow();\n });\n\n it(\"should not throw when calling info\", () => {\n expect(() => noopLogger.info(\"test\")).not.toThrow();\n });\n\n it(\"should not throw when calling debug\", () => {\n expect(() => noopLogger.debug(\"test\")).not.toThrow();\n });\n\n it(\"should not throw when calling methods with options\", () => {\n const options = { data: { key: \"value\" } };\n expect(() => noopLogger.error(\"test\", options)).not.toThrow();\n expect(() => noopLogger.warn(\"test\", options)).not.toThrow();\n expect(() => noopLogger.info(\"test\", options)).not.toThrow();\n expect(() => noopLogger.debug(\"test\", options)).not.toThrow();\n });\n});\n\ndescribe(\"noopLoggerFactory\", () => {\n it(\"should return a LoggerPublisherService regardless of tag\", () => {\n const logger = noopLoggerFactory(\"any-tag\");\n expect(logger).toBeDefined();\n expect(logger.subscribers).toEqual([]);\n expect(typeof logger.error).toBe(\"function\");\n expect(typeof logger.warn).toBe(\"function\");\n expect(typeof logger.info).toBe(\"function\");\n expect(typeof logger.debug).toBe(\"function\");\n });\n\n it(\"should always return the same noopLogger instance\", () => {\n const logger1 = noopLoggerFactory(\"tag-a\");\n const logger2 = noopLoggerFactory(\"tag-b\");\n expect(logger1).toBe(logger2);\n expect(logger1).toBe(noopLogger);\n });\n});\n"],
5
+ "mappings": "AAAA,OAAS,YAAAA,EAAU,UAAAC,EAAQ,MAAAC,MAAU,SAErC,OAAS,cAAAC,EAAY,qBAAAC,MAAyB,sBAE9CJ,EAAS,aAAc,IAAM,CAC3BE,EAAG,yCAA0C,IAAM,CACjDD,EAAOE,EAAW,WAAW,EAAE,QAAQ,CAAC,CAAC,CAC3C,CAAC,EAEDD,EAAG,sCAAuC,IAAM,CAC9CD,EAAO,IAAME,EAAW,MAAM,MAAM,CAAC,EAAE,IAAI,QAAQ,CACrD,CAAC,EAEDD,EAAG,qCAAsC,IAAM,CAC7CD,EAAO,IAAME,EAAW,KAAK,MAAM,CAAC,EAAE,IAAI,QAAQ,CACpD,CAAC,EAEDD,EAAG,qCAAsC,IAAM,CAC7CD,EAAO,IAAME,EAAW,KAAK,MAAM,CAAC,EAAE,IAAI,QAAQ,CACpD,CAAC,EAEDD,EAAG,sCAAuC,IAAM,CAC9CD,EAAO,IAAME,EAAW,MAAM,MAAM,CAAC,EAAE,IAAI,QAAQ,CACrD,CAAC,EAEDD,EAAG,qDAAsD,IAAM,CAC7D,MAAMG,EAAU,CAAE,KAAM,CAAE,IAAK,OAAQ,CAAE,EACzCJ,EAAO,IAAME,EAAW,MAAM,OAAQE,CAAO,CAAC,EAAE,IAAI,QAAQ,EAC5DJ,EAAO,IAAME,EAAW,KAAK,OAAQE,CAAO,CAAC,EAAE,IAAI,QAAQ,EAC3DJ,EAAO,IAAME,EAAW,KAAK,OAAQE,CAAO,CAAC,EAAE,IAAI,QAAQ,EAC3DJ,EAAO,IAAME,EAAW,MAAM,OAAQE,CAAO,CAAC,EAAE,IAAI,QAAQ,CAC9D,CAAC,CACH,CAAC,EAEDL,EAAS,oBAAqB,IAAM,CAClCE,EAAG,2DAA4D,IAAM,CACnE,MAAMI,EAASF,EAAkB,SAAS,EAC1CH,EAAOK,CAAM,EAAE,YAAY,EAC3BL,EAAOK,EAAO,WAAW,EAAE,QAAQ,CAAC,CAAC,EACrCL,EAAO,OAAOK,EAAO,KAAK,EAAE,KAAK,UAAU,EAC3CL,EAAO,OAAOK,EAAO,IAAI,EAAE,KAAK,UAAU,EAC1CL,EAAO,OAAOK,EAAO,IAAI,EAAE,KAAK,UAAU,EAC1CL,EAAO,OAAOK,EAAO,KAAK,EAAE,KAAK,UAAU,CAC7C,CAAC,EAEDJ,EAAG,oDAAqD,IAAM,CAC5D,MAAMK,EAAUH,EAAkB,OAAO,EACnCI,EAAUJ,EAAkB,OAAO,EACzCH,EAAOM,CAAO,EAAE,KAAKC,CAAO,EAC5BP,EAAOM,CAAO,EAAE,KAAKJ,CAAU,CACjC,CAAC,CACH,CAAC",
6
+ "names": ["describe", "expect", "it", "noopLogger", "noopLoggerFactory", "options", "logger", "logger1", "logger2"]
7
+ }
@@ -1,2 +1,2 @@
1
- import{BehaviorSubject as l,from as d,lastValueFrom as p,timeout as v}from"rxjs";import{v4 as h}from"uuid";import{CommandUtils as S}from"../../../api/command/utils/CommandUtils";import{DeviceStatus as m}from"../../../api/device/DeviceStatus";import{DeviceSessionStateType as D}from"../../../api/device-session/DeviceSessionState";import{SendApduTimeoutError as _,SendCommandTimeoutError as f}from"../../../api/transport/model/Errors";import{formatApduReceivedLog as g,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 I,SessionEvents as c}from"./DeviceSessionEventDispatcher";import{DeviceSessionRefresher as y}from"./DeviceSessionRefresher";import{DeviceSessionStateHandler as O}from"./DeviceSessionStateHandler";class K{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_intentQueueService;_sessionEventDispatcher=new I;_bypassIntentQueue=!1;constructor({connectedDevice:e,id:t=h()},i,s,n,r,a=o=>new A(i,o)){this._id=t,this._connectedDevice=e,this._logger=i("device-session"),this._managerApiService=s,this._intentQueueService=a(this._sessionEventDispatcher),this._secureChannelService=n,this._refresherOptions={...b,...r},this._deviceState=new l({sessionStateType:D.Connected,deviceStatus:m.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new R(i,e,this._sessionEventDispatcher,(o,u)=>this.sendCommand(o,u)),this._deviceSessionRefresher=new y(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(g(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 f}})):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});return{observable:t,cancel:i}}close(){this._updateDeviceStatus(m.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};
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 {\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 _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._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 });\n\n return {\n observable,\n cancel,\n };\n }\n\n public close(): void {\n this._updateDeviceStatus(DeviceStatus.NOT_CONNECTED);\n this._deviceState.complete();\n this._deviceSessionRefresher.stopRefresher();\n this._pinger.unsubscribe();\n }\n\n public disableRefresher(id: string): () => void {\n return this._refresherService.disableRefresher(id);\n }\n\n public _unsafeBypassIntentQueue(bypass: boolean): void {\n this._bypassIntentQueue = bypass;\n }\n\n private _updateDeviceStatus(deviceStatus: DeviceStatus): void {\n const state = this._deviceState.getValue();\n this._deviceState.next({ ...state, deviceStatus });\n }\n}\n"],
5
- "mappings": "AACA,OACE,mBAAAA,EACA,QAAAC,EACA,iBAAAC,EAEA,WAAAC,MACK,OACP,OAAS,MAAMC,MAAc,OAI7B,OAAS,gBAAAC,MAAoB,kCAC7B,OAAS,gBAAAC,MAAoB,2BAO7B,OAEE,0BAAAC,MACK,yCAIP,OACE,wBAAAC,EACA,2BAAAC,MACK,8BAEP,OACE,yBAAAC,EACA,wBAAAC,MACK,sBACP,OAAS,4CAAAC,MAAgD,4DACzD,OAAS,sBAAAC,MAA0B,sDACnC,OAAS,oBAAAC,MAAwB,oDAIjC,OAAS,gBAAAC,MAAoB,iBAC7B,OACE,gCAAAC,EACA,iBAAAC,MACK,iCACP,OAAS,0BAAAC,MAA8B,2BACvC,OAAS,6BAAAC,MAAiC,8BAqBnC,MAAMC,CAAc,CACR,IACA,iBACA,aACA,mBACA,sBACA,QACA,kBACT,QACA,wBACS,kBACA,oBACT,wBAA0B,IAAIJ,EAC9B,mBAA8B,GAEtC,YACE,CAAE,gBAAAK,EAAiB,GAAAC,EAAKlB,EAAO,CAAE,EACjCmB,EACAC,EACAC,EACAC,EACAC,EAE2BC,GACzB,IAAIf,EAAmBU,EAAq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,CAAa,CAAC,CACnD,CACF",
4
+ "sourcesContent": ["import { type Either } from \"purify-ts\";\nimport {\n BehaviorSubject,\n from,\n lastValueFrom,\n type Observable,\n timeout,\n} from \"rxjs\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { type Command } from \"@api/command/Command\";\nimport { type CommandResult } from \"@api/command/model/CommandResult\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nimport { type DeviceSessionId } from \"@api/device-session/types\";\nimport { type DmkError } from \"@api/Error\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport {\n SendApduTimeoutError,\n SendCommandTimeoutError,\n} from \"@api/transport/model/Errors\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport {\n formatApduReceivedLog,\n formatApduSendingLog,\n} from \"@api/utils/apduLogs\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { IntentQueueService } from \"@internal/device-session/service/IntentQueueService\";\nimport { RefresherService } from \"@internal/device-session/service/RefresherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DevicePinger } from \"./DevicePinger\";\nimport {\n DeviceSessionEventDispatcher,\n SessionEvents,\n} from \"./DeviceSessionEventDispatcher\";\nimport { DeviceSessionRefresher } from \"./DeviceSessionRefresher\";\nimport { DeviceSessionStateHandler } from \"./DeviceSessionStateHandler\";\n\nexport type SessionConstructorArgs = {\n connectedDevice: TransportConnectedDevice;\n id?: DeviceSessionId;\n};\n\nexport type DeviceSessionRefresherOptions = {\n isRefresherDisabled: boolean;\n pollingInterval?: number;\n};\n\ntype SendApduOptions = {\n isPolling?: boolean;\n triggersDisconnection?: boolean;\n abortTimeout?: number;\n};\n\n/**\n * Represents a session with a device.\n */\nexport class DeviceSession {\n private readonly _id: DeviceSessionId;\n private readonly _connectedDevice: TransportConnectedDevice;\n private readonly _deviceState: BehaviorSubject<DeviceSessionState>;\n private readonly _managerApiService: ManagerApiService;\n private readonly _secureChannelService: SecureChannelService;\n private readonly _logger: LoggerPublisherService;\n private readonly _loggerModuleFactory: (\n tag: string,\n ) => LoggerPublisherService;\n private readonly _refresherOptions: DeviceSessionRefresherOptions;\n private _pinger: DevicePinger;\n private _deviceSessionRefresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private readonly _intentQueueService: IntentQueueService;\n private _sessionEventDispatcher = new DeviceSessionEventDispatcher();\n private _bypassIntentQueue: boolean = false;\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n deviceSessionRefresherOptions: DeviceSessionRefresherOptions | undefined,\n intentQueueServiceFactory: (\n sessionEventDispatcher: DeviceSessionEventDispatcher,\n ) => IntentQueueService = (sessionEventDispatcher) =>\n new IntentQueueService(loggerModuleFactory, sessionEventDispatcher),\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._loggerModuleFactory = loggerModuleFactory;\n this._logger = loggerModuleFactory(\"device-session\");\n this._managerApiService = managerApiService;\n this._intentQueueService = intentQueueServiceFactory(\n this._sessionEventDispatcher,\n );\n this._secureChannelService = secureChannelService;\n this._refresherOptions = {\n ...DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n ...deviceSessionRefresherOptions,\n };\n this._deviceState = new BehaviorSubject<DeviceSessionState>({\n sessionStateType: DeviceSessionStateType.Connected,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n });\n\n this._pinger = new DevicePinger(\n loggerModuleFactory,\n connectedDevice,\n this._sessionEventDispatcher,\n (command, abortTimeout) => this.sendCommand(command, abortTimeout),\n );\n this._deviceSessionRefresher = new DeviceSessionRefresher(\n loggerModuleFactory,\n this._refresherOptions,\n this._sessionEventDispatcher,\n this._connectedDevice,\n );\n new DeviceSessionStateHandler(\n loggerModuleFactory,\n this._sessionEventDispatcher,\n this._connectedDevice,\n this._deviceState,\n (state) => this.setDeviceSessionState(state),\n );\n\n this._refresherService = new RefresherService(loggerModuleFactory, {\n start: () => this._deviceSessionRefresher.restartRefresher(),\n stop: () => this._deviceSessionRefresher.stopRefresher(),\n });\n }\n\n public async initialiseSession(): Promise<void> {\n try {\n if (this._refresherOptions.isRefresherDisabled) await this._pinger.ping();\n else this._deviceSessionRefresher.startRefresher();\n } catch (error) {\n this._logger.error(\"Error while initialising session\", {\n data: { error },\n });\n throw error;\n }\n }\n\n public get id(): DeviceSessionId {\n return this._id;\n }\n\n public get connectedDevice(): TransportConnectedDevice {\n return this._connectedDevice;\n }\n\n public get state(): Observable<DeviceSessionState> {\n return this._deviceState.asObservable();\n }\n\n public getDeviceSessionState(): DeviceSessionState {\n return this._deviceState.getValue();\n }\n\n public setDeviceSessionState(state: DeviceSessionState): void {\n this._deviceState.next(state);\n }\n\n public sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n // Bypass intent queue if flag is set\n if (this._bypassIntentQueue) {\n return this._unsafeInternalSendApdu(rawApdu, options);\n }\n return this._internalSendApdu(rawApdu, options);\n }\n\n private _internalSendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions,\n ): Promise<Either<DmkError, ApduResponse>> {\n const abortTimeout = options.abortTimeout;\n const beforeQueuedTimestamp = Date.now();\n const { observable, cancel } = this._intentQueueService.enqueue({\n type: \"send-apdu\",\n execute: () =>\n from(\n (async () => {\n const elapsedTime = Date.now() - beforeQueuedTimestamp;\n const result = await this._unsafeInternalSendApdu(rawApdu, {\n isPolling: options.isPolling,\n triggersDisconnection: options.triggersDisconnection,\n // Subtract the elapsed time to account for the time spent in the queue\n // to sync both observable and transport timeout\n abortTimeout: abortTimeout\n ? abortTimeout - elapsedTime\n : undefined,\n });\n return result;\n })(),\n ),\n });\n\n const timeoutObservable = abortTimeout\n ? observable.pipe(\n timeout({\n each: abortTimeout,\n with: () => {\n cancel();\n throw new SendApduTimeoutError();\n },\n }),\n )\n : observable;\n\n return lastValueFrom(timeoutObservable);\n }\n\n private async _unsafeInternalSendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n this._logger.debug(formatApduSendingLog(rawApdu));\n const result = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n options.abortTimeout,\n );\n\n return result\n .ifRight((response: ApduResponse) => {\n this._logger.debug(formatApduReceivedLog(response));\n if (CommandUtils.isLockedDeviceResponse(response)) {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_LOCKED,\n });\n } else {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n }\n })\n .ifLeft(() => {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_UNKNOWN,\n });\n });\n }\n\n public sendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n this._logger.debug(`[sendCommand] ${command.name}`);\n\n // Bypass intent queue if flag is set\n if (this._bypassIntentQueue) {\n return this._unsafeInternalSendCommand(command, abortTimeout);\n }\n return this._internalSendCommand(command, abortTimeout);\n }\n\n private _internalSendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const beforeQueuedTimestamp = Date.now();\n const { observable, cancel } = this._intentQueueService.enqueue({\n type: \"send-command\",\n execute: () =>\n from(\n (async () => {\n const elapsedTime = Date.now() - beforeQueuedTimestamp;\n const result = await this._unsafeInternalSendCommand(\n command,\n // Subtract the elapsed time to account for the time spent in the queue\n // to sync both observable and transport timeout\n abortTimeout ? abortTimeout - elapsedTime : undefined,\n );\n return result;\n })(),\n ),\n });\n\n const timeoutObservable = abortTimeout\n ? observable.pipe(\n timeout({\n each: abortTimeout,\n with: () => {\n cancel();\n throw new SendCommandTimeoutError();\n },\n }),\n )\n : observable;\n\n return lastValueFrom(timeoutObservable);\n }\n\n private async _unsafeInternalSendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const apdu = command.getApdu();\n\n const response = await this._unsafeInternalSendApdu(apdu.getRawApdu(), {\n isPolling: false,\n triggersDisconnection: command.triggersDisconnection ?? false,\n abortTimeout,\n });\n\n return response.caseOf({\n Left: (err) => {\n this._logger.error(\"[sendCommand] error\", { data: { err } });\n throw err;\n },\n Right: (r) => {\n const result = command.parseResponse(\n r,\n this._connectedDevice.deviceModel.id,\n );\n this._logger.debug(\"[sendCommand] result\", { data: { result } });\n return result;\n },\n });\n }\n\n public executeDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n // Bypass intent queue if flag is set\n if (this._bypassIntentQueue) {\n return this._unsafeInternalExecuteDeviceAction(deviceAction);\n }\n return this._internalExecuteDeviceAction(deviceAction);\n }\n\n private _internalExecuteDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n let deviceActionCancel: (() => void) | undefined;\n\n const { observable: o, cancel: queueCancel } =\n this._intentQueueService.enqueue({\n type: \"device-action\",\n execute: () => {\n const { observable, cancel } =\n this._unsafeInternalExecuteDeviceAction(deviceAction);\n deviceActionCancel = cancel;\n return observable;\n },\n });\n\n return {\n observable: o,\n cancel: () => {\n deviceActionCancel?.();\n queueCancel();\n },\n };\n }\n\n private _unsafeInternalExecuteDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n const { observable, cancel } = deviceAction._execute({\n sendApdu: async (apdu: Uint8Array) => this._unsafeInternalSendApdu(apdu), // note: there is no timeout handled at this stage\n sendCommand: async <Response, ErrorStatusCodes, Args>(\n command: Command<Response, ErrorStatusCodes, Args>,\n ) => this._unsafeInternalSendCommand(command), // note: there is no timeout handled at this stage\n getDeviceModel: () => this._connectedDevice.deviceModel,\n getDeviceSessionState: () => this._deviceState.getValue(),\n getDeviceSessionStateObservable: () => this.state,\n setDeviceSessionState: (state: DeviceSessionState) => {\n this.setDeviceSessionState(state);\n return this._deviceState.getValue();\n },\n getManagerApiService: () => this._managerApiService,\n getSecureChannelService: () => this._secureChannelService,\n loggerFactory: this._loggerModuleFactory,\n });\n\n return {\n observable,\n cancel,\n };\n }\n\n public close(): void {\n this._updateDeviceStatus(DeviceStatus.NOT_CONNECTED);\n this._deviceState.complete();\n this._deviceSessionRefresher.stopRefresher();\n this._pinger.unsubscribe();\n }\n\n public disableRefresher(id: string): () => void {\n return this._refresherService.disableRefresher(id);\n }\n\n public _unsafeBypassIntentQueue(bypass: boolean): void {\n this._bypassIntentQueue = bypass;\n }\n\n private _updateDeviceStatus(deviceStatus: DeviceStatus): void {\n const state = this._deviceState.getValue();\n this._deviceState.next({ ...state, deviceStatus });\n }\n}\n"],
5
+ "mappings": "AACA,OACE,mBAAAA,EACA,QAAAC,EACA,iBAAAC,EAEA,WAAAC,MACK,OACP,OAAS,MAAMC,MAAc,OAI7B,OAAS,gBAAAC,MAAoB,kCAC7B,OAAS,gBAAAC,MAAoB,2BAO7B,OAEE,0BAAAC,MACK,yCAIP,OACE,wBAAAC,EACA,2BAAAC,MACK,8BAEP,OACE,yBAAAC,EACA,wBAAAC,MACK,sBACP,OAAS,4CAAAC,MAAgD,4DACzD,OAAS,sBAAAC,MAA0B,sDACnC,OAAS,oBAAAC,MAAwB,oDAIjC,OAAS,gBAAAC,MAAoB,iBAC7B,OACE,gCAAAC,EACA,iBAAAC,MACK,iCACP,OAAS,0BAAAC,MAA8B,2BACvC,OAAS,6BAAAC,MAAiC,8BAqBnC,MAAMC,CAAc,CACR,IACA,iBACA,aACA,mBACA,sBACA,QACA,qBAGA,kBACT,QACA,wBACS,kBACA,oBACT,wBAA0B,IAAIJ,EAC9B,mBAA8B,GAEtC,YACE,CAAE,gBAAAK,EAAiB,GAAAC,EAAKlB,EAAO,CAAE,EACjCmB,EACAC,EACAC,EACAC,EACAC,EAE2BC,GACzB,IAAIf,EAAmBU,EAAqBK,CAAsB,EACpE,CACA,KAAK,IAAMN,EACX,KAAK,iBAAmBD,EACxB,KAAK,qBAAuBE,EAC5B,KAAK,QAAUA,EAAoB,gBAAgB,EACnD,KAAK,mBAAqBC,EAC1B,KAAK,oBAAsBG,EACzB,KAAK,uBACP,EACA,KAAK,sBAAwBF,EAC7B,KAAK,kBAAoB,CACvB,GAAGb,EACH,GAAGc,CACL,EACA,KAAK,aAAe,IAAI1B,EAAoC,CAC1D,iBAAkBO,EAAuB,UACzC,aAAcD,EAAa,UAC3B,cAAe,KAAK,iBAAiB,YAAY,EACnD,CAAC,EAED,KA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D,IAAqB,EACrBE,EAAY,CACd,CACF,CACF,CAEQ,mCAMNH,EAC6D,CAC7D,KAAM,CAAE,WAAAT,EAAY,OAAAC,CAAO,EAAIQ,EAAa,SAAS,CACnD,SAAU,MAAOJ,GAAqB,KAAK,wBAAwBA,CAAI,EACvE,YAAa,MACXZ,GACG,KAAK,2BAA2BA,CAAO,EAC5C,eAAgB,IAAM,KAAK,iBAAiB,YAC5C,sBAAuB,IAAM,KAAK,aAAa,SAAS,EACxD,gCAAiC,IAAM,KAAK,MAC5C,sBAAwBE,IACtB,KAAK,sBAAsBA,CAAK,EACzB,KAAK,aAAa,SAAS,GAEpC,qBAAsB,IAAM,KAAK,mBACjC,wBAAyB,IAAM,KAAK,sBACpC,cAAe,KAAK,oBACtB,CAAC,EAED,MAAO,CACL,WAAAK,EACA,OAAAC,CACF,CACF,CAEO,OAAc,CACnB,KAAK,oBAAoB/B,EAAa,aAAa,EACnD,KAAK,aAAa,SAAS,EAC3B,KAAK,wBAAwB,cAAc,EAC3C,KAAK,QAAQ,YAAY,CAC3B,CAEO,iBAAiBgB,EAAwB,CAC9C,OAAO,KAAK,kBAAkB,iBAAiBA,CAAE,CACnD,CAEO,yBAAyB2B,EAAuB,CACrD,KAAK,mBAAqBA,CAC5B,CAEQ,oBAAoBC,EAAkC,CAC5D,MAAMnB,EAAQ,KAAK,aAAa,SAAS,EACzC,KAAK,aAAa,KAAK,CAAE,GAAGA,EAAO,aAAAmB,CAAa,CAAC,CACnD,CACF",
6
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
  }