@ledgerhq/device-management-kit 0.10.0 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/cjs/package.json +1 -1
- package/lib/cjs/src/api/command/Command.js +1 -1
- package/lib/cjs/src/api/command/Command.js.map +1 -1
- package/lib/cjs/src/api/command/os/CloseAppCommand.js +1 -1
- package/lib/cjs/src/api/command/os/CloseAppCommand.js.map +2 -2
- package/lib/cjs/src/api/command/os/CloseAppCommand.test.js +1 -1
- package/lib/cjs/src/api/command/os/CloseAppCommand.test.js.map +2 -2
- package/lib/cjs/src/api/command/os/GetAppAndVersionCommand.js +1 -1
- package/lib/cjs/src/api/command/os/GetAppAndVersionCommand.js.map +2 -2
- package/lib/cjs/src/api/command/os/GetAppAndVersionCommand.test.js +1 -1
- package/lib/cjs/src/api/command/os/GetAppAndVersionCommand.test.js.map +2 -2
- package/lib/cjs/src/api/command/os/GetBatteryStatusCommand.js +1 -1
- package/lib/cjs/src/api/command/os/GetBatteryStatusCommand.js.map +2 -2
- package/lib/cjs/src/api/command/os/GetBatteryStatusCommand.test.js +1 -1
- package/lib/cjs/src/api/command/os/GetBatteryStatusCommand.test.js.map +3 -3
- package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.js +1 -1
- package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.js.map +2 -2
- package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.test.js +1 -1
- package/lib/cjs/src/api/command/os/GetCustomImageSizeCommand.test.js.map +2 -2
- package/lib/cjs/src/api/command/os/GetOsVersionCommand.js +1 -1
- package/lib/cjs/src/api/command/os/GetOsVersionCommand.js.map +2 -2
- package/lib/cjs/src/api/command/os/GetOsVersionCommand.test.js +1 -1
- package/lib/cjs/src/api/command/os/GetOsVersionCommand.test.js.map +2 -2
- package/lib/cjs/src/api/command/os/ListAppsCommand.js +1 -1
- package/lib/cjs/src/api/command/os/ListAppsCommand.js.map +2 -2
- package/lib/cjs/src/api/command/os/ListAppsCommand.test.js +1 -1
- package/lib/cjs/src/api/command/os/ListAppsCommand.test.js.map +2 -2
- package/lib/cjs/src/api/command/os/ListLanguagePackCommand.js +1 -1
- package/lib/cjs/src/api/command/os/ListLanguagePackCommand.js.map +2 -2
- package/lib/cjs/src/api/command/os/ListLanguagePackCommand.test.js +1 -1
- package/lib/cjs/src/api/command/os/ListLanguagePackCommand.test.js.map +2 -2
- package/lib/cjs/src/api/command/os/LoadCertificateCommand.js +1 -1
- package/lib/cjs/src/api/command/os/LoadCertificateCommand.js.map +2 -2
- package/lib/cjs/src/api/command/os/LoadCertificateCommand.test.js +1 -1
- package/lib/cjs/src/api/command/os/LoadCertificateCommand.test.js.map +3 -3
- package/lib/cjs/src/api/command/os/OpenAppCommand.js +1 -1
- package/lib/cjs/src/api/command/os/OpenAppCommand.js.map +2 -2
- package/lib/cjs/src/api/command/os/OpenAppCommand.test.js +1 -1
- package/lib/cjs/src/api/command/os/OpenAppCommand.test.js.map +2 -2
- package/lib/cjs/src/api/command/use-case/SendCommandUseCase.test.js +1 -1
- package/lib/cjs/src/api/command/use-case/SendCommandUseCase.test.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.test.js.map +2 -2
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.test.js +1 -1
- package/lib/cjs/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.test.js.map +2 -2
- package/lib/cjs/src/api/transport/model/ConnectedDevice.js +1 -1
- package/lib/cjs/src/api/transport/model/ConnectedDevice.js.map +3 -3
- package/lib/cjs/src/api/transport/model/TransportConnectedDevice.js +1 -1
- package/lib/cjs/src/api/transport/model/TransportConnectedDevice.js.map +3 -3
- package/lib/cjs/src/internal/device-session/model/DeviceSession.js +1 -1
- package/lib/cjs/src/internal/device-session/model/DeviceSession.js.map +2 -2
- package/lib/cjs/src/internal/device-session/service/DefaultDeviceSessionService.js +1 -1
- package/lib/cjs/src/internal/device-session/service/DefaultDeviceSessionService.js.map +3 -3
- package/lib/cjs/src/internal/device-session/service/DefaultDeviceSessionService.test.js +1 -1
- package/lib/cjs/src/internal/device-session/service/DefaultDeviceSessionService.test.js.map +3 -3
- package/lib/cjs/src/internal/device-session/service/DeviceSessionService.js +1 -1
- package/lib/cjs/src/internal/device-session/service/DeviceSessionService.js.map +1 -1
- package/lib/cjs/src/internal/discovery/use-case/ConnectUseCase.js +1 -1
- package/lib/cjs/src/internal/discovery/use-case/ConnectUseCase.js.map +3 -3
- package/lib/esm/package.json +1 -1
- package/lib/esm/src/api/command/os/CloseAppCommand.js +1 -1
- package/lib/esm/src/api/command/os/CloseAppCommand.js.map +2 -2
- package/lib/esm/src/api/command/os/CloseAppCommand.test.js +1 -1
- package/lib/esm/src/api/command/os/CloseAppCommand.test.js.map +2 -2
- package/lib/esm/src/api/command/os/GetAppAndVersionCommand.js +1 -1
- package/lib/esm/src/api/command/os/GetAppAndVersionCommand.js.map +2 -2
- package/lib/esm/src/api/command/os/GetAppAndVersionCommand.test.js +1 -1
- package/lib/esm/src/api/command/os/GetAppAndVersionCommand.test.js.map +2 -2
- package/lib/esm/src/api/command/os/GetBatteryStatusCommand.js +1 -1
- package/lib/esm/src/api/command/os/GetBatteryStatusCommand.js.map +2 -2
- package/lib/esm/src/api/command/os/GetBatteryStatusCommand.test.js +1 -1
- package/lib/esm/src/api/command/os/GetBatteryStatusCommand.test.js.map +3 -3
- package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.js +1 -1
- package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.js.map +2 -2
- package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.test.js +1 -1
- package/lib/esm/src/api/command/os/GetCustomImageSizeCommand.test.js.map +2 -2
- package/lib/esm/src/api/command/os/GetOsVersionCommand.js +1 -1
- package/lib/esm/src/api/command/os/GetOsVersionCommand.js.map +2 -2
- package/lib/esm/src/api/command/os/GetOsVersionCommand.test.js +1 -1
- package/lib/esm/src/api/command/os/GetOsVersionCommand.test.js.map +2 -2
- package/lib/esm/src/api/command/os/ListAppsCommand.js +1 -1
- package/lib/esm/src/api/command/os/ListAppsCommand.js.map +2 -2
- package/lib/esm/src/api/command/os/ListAppsCommand.test.js +1 -1
- package/lib/esm/src/api/command/os/ListAppsCommand.test.js.map +2 -2
- package/lib/esm/src/api/command/os/ListLanguagePackCommand.js +1 -1
- package/lib/esm/src/api/command/os/ListLanguagePackCommand.js.map +2 -2
- package/lib/esm/src/api/command/os/ListLanguagePackCommand.test.js +1 -1
- package/lib/esm/src/api/command/os/ListLanguagePackCommand.test.js.map +2 -2
- package/lib/esm/src/api/command/os/LoadCertificateCommand.js +1 -1
- package/lib/esm/src/api/command/os/LoadCertificateCommand.js.map +2 -2
- package/lib/esm/src/api/command/os/LoadCertificateCommand.test.js +1 -1
- package/lib/esm/src/api/command/os/LoadCertificateCommand.test.js.map +3 -3
- package/lib/esm/src/api/command/os/OpenAppCommand.js +1 -1
- package/lib/esm/src/api/command/os/OpenAppCommand.js.map +2 -2
- package/lib/esm/src/api/command/os/OpenAppCommand.test.js +1 -1
- package/lib/esm/src/api/command/os/OpenAppCommand.test.js.map +2 -2
- package/lib/esm/src/api/command/use-case/SendCommandUseCase.test.js +1 -1
- package/lib/esm/src/api/command/use-case/SendCommandUseCase.test.js.map +2 -2
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.test.js.map +2 -2
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.test.js +1 -1
- package/lib/esm/src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.test.js.map +2 -2
- package/lib/esm/src/api/transport/model/ConnectedDevice.js +1 -1
- package/lib/esm/src/api/transport/model/ConnectedDevice.js.map +3 -3
- package/lib/esm/src/api/transport/model/TransportConnectedDevice.js +1 -1
- package/lib/esm/src/api/transport/model/TransportConnectedDevice.js.map +3 -3
- package/lib/esm/src/internal/device-session/model/DeviceSession.js +1 -1
- package/lib/esm/src/internal/device-session/model/DeviceSession.js.map +2 -2
- package/lib/esm/src/internal/device-session/service/DefaultDeviceSessionService.js +1 -1
- package/lib/esm/src/internal/device-session/service/DefaultDeviceSessionService.js.map +3 -3
- package/lib/esm/src/internal/device-session/service/DefaultDeviceSessionService.test.js +1 -1
- package/lib/esm/src/internal/device-session/service/DefaultDeviceSessionService.test.js.map +3 -3
- package/lib/esm/src/internal/discovery/use-case/ConnectUseCase.js +1 -1
- package/lib/esm/src/internal/discovery/use-case/ConnectUseCase.js.map +3 -3
- package/lib/types/src/api/command/Command.d.ts +4 -0
- package/lib/types/src/api/command/Command.d.ts.map +1 -1
- package/lib/types/src/api/command/os/CloseAppCommand.d.ts +1 -0
- package/lib/types/src/api/command/os/CloseAppCommand.d.ts.map +1 -1
- package/lib/types/src/api/command/os/GetAppAndVersionCommand.d.ts +1 -0
- package/lib/types/src/api/command/os/GetAppAndVersionCommand.d.ts.map +1 -1
- package/lib/types/src/api/command/os/GetBatteryStatusCommand.d.ts +1 -0
- package/lib/types/src/api/command/os/GetBatteryStatusCommand.d.ts.map +1 -1
- package/lib/types/src/api/command/os/GetCustomImageSizeCommand.d.ts +1 -0
- package/lib/types/src/api/command/os/GetCustomImageSizeCommand.d.ts.map +1 -1
- package/lib/types/src/api/command/os/GetOsVersionCommand.d.ts +1 -0
- package/lib/types/src/api/command/os/GetOsVersionCommand.d.ts.map +1 -1
- package/lib/types/src/api/command/os/ListAppsCommand.d.ts +1 -0
- package/lib/types/src/api/command/os/ListAppsCommand.d.ts.map +1 -1
- package/lib/types/src/api/command/os/ListLanguagePackCommand.d.ts +1 -0
- package/lib/types/src/api/command/os/ListLanguagePackCommand.d.ts.map +1 -1
- package/lib/types/src/api/command/os/LoadCertificateCommand.d.ts +1 -0
- package/lib/types/src/api/command/os/LoadCertificateCommand.d.ts.map +1 -1
- package/lib/types/src/api/command/os/OpenAppCommand.d.ts +1 -0
- package/lib/types/src/api/command/os/OpenAppCommand.d.ts.map +1 -1
- package/lib/types/src/api/transport/model/ConnectedDevice.d.ts +1 -1
- package/lib/types/src/api/transport/model/ConnectedDevice.d.ts.map +1 -1
- package/lib/types/src/api/transport/model/TransportConnectedDevice.d.ts +3 -1
- package/lib/types/src/api/transport/model/TransportConnectedDevice.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/model/DeviceSession.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/service/DefaultDeviceSessionService.d.ts +7 -5
- package/lib/types/src/internal/device-session/service/DefaultDeviceSessionService.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/service/DeviceSessionService.d.ts +28 -1
- package/lib/types/src/internal/device-session/service/DeviceSessionService.d.ts.map +1 -1
- package/lib/types/src/internal/discovery/use-case/ConnectUseCase.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +3 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/api/device-action/os/CallTaskInAppDeviceAction/CallTaskInAppDeviceAction.test.ts"],
|
|
4
|
-
"sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports:0 */\nimport { Left, Right } from \"purify-ts\";\nimport { type Mock } from \"vitest\";\nimport { assign, createMachine } from \"xstate\";\n\nimport { type Apdu } from \"@api/apdu/model/Apdu\";\nimport { ApduBuilder } from \"@api/apdu/utils/ApduBuilder\";\nimport { CommandResultFactory } from \"@api/command/model/CommandResult\";\nimport { makeDeviceActionInternalApiMock } from \"@api/device-action/__test-utils__/makeInternalApi\";\nimport { testDeviceActionStates } from \"@api/device-action/__test-utils__/testDeviceActionStates\";\nimport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nimport { UserInteractionRequired } from \"@api/device-action/model/UserInteractionRequired\";\nimport { UnknownDAError } from \"@api/device-action/os/Errors\";\nimport { OpenAppDeviceAction } from \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\";\nimport { type Command } from \"@api/types\";\nimport { UnknownDeviceExchangeError } from \"@root/src\";\n\nimport { CallTaskInAppDeviceAction } from \"./CallTaskInAppDeviceAction\";\nimport {\n type CallTaskInAppDAError,\n type CallTaskInAppDAIntermediateValue,\n type CallTaskInAppDAOutput,\n} from \"./CallTaskInAppDeviceActionTypes\";\n\nvi.mock(\n \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\",\n async (importOriginal) => {\n const original =\n await importOriginal<\n typeof import(\"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\")\n >();\n return {\n ...original,\n OpenAppDeviceAction: vi.fn(() => ({\n ...original.OpenAppDeviceAction,\n makeStateMachine: vi.fn(),\n })),\n };\n },\n);\n\nconst setupOpenAppDAMock = (error?: unknown) => {\n (OpenAppDeviceAction as Mock).mockImplementation(() => ({\n makeStateMachine: vi.fn().mockImplementation(() =>\n createMachine({\n initial: \"pending\",\n states: {\n pending: {\n entry: assign({\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n }),\n after: {\n 0: \"done\",\n },\n },\n done: {\n type: \"final\",\n },\n },\n output: () => (error ? Left(error) : Right(undefined)),\n }),\n ),\n }));\n};\n\ndescribe(\"CallTaskInAppDeviceAction\", () => {\n const callMyTask = vi.fn();\n\n const extractDependenciesMock = () => ({\n callTask: callMyTask,\n });\n\n const { sendCommand: apiSendCommandMock } = makeDeviceActionInternalApiMock();\n\n const commandParams = {\n paramString: \"aParameter\",\n paramNumber: 1234,\n };\n const mockedCommandResponse = {\n aNumber: 5678,\n aString: \"mockedResponseString\",\n };\n beforeEach(() => {\n vi.resetAllMocks();\n });\n\n describe(\"without mocking extractDependencies\", () => {\n it(\"should call sendCommand on internalApi with the correct parameters\", async () => {\n setupOpenAppDAMock();\n apiSendCommandMock.mockResolvedValue(\n CommandResultFactory({ data: undefined }),\n );\n\n const deviceAction = new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n await new Promise<void>((resolve, reject) => {\n deviceAction\n ._execute(makeDeviceActionInternalApiMock())\n .observable.subscribe({\n error: () => reject(),\n complete: () => resolve(),\n next: () => {},\n });\n });\n\n expect(apiSendCommandMock).toHaveBeenCalledWith(\n new TestCommand(commandParams),\n );\n });\n });\n\n describe(\"error cases\", () => {\n it(\"should error and output the error if the open app fails\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock(new UnknownDAError(\"Mocked error\"));\n\n const expectedStates: MyCommandCallTaskDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Error,\n error: new UnknownDAError(\"Mocked error\"),\n },\n ];\n\n testDeviceActionStates(\n new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n }),\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n\n it(\"should error and output an error if the call task fails\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n callMyTask.mockResolvedValue(\n CommandResultFactory({\n error: new UnknownDeviceExchangeError(\"Mocked error\"),\n }),\n );\n\n const deviceAction = new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandCallTaskDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Error,\n error: new UnknownDeviceExchangeError(\"Mocked error\"),\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n });\n\n describe(\"success cases\", () => {\n it(\"should succeed and output the command result if the send command succeeds\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n callMyTask.mockResolvedValue(\n CommandResultFactory({ data: mockedCommandResponse }),\n );\n\n const deviceAction = new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandCallTaskDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Completed,\n output: mockedCommandResponse,\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n\n it(\"should succeed while skipping OpenApp\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n callMyTask.mockResolvedValue(\n CommandResultFactory({ data: mockedCommandResponse }),\n );\n\n const deviceAction = new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: true,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandCallTaskDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Completed,\n output: mockedCommandResponse,\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n });\n});\n\ntype MyCommandResponse = {\n aNumber: number;\n aString: string;\n};\n\ntype MyCommandParams = {\n paramString: string;\n paramNumber: number;\n};\n\nclass TestCommand implements Command<MyCommandResponse, MyCommandParams> {\n params: MyCommandParams;\n constructor(params: MyCommandParams) {\n this.params = params;\n }\n getApdu(): Apdu {\n return new ApduBuilder({ cla: 0x00, ins: 0x01, p1: 0x02, p2: 0x03 })\n .add32BitUIntToData(this.params.paramNumber)\n .addAsciiStringToData(this.params.paramString)\n .build();\n }\n parseResponse() {\n return CommandResultFactory({ data: { aNumber: 1, aString: \"aString\" } });\n }\n}\n\ntype MyCommandCallTaskDAState = DeviceActionState<\n CallTaskInAppDAOutput<MyCommandResponse>,\n CallTaskInAppDAError<UnknownDAError>,\n CallTaskInAppDAIntermediateValue<\n UserInteractionRequired.None | UserInteractionRequired.VerifyAddress\n >\n>;\n"],
|
|
5
|
-
"mappings": "aACA,IAAAA,EAA4B,qBAE5BC,EAAsC,kBAGtCC,EAA4B,uCAC5BC,EAAqC,4CACrCC,EAAgD,6DAChDC,EAAuC,oEACvCC,EAGO,sDACPC,EAAwC,4DACxCC,EAA+B,wCAC/BC,EAAoC,yEAEpCC,EAA2C,qBAE3CC,EAA0C,uCAO1C,GAAG,KACD,gEACA,MAAOC,GAAmB,CACxB,MAAMC,EACJ,MAAMD,EAEJ,EACJ,MAAO,CACL,GAAGC,EACH,oBAAqB,GAAG,GAAG,KAAO,CAChC,GAAGA,EAAS,oBACZ,iBAAkB,GAAG,GAAG,CAC1B,EAAE,CACJ,CACF,CACF,EAEA,MAAMC,EAAsBC,GAAoB,CAC7C,sBAA6B,mBAAmB,KAAO,CACtD,iBAAkB,GAAG,GAAG,EAAE,mBAAmB,OAC3C,iBAAc,CACZ,QAAS,UACT,OAAQ,CACN,QAAS,CACP,SAAO,UAAO,CACZ,kBAAmB,CACjB,wBAAyB,0BAAwB,cACnD,CACF,CAAC,EACD,MAAO,CACL,EAAG,MACL,CACF,EACA,KAAM,CACJ,KAAM,OACR,CACF,EACA,OAAQ,IAAOA,KAAQ,QAAKA,CAAK,KAAI,SAAM,MAAS,CACtD,CAAC,CACH,CACF,EAAE,CACJ,EAEA,SAAS,4BAA6B,IAAM,CAC1C,MAAMC,EAAa,GAAG,GAAG,EAEnBC,EAA0B,KAAO,CACrC,SAAUD,CACZ,GAEM,CAAE,YAAaE,CAAmB,KAAI,mCAAgC,EAEtEC,EAAgB,CACpB,YAAa,aACb,YAAa,IACf,EACMC,EAAwB,CAC5B,QAAS,KACT,QAAS,sBACX,EACA,WAAW,IAAM,CACf,GAAG,cAAc,CACnB,CAAC,EAED,SAAS,sCAAuC,IAAM,CACpD,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mB,QAC3B,kBAAmB,CACjB,wBAAyB,0BAAwB,cACnD,CACF,EACA,CACE,OAAQ,qBAAmB,QAC3B,kBAAmB,CACjB,wBAAyB,0BAAwB,aACnD,CACF,EACA,CACE,OAAQ,qBAAmB,UAC3B,OAAQN,CACV,CACF,KAEA,0BACEC,EACAK,KACA,mCAAgC,EAChC,CACE,OAAQF,EACR,QAASC,CACX,CACF,CACF,CAAC,CAAC,EAEJ,GAAG,wCAAyC,IAC1C,IAAI,QAAc,CAACD,EAASC,IAAW,CACrCX,EAAmB,EAEnBE,EAAW,qBACT,wBAAqB,CAAE,KAAMI,CAAsB,CAAC,CACtD,EAEA,MAAMC,EAAe,IAAI,4BAA0B,CACjD,MAAO,CACL,KAAM,MAAOC,GACX,MAAMA,EAAY,YAAY,IAAIC,EAAYJ,CAAa,CAAC,EAC9D,QAAS,QACT,wBAAyB,0BAAwB,cACjD,YAAa,EACf,CACF,CAAC,EAED,GAAG,MAAME,EAAc,qBAAqB,EAAE,mBAC5CJ,CACF,EAEA,MAAMS,EAA6C,CACjD,CACE,OAAQ,qBAAmB,QAC3B,kBAAmB,CACjB,wBAAyB,0BAAwB,aACnD,CACF,EACA,CACE,OAAQ,qBAAmB,UAC3B,OAAQN,CACV,CACF,KAEA,0BACEC,EACAK,KACA,mCAAgC,EAChC,CACE,OAAQF,EACR,QAASC,CACX,CACF,CACF,CAAC,CAAC,CACN,CAAC,CACH,CAAC,EAYD,MAAMF,CAAmE,
|
|
4
|
+
"sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports:0 */\nimport { Left, Right } from \"purify-ts\";\nimport { type Mock } from \"vitest\";\nimport { assign, createMachine } from \"xstate\";\n\nimport { type Apdu } from \"@api/apdu/model/Apdu\";\nimport { ApduBuilder } from \"@api/apdu/utils/ApduBuilder\";\nimport { CommandResultFactory } from \"@api/command/model/CommandResult\";\nimport { makeDeviceActionInternalApiMock } from \"@api/device-action/__test-utils__/makeInternalApi\";\nimport { testDeviceActionStates } from \"@api/device-action/__test-utils__/testDeviceActionStates\";\nimport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nimport { UserInteractionRequired } from \"@api/device-action/model/UserInteractionRequired\";\nimport { UnknownDAError } from \"@api/device-action/os/Errors\";\nimport { OpenAppDeviceAction } from \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\";\nimport { type Command } from \"@api/types\";\nimport { UnknownDeviceExchangeError } from \"@root/src\";\n\nimport { CallTaskInAppDeviceAction } from \"./CallTaskInAppDeviceAction\";\nimport {\n type CallTaskInAppDAError,\n type CallTaskInAppDAIntermediateValue,\n type CallTaskInAppDAOutput,\n} from \"./CallTaskInAppDeviceActionTypes\";\n\nvi.mock(\n \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\",\n async (importOriginal) => {\n const original =\n await importOriginal<\n typeof import(\"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\")\n >();\n return {\n ...original,\n OpenAppDeviceAction: vi.fn(() => ({\n ...original.OpenAppDeviceAction,\n makeStateMachine: vi.fn(),\n })),\n };\n },\n);\n\nconst setupOpenAppDAMock = (error?: unknown) => {\n (OpenAppDeviceAction as Mock).mockImplementation(() => ({\n makeStateMachine: vi.fn().mockImplementation(() =>\n createMachine({\n initial: \"pending\",\n states: {\n pending: {\n entry: assign({\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n }),\n after: {\n 0: \"done\",\n },\n },\n done: {\n type: \"final\",\n },\n },\n output: () => (error ? Left(error) : Right(undefined)),\n }),\n ),\n }));\n};\n\ndescribe(\"CallTaskInAppDeviceAction\", () => {\n const callMyTask = vi.fn();\n\n const extractDependenciesMock = () => ({\n callTask: callMyTask,\n });\n\n const { sendCommand: apiSendCommandMock } = makeDeviceActionInternalApiMock();\n\n const commandParams = {\n paramString: \"aParameter\",\n paramNumber: 1234,\n };\n const mockedCommandResponse = {\n aNumber: 5678,\n aString: \"mockedResponseString\",\n };\n beforeEach(() => {\n vi.resetAllMocks();\n });\n\n describe(\"without mocking extractDependencies\", () => {\n it(\"should call sendCommand on internalApi with the correct parameters\", async () => {\n setupOpenAppDAMock();\n apiSendCommandMock.mockResolvedValue(\n CommandResultFactory({ data: undefined }),\n );\n\n const deviceAction = new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n await new Promise<void>((resolve, reject) => {\n deviceAction\n ._execute(makeDeviceActionInternalApiMock())\n .observable.subscribe({\n error: () => reject(),\n complete: () => resolve(),\n next: () => {},\n });\n });\n\n expect(apiSendCommandMock).toHaveBeenCalledWith(\n new TestCommand(commandParams),\n );\n });\n });\n\n describe(\"error cases\", () => {\n it(\"should error and output the error if the open app fails\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock(new UnknownDAError(\"Mocked error\"));\n\n const expectedStates: MyCommandCallTaskDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Error,\n error: new UnknownDAError(\"Mocked error\"),\n },\n ];\n\n testDeviceActionStates(\n new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n }),\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n\n it(\"should error and output an error if the call task fails\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n callMyTask.mockResolvedValue(\n CommandResultFactory({\n error: new UnknownDeviceExchangeError(\"Mocked error\"),\n }),\n );\n\n const deviceAction = new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandCallTaskDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Error,\n error: new UnknownDeviceExchangeError(\"Mocked error\"),\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n });\n\n describe(\"success cases\", () => {\n it(\"should succeed and output the command result if the send command succeeds\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n callMyTask.mockResolvedValue(\n CommandResultFactory({ data: mockedCommandResponse }),\n );\n\n const deviceAction = new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandCallTaskDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Completed,\n output: mockedCommandResponse,\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n\n it(\"should succeed while skipping OpenApp\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n callMyTask.mockResolvedValue(\n CommandResultFactory({ data: mockedCommandResponse }),\n );\n\n const deviceAction = new CallTaskInAppDeviceAction({\n input: {\n task: async (internalApi) =>\n await internalApi.sendCommand(new TestCommand(commandParams)),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: true,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandCallTaskDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Completed,\n output: mockedCommandResponse,\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n });\n});\n\ntype MyCommandResponse = {\n aNumber: number;\n aString: string;\n};\n\ntype MyCommandParams = {\n paramString: string;\n paramNumber: number;\n};\n\nclass TestCommand implements Command<MyCommandResponse, MyCommandParams> {\n readonly name = \"testCommand\";\n\n params: MyCommandParams;\n constructor(params: MyCommandParams) {\n this.params = params;\n }\n getApdu(): Apdu {\n return new ApduBuilder({ cla: 0x00, ins: 0x01, p1: 0x02, p2: 0x03 })\n .add32BitUIntToData(this.params.paramNumber)\n .addAsciiStringToData(this.params.paramString)\n .build();\n }\n parseResponse() {\n return CommandResultFactory({ data: { aNumber: 1, aString: \"aString\" } });\n }\n}\n\ntype MyCommandCallTaskDAState = DeviceActionState<\n CallTaskInAppDAOutput<MyCommandResponse>,\n CallTaskInAppDAError<UnknownDAError>,\n CallTaskInAppDAIntermediateValue<\n UserInteractionRequired.None | UserInteractionRequired.VerifyAddress\n >\n>;\n"],
|
|
5
|
+
"mappings": "aACA,IAAAA,EAA4B,qBAE5BC,EAAsC,kBAGtCC,EAA4B,uCAC5BC,EAAqC,4CACrCC,EAAgD,6DAChDC,EAAuC,oEACvCC,EAGO,sDACPC,EAAwC,4DACxCC,EAA+B,wCAC/BC,EAAoC,yEAEpCC,EAA2C,qBAE3CC,EAA0C,uCAO1C,GAAG,KACD,gEACA,MAAOC,GAAmB,CACxB,MAAMC,EACJ,MAAMD,EAEJ,EACJ,MAAO,CACL,GAAGC,EACH,oBAAqB,GAAG,GAAG,KAAO,CAChC,GAAGA,EAAS,oBACZ,iBAAkB,GAAG,GAAG,CAC1B,EAAE,CACJ,CACF,CACF,EAEA,MAAMC,EAAsBC,GAAoB,CAC7C,sBAA6B,mBAAmB,KAAO,CACtD,iBAAkB,GAAG,GAAG,EAAE,mBAAmB,OAC3C,iBAAc,CACZ,QAAS,UACT,OAAQ,CACN,QAAS,CACP,SAAO,UAAO,CACZ,kBAAmB,CACjB,wBAAyB,0BAAwB,cACnD,CACF,CAAC,EACD,MAAO,CACL,EAAG,MACL,CACF,EACA,KAAM,CACJ,KAAM,OACR,CACF,EACA,OAAQ,IAAOA,KAAQ,QAAKA,CAAK,KAAI,SAAM,MAAS,CACtD,CAAC,CACH,CACF,EAAE,CACJ,EAEA,SAAS,4BAA6B,IAAM,CAC1C,MAAMC,EAAa,GAAG,GAAG,EAEnBC,EAA0B,KAAO,CACrC,SAAUD,CACZ,GAEM,CAAE,YAAaE,CAAmB,KAAI,mCAAgC,EAEtEC,EAAgB,CACpB,YAAa,aACb,YAAa,IACf,EACMC,EAAwB,CAC5B,QAAS,KACT,QAAS,sBACX,EACA,WAAW,IAAM,CACf,GAAG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AAE,KAAM,CAAE,QAAS,EAAG,QAAS,SAAU,CAAE,CAAC,CAC1E,CACF",
|
|
6
6
|
"names": ["import_purify_ts", "import_xstate", "import_ApduBuilder", "import_CommandResult", "import_makeInternalApi", "import_testDeviceActionStates", "import_DeviceActionState", "import_UserInteractionRequired", "import_Errors", "import_OpenAppDeviceAction", "import_src", "import_CallTaskInAppDeviceAction", "importOriginal", "original", "setupOpenAppDAMock", "error", "callMyTask", "extractDependenciesMock", "apiSendCommandMock", "commandParams", "mockedCommandResponse", "deviceAction", "internalApi", "TestCommand", "resolve", "reject", "expectedStates", "params"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var y=require("purify-ts"),C=require("xstate"),k=require("../../../apdu/utils/ApduBuilder"),c=require("../../../command/model/CommandResult"),i=require("../../../device-action/__test-utils__/makeInternalApi"),l=require("../../../device-action/__test-utils__/testDeviceActionStates"),n=require("../../../device-action/model/DeviceActionState"),e=require("../../../device-action/model/UserInteractionRequired"),v=require("../../../device-action/os/Errors"),I=require("../../../device-action/os/OpenAppDeviceAction/OpenAppDeviceAction"),D=require("../../../../../src"),s=require("./SendCommandInAppDeviceAction");vi.mock("@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction",async r=>({...await r(),OpenAppDeviceAction:vi.fn(()=>({makeStateMachine:vi.fn()}))}));const A=r=>{I.OpenAppDeviceAction.mockImplementation(()=>({makeStateMachine:vi.fn().mockImplementation(()=>(0,C.createMachine)({initial:"pending",states:{pending:{entry:(0,C.assign)({intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.ConfirmOpenApp}}),after:{0:"done"}},done:{type:"final"}},output:()=>r?(0,y.Left)(r):(0,y.Right)(void 0)}))}))};describe("SendCommandInAppDeviceAction",()=>{const r=vi.fn(),m=()=>({sendCommand:r}),{sendCommand:S}=(0,i.makeDeviceActionInternalApiMock)(),
|
|
1
|
+
"use strict";var y=require("purify-ts"),C=require("xstate"),k=require("../../../apdu/utils/ApduBuilder"),c=require("../../../command/model/CommandResult"),i=require("../../../device-action/__test-utils__/makeInternalApi"),l=require("../../../device-action/__test-utils__/testDeviceActionStates"),n=require("../../../device-action/model/DeviceActionState"),e=require("../../../device-action/model/UserInteractionRequired"),v=require("../../../device-action/os/Errors"),I=require("../../../device-action/os/OpenAppDeviceAction/OpenAppDeviceAction"),D=require("../../../../../src"),s=require("./SendCommandInAppDeviceAction");vi.mock("@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction",async r=>({...await r(),OpenAppDeviceAction:vi.fn(()=>({makeStateMachine:vi.fn()}))}));const A=r=>{I.OpenAppDeviceAction.mockImplementation(()=>({makeStateMachine:vi.fn().mockImplementation(()=>(0,C.createMachine)({initial:"pending",states:{pending:{entry:(0,C.assign)({intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.ConfirmOpenApp}}),after:{0:"done"}},done:{type:"final"}},output:()=>r?(0,y.Left)(r):(0,y.Right)(void 0)}))}))};describe("SendCommandInAppDeviceAction",()=>{const r=vi.fn(),m=()=>({sendCommand:r}),{sendCommand:S}=(0,i.makeDeviceActionInternalApiMock)(),d={paramString:"aParameter",paramNumber:1234},f={aNumber:5678,aString:"mockedResponseString"};beforeEach(()=>{vi.resetAllMocks()}),describe("without mocking extractDependencies",()=>{it("should call sendCommand on internalApi with the correct parameters",async()=>{A(),S.mockResolvedValue((0,c.CommandResultFactory)({data:void 0}));const o=new s.SendCommandInAppDeviceAction({input:{command:new p(d),appName:"MyApp",requiredUserInteraction:e.UserInteractionRequired.VerifyAddress,skipOpenApp:!1}});await new Promise((a,t)=>{o._execute((0,i.makeDeviceActionInternalApiMock)()).observable.subscribe({error:()=>t(),complete:()=>a(),next:()=>{}})}),expect(S).toHaveBeenCalledWith(new p(d))})}),describe("error cases",()=>{it("should error and output the error if the open app fails",()=>new Promise((o,a)=>{A(new v.UnknownDAError("Mocked error"));const t=[{status:n.DeviceActionStatus.Pending,intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.None}},{status:n.DeviceActionStatus.Pending,intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.ConfirmOpenApp}},{status:n.DeviceActionStatus.Error,error:new v.UnknownDAError("Mocked error")}];(0,l.testDeviceActionStates)(new s.SendCommandInAppDeviceAction({input:{command:new p(d),appName:"MyApp",requiredUserInteraction:e.UserInteractionRequired.VerifyAddress,skipOpenApp:!1}}),t,(0,i.makeDeviceActionInternalApiMock)(),{onDone:o,onError:a})})),it("should error and output an error if the send command fails",()=>new Promise((o,a)=>{A(),r.mockResolvedValue((0,c.CommandResultFactory)({error:new D.UnknownDeviceExchangeError("Mocked error")}));const t=new s.SendCommandInAppDeviceAction({input:{command:new p(d),appName:"MyApp",requiredUserInteraction:e.UserInteractionRequired.VerifyAddress,skipOpenApp:!1}});vi.spyOn(t,"extractDependencies").mockImplementation(m);const u=[{status:n.DeviceActionStatus.Pending,intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.None}},{status:n.DeviceActionStatus.Pending,intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.ConfirmOpenApp}},{status:n.DeviceActionStatus.Pending,intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.VerifyAddress}},{status:n.DeviceActionStatus.Error,error:new D.UnknownDeviceExchangeError("Mocked error")}];(0,l.testDeviceActionStates)(t,u,(0,i.makeDeviceActionInternalApiMock)(),{onDone:o,onError:a})}))}),describe("success cases",()=>{it("should succeed and output the command result if the send command succeeds",()=>new Promise((o,a)=>{A(),r.mockResolvedValue((0,c.CommandResultFactory)({data:f}));const t=new s.SendCommandInAppDeviceAction({input:{command:new p(d),appName:"MyApp",requiredUserInteraction:e.UserInteractionRequired.VerifyAddress,skipOpenApp:!1}});vi.spyOn(t,"extractDependencies").mockImplementation(m);const u=[{status:n.DeviceActionStatus.Pending,intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.None}},{status:n.DeviceActionStatus.Pending,intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.ConfirmOpenApp}},{status:n.DeviceActionStatus.Pending,intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.VerifyAddress}},{status:n.DeviceActionStatus.Completed,output:f}];(0,l.testDeviceActionStates)(t,u,(0,i.makeDeviceActionInternalApiMock)(),{onDone:o,onError:a})})),it("should succeed while skipping OpenApp",()=>new Promise((o,a)=>{A(),r.mockResolvedValue((0,c.CommandResultFactory)({data:f}));const t=new s.SendCommandInAppDeviceAction({input:{command:new p(d),appName:"MyApp",requiredUserInteraction:e.UserInteractionRequired.VerifyAddress,skipOpenApp:!0}});vi.spyOn(t,"extractDependencies").mockImplementation(m);const u=[{status:n.DeviceActionStatus.Pending,intermediateValue:{requiredUserInteraction:e.UserInteractionRequired.VerifyAddress}},{status:n.DeviceActionStatus.Completed,output:f}];(0,l.testDeviceActionStates)(t,u,(0,i.makeDeviceActionInternalApiMock)(),{onDone:o,onError:a})}))})});class p{name="testCommand";params;constructor(m){this.params=m}getApdu(){return new k.ApduBuilder({cla:0,ins:1,p1:2,p2:3}).add32BitUIntToData(this.params.paramNumber).addAsciiStringToData(this.params.paramString).build()}parseResponse(){return(0,c.CommandResultFactory)({data:{aNumber:1,aString:"aString"}})}}
|
|
2
2
|
//# sourceMappingURL=SendCommandInAppDeviceAction.test.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/api/device-action/os/SendCommandInAppDeviceAction/SendCommandInAppDeviceAction.test.ts"],
|
|
4
|
-
"sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports:0 */\nimport { Left, Right } from \"purify-ts\";\nimport { type Mock } from \"vitest\";\nimport { assign, createMachine } from \"xstate\";\n\nimport { type Apdu } from \"@api/apdu/model/Apdu\";\nimport { ApduBuilder } from \"@api/apdu/utils/ApduBuilder\";\nimport { CommandResultFactory } from \"@api/command/model/CommandResult\";\nimport { makeDeviceActionInternalApiMock } from \"@api/device-action/__test-utils__/makeInternalApi\";\nimport { testDeviceActionStates } from \"@api/device-action/__test-utils__/testDeviceActionStates\";\nimport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nimport { UserInteractionRequired } from \"@api/device-action/model/UserInteractionRequired\";\nimport { UnknownDAError } from \"@api/device-action/os/Errors\";\nimport { OpenAppDeviceAction } from \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\";\nimport { type Command } from \"@api/types\";\nimport { UnknownDeviceExchangeError } from \"@root/src\";\n\nimport { SendCommandInAppDeviceAction } from \"./SendCommandInAppDeviceAction\";\nimport {\n type SendCommandInAppDAError,\n type SendCommandInAppDAIntermediateValue,\n type SendCommandInAppDAOutput,\n} from \"./SendCommandInAppDeviceActionTypes\";\n\nvi.mock(\n \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\",\n async (importOriginal) => {\n const original =\n await importOriginal<\n typeof import(\"../OpenAppDeviceAction/OpenAppDeviceAction\")\n >();\n\n return {\n ...original,\n OpenAppDeviceAction: vi.fn(() => ({\n makeStateMachine: vi.fn(),\n })),\n };\n },\n);\n\nconst setupOpenAppDAMock = (error?: unknown) => {\n (OpenAppDeviceAction as Mock).mockImplementation(() => ({\n makeStateMachine: vi.fn().mockImplementation(() =>\n createMachine({\n initial: \"pending\",\n states: {\n pending: {\n entry: assign({\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n }),\n after: {\n 0: \"done\",\n },\n },\n done: {\n type: \"final\",\n },\n },\n output: () => (error ? Left(error) : Right(undefined)),\n }),\n ),\n }));\n};\n\ndescribe(\"SendCommandInAppDeviceAction\", () => {\n const sendMyCommand = vi.fn();\n\n const extractDependenciesMock = () => ({\n sendCommand: sendMyCommand,\n });\n\n const { sendCommand: apiSendCommandMock } = makeDeviceActionInternalApiMock();\n\n const commandParams = {\n paramString: \"aParameter\",\n paramNumber: 1234,\n };\n const mockedCommandResponse = {\n aNumber: 5678,\n aString: \"mockedResponseString\",\n };\n beforeEach(() => {\n vi.resetAllMocks();\n });\n\n describe(\"without mocking extractDependencies\", () => {\n it(\"should call sendCommand on internalApi with the correct parameters\", async () => {\n setupOpenAppDAMock();\n apiSendCommandMock.mockResolvedValue(\n CommandResultFactory({ data: undefined }),\n );\n\n const deviceAction = new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n await new Promise<void>((resolve, reject) => {\n deviceAction\n ._execute(makeDeviceActionInternalApiMock())\n .observable.subscribe({\n error: () => reject(),\n complete: () => resolve(),\n next: () => {},\n });\n });\n\n expect(apiSendCommandMock).toHaveBeenCalledWith(\n new TestCommand(commandParams),\n );\n });\n });\n\n describe(\"error cases\", () => {\n it(\"should error and output the error if the open app fails\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock(new UnknownDAError(\"Mocked error\"));\n\n const expectedStates: MyCommandSendCommandDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Error,\n error: new UnknownDAError(\"Mocked error\"),\n },\n ];\n\n testDeviceActionStates(\n new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n }),\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n\n it(\"should error and output an error if the send command fails\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n sendMyCommand.mockResolvedValue(\n CommandResultFactory({\n error: new UnknownDeviceExchangeError(\"Mocked error\"),\n }),\n );\n\n const deviceAction = new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandSendCommandDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Error,\n error: new UnknownDeviceExchangeError(\"Mocked error\"),\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n });\n\n describe(\"success cases\", () => {\n it(\"should succeed and output the command result if the send command succeeds\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n sendMyCommand.mockResolvedValue(\n CommandResultFactory({ data: mockedCommandResponse }),\n );\n\n const deviceAction = new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandSendCommandDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Completed,\n output: mockedCommandResponse,\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n\n it(\"should succeed while skipping OpenApp\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n sendMyCommand.mockResolvedValue(\n CommandResultFactory({ data: mockedCommandResponse }),\n );\n\n const deviceAction = new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: true,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandSendCommandDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Completed,\n output: mockedCommandResponse,\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n });\n});\n\ntype MyCommandResponse = {\n aNumber: number;\n aString: string;\n};\n\ntype MyCommandParams = {\n paramString: string;\n paramNumber: number;\n};\n\nclass TestCommand implements Command<MyCommandResponse, MyCommandParams> {\n params: MyCommandParams;\n constructor(params: MyCommandParams) {\n this.params = params;\n }\n getApdu(): Apdu {\n return new ApduBuilder({ cla: 0x00, ins: 0x01, p1: 0x02, p2: 0x03 })\n .add32BitUIntToData(this.params.paramNumber)\n .addAsciiStringToData(this.params.paramString)\n .build();\n }\n parseResponse() {\n return CommandResultFactory({ data: { aNumber: 1, aString: \"aString\" } });\n }\n}\n\ntype MyCommandSendCommandDAState = DeviceActionState<\n SendCommandInAppDAOutput<MyCommandResponse>,\n SendCommandInAppDAError<UnknownDAError>,\n SendCommandInAppDAIntermediateValue<\n UserInteractionRequired.None | UserInteractionRequired.VerifyAddress\n >\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,EAEnBE,EAAc,qBACZ,wBAAqB,CAAE,KAAMI,CAAsB,CAAC,CACtD,EAEA,MAAMC,EAAe,IAAI,+BAA6B,CACpD,MAAO,CACL,QAAS,IAAIC,EAAYH,CAAa,EACtC,QAAS,QACT,wBAAyB,0BAAwB,cACjD,YAAa,EACf,CACF,CAAC,EAED,GAAG,MAAME,EAAc,qBAAqB,EAAE,mBAC5CJ,CACF,EAEA,MAAMQ,EAAgD,CACpD,CACE,OAAQ,qBAAmB,QAC3B,kBAAmB,CACjB,wBAAyB,0BAAwB,aACnD,CACF,EACA,CACE,OAAQ,qBAAmB,UAC3B,OAAQL,CACV,CACF,KAEA,0BACEC,EACAI,KACA,mCAAgC,EAChC,CACE,OAAQF,EACR,QAASC,CACX,CACF,CACF,CAAC,CAAC,CACN,CAAC,CACH,CAAC,EAYD,MAAMF,CAAmE,
|
|
4
|
+
"sourcesContent": ["/* eslint @typescript-eslint/consistent-type-imports:0 */\nimport { Left, Right } from \"purify-ts\";\nimport { type Mock } from \"vitest\";\nimport { assign, createMachine } from \"xstate\";\n\nimport { type Apdu } from \"@api/apdu/model/Apdu\";\nimport { ApduBuilder } from \"@api/apdu/utils/ApduBuilder\";\nimport { CommandResultFactory } from \"@api/command/model/CommandResult\";\nimport { makeDeviceActionInternalApiMock } from \"@api/device-action/__test-utils__/makeInternalApi\";\nimport { testDeviceActionStates } from \"@api/device-action/__test-utils__/testDeviceActionStates\";\nimport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nimport { UserInteractionRequired } from \"@api/device-action/model/UserInteractionRequired\";\nimport { UnknownDAError } from \"@api/device-action/os/Errors\";\nimport { OpenAppDeviceAction } from \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\";\nimport { type Command } from \"@api/types\";\nimport { UnknownDeviceExchangeError } from \"@root/src\";\n\nimport { SendCommandInAppDeviceAction } from \"./SendCommandInAppDeviceAction\";\nimport {\n type SendCommandInAppDAError,\n type SendCommandInAppDAIntermediateValue,\n type SendCommandInAppDAOutput,\n} from \"./SendCommandInAppDeviceActionTypes\";\n\nvi.mock(\n \"@api/device-action/os/OpenAppDeviceAction/OpenAppDeviceAction\",\n async (importOriginal) => {\n const original =\n await importOriginal<\n typeof import(\"../OpenAppDeviceAction/OpenAppDeviceAction\")\n >();\n\n return {\n ...original,\n OpenAppDeviceAction: vi.fn(() => ({\n makeStateMachine: vi.fn(),\n })),\n };\n },\n);\n\nconst setupOpenAppDAMock = (error?: unknown) => {\n (OpenAppDeviceAction as Mock).mockImplementation(() => ({\n makeStateMachine: vi.fn().mockImplementation(() =>\n createMachine({\n initial: \"pending\",\n states: {\n pending: {\n entry: assign({\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n }),\n after: {\n 0: \"done\",\n },\n },\n done: {\n type: \"final\",\n },\n },\n output: () => (error ? Left(error) : Right(undefined)),\n }),\n ),\n }));\n};\n\ndescribe(\"SendCommandInAppDeviceAction\", () => {\n const sendMyCommand = vi.fn();\n\n const extractDependenciesMock = () => ({\n sendCommand: sendMyCommand,\n });\n\n const { sendCommand: apiSendCommandMock } = makeDeviceActionInternalApiMock();\n\n const commandParams = {\n paramString: \"aParameter\",\n paramNumber: 1234,\n };\n const mockedCommandResponse = {\n aNumber: 5678,\n aString: \"mockedResponseString\",\n };\n beforeEach(() => {\n vi.resetAllMocks();\n });\n\n describe(\"without mocking extractDependencies\", () => {\n it(\"should call sendCommand on internalApi with the correct parameters\", async () => {\n setupOpenAppDAMock();\n apiSendCommandMock.mockResolvedValue(\n CommandResultFactory({ data: undefined }),\n );\n\n const deviceAction = new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n await new Promise<void>((resolve, reject) => {\n deviceAction\n ._execute(makeDeviceActionInternalApiMock())\n .observable.subscribe({\n error: () => reject(),\n complete: () => resolve(),\n next: () => {},\n });\n });\n\n expect(apiSendCommandMock).toHaveBeenCalledWith(\n new TestCommand(commandParams),\n );\n });\n });\n\n describe(\"error cases\", () => {\n it(\"should error and output the error if the open app fails\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock(new UnknownDAError(\"Mocked error\"));\n\n const expectedStates: MyCommandSendCommandDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Error,\n error: new UnknownDAError(\"Mocked error\"),\n },\n ];\n\n testDeviceActionStates(\n new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n }),\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n\n it(\"should error and output an error if the send command fails\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n sendMyCommand.mockResolvedValue(\n CommandResultFactory({\n error: new UnknownDeviceExchangeError(\"Mocked error\"),\n }),\n );\n\n const deviceAction = new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandSendCommandDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Error,\n error: new UnknownDeviceExchangeError(\"Mocked error\"),\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n });\n\n describe(\"success cases\", () => {\n it(\"should succeed and output the command result if the send command succeeds\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n sendMyCommand.mockResolvedValue(\n CommandResultFactory({ data: mockedCommandResponse }),\n );\n\n const deviceAction = new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: false,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandSendCommandDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.ConfirmOpenApp,\n },\n },\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Completed,\n output: mockedCommandResponse,\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n\n it(\"should succeed while skipping OpenApp\", () =>\n new Promise<void>((resolve, reject) => {\n setupOpenAppDAMock();\n\n sendMyCommand.mockResolvedValue(\n CommandResultFactory({ data: mockedCommandResponse }),\n );\n\n const deviceAction = new SendCommandInAppDeviceAction({\n input: {\n command: new TestCommand(commandParams),\n appName: \"MyApp\",\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n skipOpenApp: true,\n },\n });\n\n vi.spyOn(deviceAction, \"extractDependencies\").mockImplementation(\n extractDependenciesMock,\n );\n\n const expectedStates: MyCommandSendCommandDAState[] = [\n {\n status: DeviceActionStatus.Pending,\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.VerifyAddress,\n },\n },\n {\n status: DeviceActionStatus.Completed,\n output: mockedCommandResponse,\n },\n ];\n\n testDeviceActionStates(\n deviceAction,\n expectedStates,\n makeDeviceActionInternalApiMock(),\n {\n onDone: resolve,\n onError: reject,\n },\n );\n }));\n });\n});\n\ntype MyCommandResponse = {\n aNumber: number;\n aString: string;\n};\n\ntype MyCommandParams = {\n paramString: string;\n paramNumber: number;\n};\n\nclass TestCommand implements Command<MyCommandResponse, MyCommandParams> {\n readonly name = \"testCommand\";\n\n params: MyCommandParams;\n constructor(params: MyCommandParams) {\n this.params = params;\n }\n getApdu(): Apdu {\n return new ApduBuilder({ cla: 0x00, ins: 0x01, p1: 0x02, p2: 0x03 })\n .add32BitUIntToData(this.params.paramNumber)\n .addAsciiStringToData(this.params.paramString)\n .build();\n }\n parseResponse() {\n return CommandResultFactory({ data: { aNumber: 1, aString: \"aString\" } });\n }\n}\n\ntype MyCommandSendCommandDAState = DeviceActionState<\n SendCommandInAppDAOutput<MyCommandResponse>,\n SendCommandInAppDAError<UnknownDAError>,\n SendCommandInAppDAIntermediateValue<\n UserInteractionRequired.None | UserInteractionRequired.VerifyAddress\n >\n>;\n"],
|
|
5
|
+
"mappings": "aACA,IAAAA,EAA4B,qBAE5BC,EAAsC,kBAGtCC,EAA4B,uCAC5BC,EAAqC,4CACrCC,EAAgD,6DAChDC,EAAuC,oEACvCC,EAGO,sDACPC,EAAwC,4DACxCC,EAA+B,wCAC/BC,EAAoC,yEAEpCC,EAA2C,qBAE3CC,EAA6C,0CAO7C,GAAG,KACD,gEACA,MAAOC,IAME,CACL,GALA,MAAMA,EAEJ,EAIF,oBAAqB,GAAG,GAAG,KAAO,CAChC,iBAAkB,GAAG,GAAG,CAC1B,EAAE,C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E,OAAQ,qBAAmB,UAC3B,OAAQL,CACV,CACF,KAEA,0BACEC,EACAI,KACA,mCAAgC,EAChC,CACE,OAAQF,EACR,QAASC,CACX,CACF,CACF,CAAC,CAAC,CACN,CAAC,CACH,CAAC,EAYD,MAAMF,CAAmE,CAC9D,KAAO,cAEhB,OACA,YAAYI,EAAyB,CACnC,KAAK,OAASA,CAChB,CACA,SAAgB,CACd,OAAO,IAAI,cAAY,CAAE,IAAK,EAAM,IAAK,EAAM,GAAI,EAAM,GAAI,CAAK,CAAC,EAChE,mBAAmB,KAAK,OAAO,WAAW,EAC1C,qBAAqB,KAAK,OAAO,WAAW,EAC5C,MAAM,CACX,CACA,eAAgB,CACd,SAAO,wBAAqB,CAAE,KAAM,CAAE,QAAS,EAAG,QAAS,SAAU,CAAE,CAAC,CAC1E,CACF",
|
|
6
6
|
"names": ["import_purify_ts", "import_xstate", "import_ApduBuilder", "import_CommandResult", "import_makeInternalApi", "import_testDeviceActionStates", "import_DeviceActionState", "import_UserInteractionRequired", "import_Errors", "import_OpenAppDeviceAction", "import_src", "import_SendCommandInAppDeviceAction", "importOriginal", "setupOpenAppDAMock", "error", "sendMyCommand", "extractDependenciesMock", "apiSendCommandMock", "commandParams", "mockedCommandResponse", "deviceAction", "TestCommand", "resolve", "reject", "expectedStates", "params"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var r=Object.defineProperty;var
|
|
1
|
+
"use strict";var r=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var a=Object.prototype.hasOwnProperty;var y=(o,e)=>{for(var t in e)r(o,t,{get:e[t],enumerable:!0})},v=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of l(e))!a.call(o,n)&&n!==t&&r(o,n,{get:()=>e[n],enumerable:!(i=p(e,n))||i.enumerable});return o};var D=o=>v(r({},"__esModule",{value:!0}),o);var m={};y(m,{ConnectedDevice:()=>I});module.exports=D(m);class I{id;sessionId;modelId;name;type;transport;constructor({transportConnectedDevice:{id:e,deviceModel:{id:t,productName:i},type:n,transport:d,name:s},sessionId:c}){this.id=e,this.sessionId=c,this.modelId=t,this.name=s??i,this.type=n,this.transport=d}}0&&(module.exports={ConnectedDevice});
|
|
2
2
|
//# sourceMappingURL=ConnectedDevice.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/api/transport/model/ConnectedDevice.ts"],
|
|
4
|
-
"sourcesContent": ["import { type DeviceId, type DeviceModelId } from \"@api/device/DeviceModel\";\nimport { type ConnectionType } from \"@api/discovery/ConnectionType\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { type DeviceSessionId, type TransportIdentifier } from \"@api/types\";\n\ntype ConnectedDeviceConstructorArgs = {\n readonly sessionId: DeviceSessionId;\n readonly transportConnectedDevice: TransportConnectedDevice;\n};\n\nexport class ConnectedDevice {\n public readonly id: DeviceId;\n public readonly sessionId: DeviceSessionId;\n public readonly modelId: DeviceModelId;\n public readonly name: string;\n public readonly type: ConnectionType;\n public readonly transport: TransportIdentifier;\n\n constructor({\n transportConnectedDevice: {\n id,\n deviceModel: { id: deviceModelId, productName
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAUO,MAAME,CAAgB,CACX,GACA,UACA,QACA,KACA,KACA,UAEhB,YAAY,CACV,yBAA0B,CACxB,GAAAE,EACA,YAAa,CAAE,GAAIC,EAAe,
|
|
6
|
-
"names": ["ConnectedDevice_exports", "__export", "ConnectedDevice", "__toCommonJS", "id", "deviceModelId", "
|
|
4
|
+
"sourcesContent": ["import { type DeviceId, type DeviceModelId } from \"@api/device/DeviceModel\";\nimport { type ConnectionType } from \"@api/discovery/ConnectionType\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { type DeviceSessionId, type TransportIdentifier } from \"@api/types\";\n\ntype ConnectedDeviceConstructorArgs = {\n readonly sessionId: DeviceSessionId;\n readonly transportConnectedDevice: TransportConnectedDevice;\n};\n\nexport class ConnectedDevice {\n public readonly id: DeviceId;\n public readonly sessionId: DeviceSessionId;\n public readonly modelId: DeviceModelId;\n public readonly name: string;\n public readonly type: ConnectionType;\n public readonly transport: TransportIdentifier;\n\n constructor({\n transportConnectedDevice: {\n id,\n deviceModel: { id: deviceModelId, productName },\n type,\n transport,\n name,\n },\n sessionId,\n }: ConnectedDeviceConstructorArgs) {\n this.id = id;\n this.sessionId = sessionId;\n this.modelId = deviceModelId;\n this.name = name ?? productName;\n this.type = type;\n this.transport = transport;\n }\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,qBAAAE,IAAA,eAAAC,EAAAH,GAUO,MAAME,CAAgB,CACX,GACA,UACA,QACA,KACA,KACA,UAEhB,YAAY,CACV,yBAA0B,CACxB,GAAAE,EACA,YAAa,CAAE,GAAIC,EAAe,YAAAC,CAAY,EAC9C,KAAAC,EACA,UAAAC,EACA,KAAAC,CACF,EACA,UAAAC,CACF,EAAmC,CACjC,KAAK,GAAKN,EACV,KAAK,UAAYM,EACjB,KAAK,QAAUL,EACf,KAAK,KAAOI,GAAQH,EACpB,KAAK,KAAOC,EACZ,KAAK,UAAYC,CACnB,CACF",
|
|
6
|
+
"names": ["ConnectedDevice_exports", "__export", "ConnectedDevice", "__toCommonJS", "id", "deviceModelId", "productName", "type", "transport", "name", "sessionId"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var p=Object.defineProperty;var
|
|
1
|
+
"use strict";var p=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var s=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var a=(t,e)=>{for(var r in e)p(t,r,{get:e[r],enumerable:!0})},l=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of s(e))!y.call(t,n)&&n!==r&&p(t,n,{get:()=>e[n],enumerable:!(o=c(e,n))||o.enumerable});return t};var u=t=>l(p({},"__esModule",{value:!0}),t);var T={};a(T,{TransportConnectedDevice:()=>m});module.exports=u(T);class m{id;deviceModel;sendApdu;type;transport;name;constructor({id:e,deviceModel:r,type:o,transport:n,sendApdu:i,name:d}){this.id=e,this.deviceModel=r,this.sendApdu=i,this.type=o,this.transport=n,this.name=d}}0&&(module.exports={TransportConnectedDevice});
|
|
2
2
|
//# sourceMappingURL=TransportConnectedDevice.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/api/transport/model/TransportConnectedDevice.ts"],
|
|
4
|
-
"sourcesContent": ["import { type DeviceId } from \"@api/device/DeviceModel\";\nimport { type TransportDeviceModel } from \"@api/device-model/model/DeviceModel\";\nimport { type ConnectionType } from \"@api/discovery/ConnectionType\";\nimport { type SendApduFnType } from \"@api/transport/model/DeviceConnection\";\nimport { type TransportIdentifier } from \"@api/transport/model/TransportIdentifier\";\n\n/**\n * The internal connected device.\n */\nexport type ConnectedDeviceConstructorArgs = {\n id: DeviceId;\n deviceModel: TransportDeviceModel;\n type: ConnectionType;\n transport: TransportIdentifier;\n sendApdu: SendApduFnType;\n};\n\nexport class TransportConnectedDevice {\n public readonly id: DeviceId;\n public readonly deviceModel: TransportDeviceModel;\n public readonly sendApdu: SendApduFnType;\n public readonly type: ConnectionType;\n public readonly transport: TransportIdentifier;\n\n constructor({\n id,\n deviceModel,\n type,\n transport,\n sendApdu,\n }: ConnectedDeviceConstructorArgs) {\n this.id = id;\n this.deviceModel = deviceModel;\n this.sendApdu = sendApdu;\n this.type = type;\n this.transport = transport;\n }\n}\n"],
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8BAAAE,IAAA,eAAAC,EAAAH,
|
|
6
|
-
"names": ["TransportConnectedDevice_exports", "__export", "TransportConnectedDevice", "__toCommonJS", "id", "deviceModel", "type", "transport", "sendApdu"]
|
|
4
|
+
"sourcesContent": ["import { type DeviceId } from \"@api/device/DeviceModel\";\nimport { type TransportDeviceModel } from \"@api/device-model/model/DeviceModel\";\nimport { type ConnectionType } from \"@api/discovery/ConnectionType\";\nimport { type SendApduFnType } from \"@api/transport/model/DeviceConnection\";\nimport { type TransportIdentifier } from \"@api/transport/model/TransportIdentifier\";\n\n/**\n * The internal connected device.\n */\nexport type ConnectedDeviceConstructorArgs = {\n id: DeviceId;\n deviceModel: TransportDeviceModel;\n type: ConnectionType;\n transport: TransportIdentifier;\n sendApdu: SendApduFnType;\n name?: string;\n};\n\nexport class TransportConnectedDevice {\n public readonly id: DeviceId;\n public readonly deviceModel: TransportDeviceModel;\n public readonly sendApdu: SendApduFnType;\n public readonly type: ConnectionType;\n public readonly transport: TransportIdentifier;\n public readonly name?: string;\n\n constructor({\n id,\n deviceModel,\n type,\n transport,\n sendApdu,\n name,\n }: ConnectedDeviceConstructorArgs) {\n this.id = id;\n this.deviceModel = deviceModel;\n this.sendApdu = sendApdu;\n this.type = type;\n this.transport = transport;\n this.name = name;\n }\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,8BAAAE,IAAA,eAAAC,EAAAH,GAkBO,MAAME,CAAyB,CACpB,GACA,YACA,SACA,KACA,UACA,KAEhB,YAAY,CACV,GAAAE,EACA,YAAAC,EACA,KAAAC,EACA,UAAAC,EACA,SAAAC,EACA,KAAAC,CACF,EAAmC,CACjC,KAAK,GAAKL,EACV,KAAK,YAAcC,EACnB,KAAK,SAAWG,EAChB,KAAK,KAAOF,EACZ,KAAK,UAAYC,EACjB,KAAK,KAAOE,CACd,CACF",
|
|
6
|
+
"names": ["TransportConnectedDevice_exports", "__export", "TransportConnectedDevice", "__toCommonJS", "id", "deviceModel", "type", "transport", "sendApdu", "name"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var p=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var y=(n,e)=>{for(var i in e)p(n,i,{get:e[i],enumerable:!0})},T=(n,e,i,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of R(e))!A.call(n,t)&&t!==i&&p(n,t,{get:()=>e[t],enumerable:!(s=C(e,t))||s.enumerable});return n};var O=n=>T(p({},"__esModule",{value:!0}),n);var x={};y(x,{DeviceSession:()=>I});module.exports=O(x);var h=require("rxjs"),S=require("uuid"),u=require("../../../api/command/utils/CommandUtils"),d=require("../../../api/device/DeviceStatus"),m=require("../../../api/device-session/DeviceSessionState"),a=require("../../../api/index"),l=require("../../device-session/data/DeviceSessionRefresherConst"),D=require("../../device-session/service/MutexService"),_=require("../../device-session/service/RefresherService"),g=require("./DevicePinger"),o=require("./DeviceSessionEventDispatcher"),f=require("./DeviceSessionRefresher"),E=require("./DeviceSessionStateHandler");class I{_id;_connectedDevice;_deviceState;_managerApiService;_secureChannelService;_logger;_refresherOptions;_pinger;_deviceSessionRefresher;_refresherService;_commandMutex=new D.MutexService;_sessionEventDispatcher=new o.DeviceSessionEventDispatcher;constructor({connectedDevice:e,id:i=(0,S.v4)()},s,t,r,c){this._id=i,this._connectedDevice=e,this._logger=s("device-session"),this._managerApiService=t,this._secureChannelService=r,this._refresherOptions={...l.DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,...c},this._deviceState=new h.BehaviorSubject({sessionStateType:m.DeviceSessionStateType.Connected,deviceStatus:d.DeviceStatus.CONNECTED,deviceModelId:this._connectedDevice.deviceModel.id}),this._pinger=new g.DevicePinger(s,e,this._sessionEventDispatcher,(v,b)=>this.sendCommand(v,b)),this._deviceSessionRefresher=new f.DeviceSessionRefresher(s,this._refresherOptions,this._sessionEventDispatcher,this._connectedDevice),new E.DeviceSessionStateHandler(s,this._sessionEventDispatcher,this._connectedDevice,this._deviceState,v=>this.setDeviceSessionState(v)),this._refresherService=new _.RefresherService(s,{start:()=>this._deviceSessionRefresher.restartRefresher(),stop:()=>this._deviceSessionRefresher.stopRefresher()})}async initialiseSession(){try{await this._pinger.ping()}catch(e){throw this._logger.error("Error while initialising session",{data:{error:e}}),e}finally{this._refresherOptions.isRefresherDisabled||this._deviceSessionRefresher.startRefresher()}}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)}async sendApdu(e,i={isPolling:!1,triggersDisconnection:!1,abortTimeout:void 0}){const s=await this._commandMutex.lock();try{this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_BUSY}),this._logger.debug(`[exchange] => ${(0,a.bufferToHexaString)(e,!1)}`);const t=await this._connectedDevice.sendApdu(e,i.triggersDisconnection,i.abortTimeout);return t.ifRight(r=>{this._logger.debug(`[exchange] <= ${(0,a.bufferToHexaString)(r.data,!1)}${(0,a.bufferToHexaString)(r.statusCode,!1)}`),u.CommandUtils.isLockedDeviceResponse(r)?this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_LOCKED}):this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_CONNECTED})}).ifLeft(()=>{this._sessionEventDispatcher.dispatch({eventName:o.SessionEvents.DEVICE_STATE_UPDATE_CONNECTED})}),t}finally{s()}}async sendCommand(e,i){this._logger.debug(`[sendCommand] ${e.name}`);const s=e.getApdu();return(await this.sendApdu(s.getRawApdu(),{isPolling:!1,triggersDisconnection:e.triggersDisconnection??!1,abortTimeout:i})).caseOf({Left:r=>{throw this._logger.error("[sendCommand] error",{data:{err:r}}),r},Right:r=>{const c=e.parseResponse(r,this._connectedDevice.deviceModel.id);return this._logger.debug("[sendCommand] result",{data:{result:c}}),c}})}executeDeviceAction(e){const{observable:i,cancel:s}=e._execute({sendApdu:async t=>this.sendApdu(t),sendCommand:async(t,r)=>this.sendCommand(t,r),getDeviceModel:()=>this._connectedDevice.deviceModel,getDeviceSessionState:()=>this._deviceState.getValue(),getDeviceSessionStateObservable:()=>this.state,setDeviceSessionState:t=>(this.setDeviceSessionState(t),this._deviceState.getValue()),disableRefresher:t=>this._refresherService.disableRefresher(t),getManagerApiService:()=>this._managerApiService,getSecureChannelService:()=>this._secureChannelService});return{observable:i,cancel:s}}close(){this._updateDeviceStatus(d.DeviceStatus.NOT_CONNECTED),this._deviceState.complete(),this._deviceSessionRefresher.stopRefresher()}disableRefresher(e){return this._refresherService.disableRefresher(e)}_updateDeviceStatus(e){const i=this._deviceState.getValue();this._deviceState.next({...i,deviceStatus:e})}}0&&(module.exports={DeviceSession});
|
|
2
2
|
//# sourceMappingURL=DeviceSession.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/model/DeviceSession.ts"],
|
|
4
|
-
"sourcesContent": ["import { type Either } from \"purify-ts\";\nimport { BehaviorSubject, type Observable } from \"rxjs\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { type Command } from \"@api/command/Command\";\nimport { type CommandResult } from \"@api/command/model/CommandResult\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nimport { type DeviceSessionId } from \"@api/device-session/types\";\nimport { type DmkError } from \"@api/Error\";\nimport { bufferToHexaString } from \"@api/index\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { MutexService } from \"@internal/device-session/service/MutexService\";\nimport { RefresherService } from \"@internal/device-session/service/RefresherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DevicePinger } from \"./DevicePinger\";\nimport {\n DeviceSessionEventDispatcher,\n SessionEvents,\n} from \"./DeviceSessionEventDispatcher\";\nimport { DeviceSessionRefresher } from \"./DeviceSessionRefresher\";\nimport { DeviceSessionStateHandler } from \"./DeviceSessionStateHandler\";\n\nexport type SessionConstructorArgs = {\n connectedDevice: TransportConnectedDevice;\n id?: DeviceSessionId;\n};\n\nexport type DeviceSessionRefresherOptions = {\n isRefresherDisabled: boolean;\n pollingInterval?: number;\n};\n\ntype SendApduOptions = {\n isPolling?: boolean;\n triggersDisconnection?: boolean;\n abortTimeout?: number;\n};\n\n/**\n * Represents a session with a device.\n */\nexport class DeviceSession {\n private readonly _id: DeviceSessionId;\n private readonly _connectedDevice: TransportConnectedDevice;\n private readonly _deviceState: BehaviorSubject<DeviceSessionState>;\n private readonly _managerApiService: ManagerApiService;\n private readonly _secureChannelService: SecureChannelService;\n private readonly _logger: LoggerPublisherService;\n private readonly _refresherOptions: DeviceSessionRefresherOptions;\n private _pinger: DevicePinger;\n private _deviceSessionRefresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private _commandMutex = new MutexService();\n private _sessionEventDispatcher = new DeviceSessionEventDispatcher();\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n deviceSessionRefresherOptions: DeviceSessionRefresherOptions | undefined,\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._logger = loggerModuleFactory(\"device-session\");\n this._managerApiService = managerApiService;\n this._secureChannelService = secureChannelService;\n this._refresherOptions = {\n ...DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n ...deviceSessionRefresherOptions,\n };\n this._deviceState = new BehaviorSubject<DeviceSessionState>({\n sessionStateType: DeviceSessionStateType.Connected,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n });\n\n this._pinger = new DevicePinger(\n loggerModuleFactory,\n connectedDevice,\n this._sessionEventDispatcher,\n (command, abortTimeout) => this.sendCommand(command, abortTimeout),\n );\n this._deviceSessionRefresher = new DeviceSessionRefresher(\n loggerModuleFactory,\n this._refresherOptions,\n this._sessionEventDispatcher,\n this._connectedDevice,\n );\n new DeviceSessionStateHandler(\n loggerModuleFactory,\n this._sessionEventDispatcher,\n this._connectedDevice,\n this._deviceState,\n (state) => this.setDeviceSessionState(state),\n );\n\n this._refresherService = new RefresherService(loggerModuleFactory, {\n start: () => this._deviceSessionRefresher.restartRefresher(),\n stop: () => this._deviceSessionRefresher.stopRefresher(),\n });\n }\n\n public async initialiseSession(): Promise<void> {\n try {\n await this._pinger.ping();\n } catch (error) {\n this._logger.error(\"Error while initialising session\", {\n data: { error },\n });\n throw error;\n } finally {\n if (!this._refresherOptions.isRefresherDisabled) {\n this._deviceSessionRefresher.startRefresher();\n }\n }\n }\n\n public get id(): DeviceSessionId {\n return this._id;\n }\n\n public get connectedDevice(): TransportConnectedDevice {\n return this._connectedDevice;\n }\n\n public get state(): Observable<DeviceSessionState> {\n return this._deviceState.asObservable();\n }\n\n public getDeviceSessionState(): DeviceSessionState {\n return this._deviceState.getValue();\n }\n\n public setDeviceSessionState(state: DeviceSessionState): void {\n this._deviceState.next(state);\n }\n\n public async sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n const release = await this._commandMutex.lock();\n\n try {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_BUSY,\n });\n\n this._logger.debug(`[exchange] => ${bufferToHexaString(rawApdu, false)}`);\n const result = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n options.abortTimeout,\n );\n\n result\n .ifRight((response: ApduResponse) => {\n this._logger.debug(\n `[exchange] <= ${bufferToHexaString(response.data, false)}${bufferToHexaString(response.statusCode, false)}`,\n );\n if (CommandUtils.isLockedDeviceResponse(response)) {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_LOCKED,\n });\n } else {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n }\n })\n .ifLeft(() => {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n });\n return result;\n } finally {\n release();\n }\n }\n\n public async sendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n const apdu = command.getApdu();\n\n const response = await this.sendApdu(apdu.getRawApdu(), {\n isPolling: false,\n triggersDisconnection: command.triggersDisconnection ?? false,\n abortTimeout,\n });\n\n return response.caseOf({\n Left: (err) => {\n throw err;\n },\n Right: (r)
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAiD,gBACjDC,EAA6B,gBAI7BC,EAA6B,2CAC7BC,EAA6B,oCAO7BC,EAGO,kDAGPC,EAAmC,sBAGnCC,EAAyD,qEACzDC,EAA6B,yDAC7BC,EAAiC,6DAIjCC,EAA6B,0BAC7BC,EAGO,0CACPC,EAAuC,oCACvCC,EAA0C,uCAqBnC,MAAMd,CAAc,CACR,IACA,iBACA,aACA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,aAAa,aAAa,CACxC,CAEO,uBAA4C,CACjD,OAAO,KAAK,aAAa,SAAS,CACpC,CAEO,sBAAsBD,EAAiC,CAC5D,KAAK,aAAa,KAAKA,CAAK,CAC9B,CAEA,MAAa,SACXE,EACAC,EAA2B,CACzB,UAAW,GACX,sBAAuB,GACvB,aAAc,MAChB,EACyC,CACzC,MAAMC,EAAU,MAAM,KAAK,cAAc,KAAK,EAE9C,GAAI,CACF,KAAK,wBAAwB,SAAS,CACpC,UAAW,gBAAc,wBAC3B,CAAC,EAED,KAAK,QAAQ,MAAM,oBAAiB,sBAAmBF,EAAS,EAAK,CAAC,EAAE,EACxE,MAAMG,EAAS,MAAM,KAAK,iBAAiB,SACzCH,EACAC,EAAQ,sBACRA,EAAQ,YACV,EAEA,OAAAE,EACG,QAASC,GAA2B,CACnC,KAAK,QAAQ,MACX,oBAAiB,sBAAmBA,EAAS,KAAM,EAAK,CAAC,MAAG,sBAAmBA,EAAS,WAAY,EAAK,CAAC,EAC5G,EACI,eAAa,uBAAuBA,CAAQ,EAC9C,KAAK,wBAAwB,SAAS,CACpC,UAAW,gBAAc,0BAC3B,CAAC,EAED,KAAK,wBAAwB,SAAS,CACpC,UAAW,gBAAc,6BAC3B,CAAC,CAEL,CAAC,EACA,OAAO,IAAM,CACZ,KAAK,wBAAwB,SAAS,CACpC,UAAW,gBAAc,6BAC3B,CAAC,CACH,CAAC,EACID,CACT,QAAE,CACAD,EAAQ,CACV,CACF,CAEA,MAAa,YACXN,EACAC,EACoD,CACpD,
|
|
4
|
+
"sourcesContent": ["import { type Either } from \"purify-ts\";\nimport { BehaviorSubject, type Observable } from \"rxjs\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport { type Command } from \"@api/command/Command\";\nimport { type CommandResult } from \"@api/command/model/CommandResult\";\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n} from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\nimport { type DeviceSessionId } from \"@api/device-session/types\";\nimport { type DmkError } from \"@api/Error\";\nimport { bufferToHexaString } from \"@api/index\";\nimport { type LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { type TransportConnectedDevice } from \"@api/transport/model/TransportConnectedDevice\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { MutexService } from \"@internal/device-session/service/MutexService\";\nimport { RefresherService } from \"@internal/device-session/service/RefresherService\";\nimport { type ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DevicePinger } from \"./DevicePinger\";\nimport {\n DeviceSessionEventDispatcher,\n SessionEvents,\n} from \"./DeviceSessionEventDispatcher\";\nimport { DeviceSessionRefresher } from \"./DeviceSessionRefresher\";\nimport { DeviceSessionStateHandler } from \"./DeviceSessionStateHandler\";\n\nexport type SessionConstructorArgs = {\n connectedDevice: TransportConnectedDevice;\n id?: DeviceSessionId;\n};\n\nexport type DeviceSessionRefresherOptions = {\n isRefresherDisabled: boolean;\n pollingInterval?: number;\n};\n\ntype SendApduOptions = {\n isPolling?: boolean;\n triggersDisconnection?: boolean;\n abortTimeout?: number;\n};\n\n/**\n * Represents a session with a device.\n */\nexport class DeviceSession {\n private readonly _id: DeviceSessionId;\n private readonly _connectedDevice: TransportConnectedDevice;\n private readonly _deviceState: BehaviorSubject<DeviceSessionState>;\n private readonly _managerApiService: ManagerApiService;\n private readonly _secureChannelService: SecureChannelService;\n private readonly _logger: LoggerPublisherService;\n private readonly _refresherOptions: DeviceSessionRefresherOptions;\n private _pinger: DevicePinger;\n private _deviceSessionRefresher: DeviceSessionRefresher;\n private readonly _refresherService: RefresherService;\n private _commandMutex = new MutexService();\n private _sessionEventDispatcher = new DeviceSessionEventDispatcher();\n\n constructor(\n { connectedDevice, id = uuidv4() }: SessionConstructorArgs,\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n managerApiService: ManagerApiService,\n secureChannelService: SecureChannelService,\n deviceSessionRefresherOptions: DeviceSessionRefresherOptions | undefined,\n ) {\n this._id = id;\n this._connectedDevice = connectedDevice;\n this._logger = loggerModuleFactory(\"device-session\");\n this._managerApiService = managerApiService;\n this._secureChannelService = secureChannelService;\n this._refresherOptions = {\n ...DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n ...deviceSessionRefresherOptions,\n };\n this._deviceState = new BehaviorSubject<DeviceSessionState>({\n sessionStateType: DeviceSessionStateType.Connected,\n deviceStatus: DeviceStatus.CONNECTED,\n deviceModelId: this._connectedDevice.deviceModel.id,\n });\n\n this._pinger = new DevicePinger(\n loggerModuleFactory,\n connectedDevice,\n this._sessionEventDispatcher,\n (command, abortTimeout) => this.sendCommand(command, abortTimeout),\n );\n this._deviceSessionRefresher = new DeviceSessionRefresher(\n loggerModuleFactory,\n this._refresherOptions,\n this._sessionEventDispatcher,\n this._connectedDevice,\n );\n new DeviceSessionStateHandler(\n loggerModuleFactory,\n this._sessionEventDispatcher,\n this._connectedDevice,\n this._deviceState,\n (state) => this.setDeviceSessionState(state),\n );\n\n this._refresherService = new RefresherService(loggerModuleFactory, {\n start: () => this._deviceSessionRefresher.restartRefresher(),\n stop: () => this._deviceSessionRefresher.stopRefresher(),\n });\n }\n\n public async initialiseSession(): Promise<void> {\n try {\n await this._pinger.ping();\n } catch (error) {\n this._logger.error(\"Error while initialising session\", {\n data: { error },\n });\n throw error;\n } finally {\n if (!this._refresherOptions.isRefresherDisabled) {\n this._deviceSessionRefresher.startRefresher();\n }\n }\n }\n\n public get id(): DeviceSessionId {\n return this._id;\n }\n\n public get connectedDevice(): TransportConnectedDevice {\n return this._connectedDevice;\n }\n\n public get state(): Observable<DeviceSessionState> {\n return this._deviceState.asObservable();\n }\n\n public getDeviceSessionState(): DeviceSessionState {\n return this._deviceState.getValue();\n }\n\n public setDeviceSessionState(state: DeviceSessionState): void {\n this._deviceState.next(state);\n }\n\n public async sendApdu(\n rawApdu: Uint8Array,\n options: SendApduOptions = {\n isPolling: false,\n triggersDisconnection: false,\n abortTimeout: undefined,\n },\n ): Promise<Either<DmkError, ApduResponse>> {\n const release = await this._commandMutex.lock();\n\n try {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_BUSY,\n });\n\n this._logger.debug(`[exchange] => ${bufferToHexaString(rawApdu, false)}`);\n const result = await this._connectedDevice.sendApdu(\n rawApdu,\n options.triggersDisconnection,\n options.abortTimeout,\n );\n\n result\n .ifRight((response: ApduResponse) => {\n this._logger.debug(\n `[exchange] <= ${bufferToHexaString(response.data, false)}${bufferToHexaString(response.statusCode, false)}`,\n );\n if (CommandUtils.isLockedDeviceResponse(response)) {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_LOCKED,\n });\n } else {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n }\n })\n .ifLeft(() => {\n this._sessionEventDispatcher.dispatch({\n eventName: SessionEvents.DEVICE_STATE_UPDATE_CONNECTED,\n });\n });\n return result;\n } finally {\n release();\n }\n }\n\n public async sendCommand<Response, Args, ErrorStatusCodes>(\n command: Command<Response, Args, ErrorStatusCodes>,\n abortTimeout?: number,\n ): Promise<CommandResult<Response, ErrorStatusCodes>> {\n this._logger.debug(`[sendCommand] ${command.name}`);\n const apdu = command.getApdu();\n\n const response = await this.sendApdu(apdu.getRawApdu(), {\n isPolling: false,\n triggersDisconnection: command.triggersDisconnection ?? false,\n abortTimeout,\n });\n\n return response.caseOf({\n Left: (err) => {\n this._logger.error(\"[sendCommand] error\", { data: { err } });\n throw err;\n },\n Right: (r) => {\n const result = command.parseResponse(\n r,\n this._connectedDevice.deviceModel.id,\n );\n this._logger.debug(\"[sendCommand] result\", { data: { result } });\n return result;\n },\n });\n }\n\n public executeDeviceAction<\n Output,\n Input,\n E extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n >(\n deviceAction: DeviceAction<Output, Input, E, IntermediateValue>,\n ): ExecuteDeviceActionReturnType<Output, E, IntermediateValue> {\n const { observable, cancel } = deviceAction._execute({\n sendApdu: async (apdu: Uint8Array) => this.sendApdu(apdu),\n sendCommand: async <Response, ErrorStatusCodes, Args>(\n command: Command<Response, ErrorStatusCodes, Args>,\n abortTimeout?: number,\n ) => this.sendCommand(command, abortTimeout),\n getDeviceModel: () => this._connectedDevice.deviceModel,\n getDeviceSessionState: () => this._deviceState.getValue(),\n getDeviceSessionStateObservable: () => this.state,\n setDeviceSessionState: (state: DeviceSessionState) => {\n this.setDeviceSessionState(state);\n return this._deviceState.getValue();\n },\n disableRefresher: (blockerId: string) =>\n this._refresherService.disableRefresher(blockerId),\n getManagerApiService: () => this._managerApiService,\n getSecureChannelService: () => this._secureChannelService,\n });\n return { observable, cancel };\n }\n\n public close(): void {\n this._updateDeviceStatus(DeviceStatus.NOT_CONNECTED);\n this._deviceState.complete();\n this._deviceSessionRefresher.stopRefresher();\n }\n\n public disableRefresher(id: string): () => void {\n return this._refresherService.disableRefresher(id);\n }\n\n private _updateDeviceStatus(deviceStatus: DeviceStatus): void {\n const state = this._deviceState.getValue();\n this._deviceState.next({ ...state, deviceStatus });\n }\n}\n"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAiD,gBACjDC,EAA6B,gBAI7BC,EAA6B,2CAC7BC,EAA6B,oCAO7BC,EAGO,kDAGPC,EAAmC,sBAGnCC,EAAyD,qEACzDC,EAA6B,yDAC7BC,EAAiC,6DAIjCC,EAA6B,0BAC7BC,EAGO,0CACPC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GAAQ,CACb,WAAK,QAAQ,MAAM,sBAAuB,CAAE,KAAM,CAAE,IAAAA,CAAI,CAAE,CAAC,EACrDA,CACR,EACA,MAAQ,GAAM,CACZ,MAAMH,EAASP,EAAQ,cACrB,EACA,KAAK,iBAAiB,YAAY,EACpC,EACA,YAAK,QAAQ,MAAM,uBAAwB,CAAE,KAAM,CAAE,OAAAO,CAAO,CAAE,CAAC,EACxDA,CACT,CACF,CAAC,CACH,CAEO,oBAMLI,EAC6D,CAC7D,KAAM,CAAE,WAAAC,EAAY,OAAAC,CAAO,EAAIF,EAAa,SAAS,CACnD,SAAU,MAAOF,GAAqB,KAAK,SAASA,CAAI,EACxD,YAAa,MACXT,EACAC,IACG,KAAK,YAAYD,EAASC,CAAY,EAC3C,eAAgB,IAAM,KAAK,iBAAiB,YAC5C,sBAAuB,IAAM,KAAK,aAAa,SAAS,EACxD,gCAAiC,IAAM,KAAK,MAC5C,sBAAwBC,IACtB,KAAK,sBAAsBA,CAAK,EACzB,KAAK,aAAa,SAAS,GAEpC,iBAAmBY,GACjB,KAAK,kBAAkB,iBAAiBA,CAAS,EACnD,qBAAsB,IAAM,KAAK,mBACjC,wBAAyB,IAAM,KAAK,qBACtC,CAAC,EACD,MAAO,CAAE,WAAAF,EAAY,OAAAC,CAAO,CAC9B,CAEO,OAAc,CACnB,KAAK,oBAAoB,eAAa,aAAa,EACnD,KAAK,aAAa,SAAS,EAC3B,KAAK,wBAAwB,cAAc,CAC7C,CAEO,iBAAiBnB,EAAwB,CAC9C,OAAO,KAAK,kBAAkB,iBAAiBA,CAAE,CACnD,CAEQ,oBAAoBqB,EAAkC,CAC5D,MAAMb,EAAQ,KAAK,aAAa,SAAS,EACzC,KAAK,aAAa,KAAK,CAAE,GAAGA,EAAO,aAAAa,CAAa,CAAC,CACnD,CACF",
|
|
6
6
|
"names": ["DeviceSession_exports", "__export", "DeviceSession", "__toCommonJS", "import_rxjs", "import_uuid", "import_CommandUtils", "import_DeviceStatus", "import_DeviceSessionState", "import_api", "import_DeviceSessionRefresherConst", "import_MutexService", "import_RefresherService", "import_DevicePinger", "import_DeviceSessionEventDispatcher", "import_DeviceSessionRefresher", "import_DeviceSessionStateHandler", "connectedDevice", "id", "uuidv4", "loggerModuleFactory", "managerApiService", "secureChannelService", "deviceSessionRefresherOptions", "command", "abortTimeout", "state", "error", "rawApdu", "options", "release", "result", "response", "apdu", "err", "deviceAction", "observable", "cancel", "blockerId", "deviceStatus"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var n=Object.defineProperty;var
|
|
1
|
+
"use strict";var n=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var b=Object.prototype.hasOwnProperty;var f=(o,e)=>{for(var s in e)n(o,s,{get:e[s],enumerable:!0})},_=(o,e,s,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of D(e))!b.call(o,r)&&r!==s&&n(o,r,{get:()=>e[r],enumerable:!(i=S(e,r))||i.enumerable});return o};var p=o=>_(n({},"__esModule",{value:!0}),o),a=(o,e,s,i)=>{for(var r=i>1?void 0:i?S(e,s):e,v=o.length-1,h;v>=0;v--)(h=o[v])&&(r=(i?h(e,s,r):h(r))||r);return i&&r&&n(e,s,r),r},l=(o,e)=>(s,i)=>e(s,i,o);var y={};f(y,{DefaultDeviceSessionService:()=>t});module.exports=p(y);var c=require("inversify"),d=require("purify-ts"),u=require("rxjs"),g=require("../../device-session/model/Errors"),m=require("../../logger-publisher/di/loggerTypes");let t=class{_sessions;_sessionsSubject;_logger;constructor(e){this._sessions=[],this._sessionsSubject=new u.ReplaySubject,this._logger=e("DeviceSessionService")}get sessionsObs(){return this._sessionsSubject.asObservable()}addDeviceSession(e){return this._sessions.find(i=>i.id===e.id)?(this._logger.warn("DeviceSession already exists",{data:{deviceSession:e}}),this):(this._sessions.push(e),this._sessionsSubject.next(e),this._logger.info("DeviceSession added",{data:{sessionId:e.id}}),this)}removeDeviceSession(e){const s=this._sessions.find(i=>i.id===e);return s?(s.close(),this._sessions=this._sessions.filter(i=>i.id!==e),this._logger.info("DeviceSession removed",{data:{sessionId:e}}),this):(this._logger.warn("DeviceSession not found",{data:{sessionId:e}}),this)}getDeviceSessionById(e){return d.Maybe.fromNullable(this._sessions.find(s=>s.id===e)).toEither(new g.DeviceSessionNotFound)}getDeviceSessionsByDeviceId(e){return d.Maybe.fromPredicate(({length:s})=>s>0,this._sessions.filter(s=>s.connectedDevice.id===e)).toEither(new g.DeviceSessionNotFound)}getDeviceSessions(){return this._sessions}};t=a([(0,c.injectable)(),l(0,(0,c.inject)(m.loggerTypes.LoggerPublisherServiceFactory))],t);0&&(module.exports={DefaultDeviceSessionService});
|
|
2
2
|
//# sourceMappingURL=DefaultDeviceSessionService.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/service/DefaultDeviceSessionService.ts"],
|
|
4
|
-
"sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Maybe } from \"purify-ts\";\nimport { Observable, ReplaySubject } from \"rxjs\";\n\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { DeviceSession } from \"@internal/device-session/model/DeviceSession\";\nimport { DeviceSessionNotFound } from \"@internal/device-session/model/Errors\";\nimport { DeviceSessionService } from \"@internal/device-session/service/DeviceSessionService\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n@injectable()\nexport class DefaultDeviceSessionService implements DeviceSessionService {\n private _sessions: DeviceSession[];\n private readonly
|
|
5
|
-
"mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBACnCC,
|
|
6
|
-
"names": ["DefaultDeviceSessionService_exports", "__export", "DefaultDeviceSessionService", "__toCommonJS", "import_inversify", "import_purify_ts", "import_rxjs", "import_Errors", "import_loggerTypes", "DefaultDeviceSessionService", "loggerModuleFactory", "deviceSession", "sessionId", "found", "deviceId", "__decorateClass", "__decorateParam"]
|
|
4
|
+
"sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Either, Maybe } from \"purify-ts\";\nimport { Observable, ReplaySubject } from \"rxjs\";\n\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { DeviceId } from \"@api/types\";\nimport { DeviceSession } from \"@internal/device-session/model/DeviceSession\";\nimport { DeviceSessionNotFound } from \"@internal/device-session/model/Errors\";\nimport { DeviceSessionService } from \"@internal/device-session/service/DeviceSessionService\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n@injectable()\nexport class DefaultDeviceSessionService implements DeviceSessionService {\n private _sessions: DeviceSession[];\n private readonly _sessionsSubject: ReplaySubject<DeviceSession>;\n private readonly _logger: LoggerPublisherService;\n\n constructor(\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._sessions = [];\n this._sessionsSubject = new ReplaySubject();\n this._logger = loggerModuleFactory(\"DeviceSessionService\");\n }\n\n public get sessionsObs(): Observable<DeviceSession> {\n return this._sessionsSubject.asObservable();\n }\n\n addDeviceSession(deviceSession: DeviceSession): DeviceSessionService {\n const found = this._sessions.find((s) => s.id === deviceSession.id);\n if (found) {\n this._logger.warn(\"DeviceSession already exists\", {\n data: { deviceSession },\n });\n return this;\n }\n this._sessions.push(deviceSession);\n this._sessionsSubject.next(deviceSession);\n this._logger.info(\"DeviceSession added\", {\n data: { sessionId: deviceSession.id },\n });\n return this;\n }\n\n removeDeviceSession(sessionId: string): DeviceSessionService {\n const found = this._sessions.find((s) => s.id === sessionId);\n if (found) {\n found.close();\n this._sessions = this._sessions.filter((s) => s.id !== sessionId);\n this._logger.info(\"DeviceSession removed\", { data: { sessionId } });\n return this;\n }\n this._logger.warn(\"DeviceSession not found\", { data: { sessionId } });\n return this;\n }\n\n getDeviceSessionById(\n sessionId: string,\n ): Either<DeviceSessionNotFound, DeviceSession> {\n return Maybe.fromNullable(\n this._sessions.find((s) => s.id === sessionId),\n ).toEither(new DeviceSessionNotFound());\n }\n\n getDeviceSessionsByDeviceId(\n deviceId: DeviceId,\n ): Either<DeviceSessionNotFound, DeviceSession[]> {\n return Maybe.fromPredicate(\n ({ length }) => length > 0,\n this._sessions.filter((s) => s.connectedDevice.id === deviceId),\n ).toEither(new DeviceSessionNotFound());\n }\n\n getDeviceSessions(): DeviceSession[] {\n return this._sessions;\n }\n}\n"],
|
|
5
|
+
"mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBACnCC,EAA8B,qBAC9BC,EAA0C,gBAK1CC,EAAsC,iDAEtCC,EAA4B,qDAGrB,IAAMC,EAAN,KAAkE,CAC/D,UACS,iBACA,QAEjB,YAEEC,EACA,CACA,KAAK,UAAY,CAAC,EAClB,KAAK,iBAAmB,IAAI,gBAC5B,KAAK,QAAUA,EAAoB,sBAAsB,CAC3D,CAEA,IAAW,aAAyC,CAClD,OAAO,KAAK,iBAAiB,aAAa,CAC5C,CAEA,iBAAiBC,EAAoD,CAEnE,OADc,KAAK,UAAU,KAAMC,GAAMA,EAAE,KAAOD,EAAc,EAAE,GAEhE,KAAK,QAAQ,KAAK,+BAAgC,CAChD,KAAM,CAAE,cAAAA,CAAc,CACxB,CAAC,EACM,OAET,KAAK,UAAU,KAAKA,CAAa,EACjC,KAAK,iBAAiB,KAAKA,CAAa,EACxC,KAAK,QAAQ,KAAK,sBAAuB,CACvC,KAAM,CAAE,UAAWA,EAAc,EAAG,CACtC,CAAC,EACM,KACT,CAEA,oBAAoBE,EAAyC,CAC3D,MAAMC,EAAQ,KAAK,UAAU,KAAMF,GAAMA,EAAE,KAAOC,CAAS,EAC3D,OAAIC,GACFA,EAAM,MAAM,EACZ,KAAK,UAAY,KAAK,UAAU,OAAQF,GAAMA,EAAE,KAAOC,CAAS,EAChE,KAAK,QAAQ,KAAK,wBAAyB,CAAE,KAAM,CAAE,UAAAA,CAAU,CAAE,CAAC,EAC3D,OAET,KAAK,QAAQ,KAAK,0BAA2B,CAAE,KAAM,CAAE,UAAAA,CAAU,CAAE,CAAC,EAC7D,KACT,CAEA,qBACEA,EAC8C,CAC9C,OAAO,QAAM,aACX,KAAK,UAAU,KAAM,GAAM,EAAE,KAAOA,CAAS,CAC/C,EAAE,SAAS,IAAI,uBAAuB,CACxC,CAEA,4BACEE,EACgD,CAChD,OAAO,QAAM,cACX,CAAC,CAAE,OAAAC,CAAO,IAAMA,EAAS,EACzB,KAAK,UAAU,OAAQ,GAAM,EAAE,gBAAgB,KAAOD,CAAQ,CAChE,EAAE,SAAS,IAAI,uBAAuB,CACxC,CAEA,mBAAqC,CACnC,OAAO,KAAK,SACd,CACF,EAlEaN,EAANQ,EAAA,IADN,cAAW,EAOPC,EAAA,eAAO,cAAY,6BAA6B,IANxCT",
|
|
6
|
+
"names": ["DefaultDeviceSessionService_exports", "__export", "DefaultDeviceSessionService", "__toCommonJS", "import_inversify", "import_purify_ts", "import_rxjs", "import_Errors", "import_loggerTypes", "DefaultDeviceSessionService", "loggerModuleFactory", "deviceSession", "s", "sessionId", "found", "deviceId", "length", "__decorateClass", "__decorateParam"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var s=require("purify-ts"),f=require("rxjs"),u=require("../../../api/transport/model/TransportConnectedDevice.stub"),r=require("../../device-session/data/DeviceSessionRefresherConst"),a=require("../../device-session/model/DeviceSession.stub"),p=require("../../device-session/model/Errors"),h=require("../../logger-publisher/service/DefaultLoggerPublisherService"),b=require("../../manager-api/data/AxiosManagerApiDataSource"),x=require("../../manager-api/service/DefaultManagerApiService"),E=require("../../secure-channel/data/DefaultSecureChannelDataSource"),y=require("../../secure-channel/service/DefaultSecureChannelService"),I=require("./DefaultDeviceSessionService");vi.mock("@internal/logger-publisher/service/DefaultLoggerPublisherService");vi.mock("@internal/manager-api/data/AxiosManagerApiDataSource");let e,o,i,d,S,m,c,g,n;describe("DefaultDeviceSessionService",()=>{o=new h.DefaultLoggerPublisherService([],"deviceSession"),m=new b.AxiosManagerApiDataSource({}),c=new x.DefaultManagerApiService(m),g=new E.DefaultSecureChannelDataSource({}),n=new y.DefaultSecureChannelService(g),beforeEach(()=>{vi.restoreAllMocks(),e=new I.DefaultDeviceSessionService(()=>o),i=(0,a.deviceSessionStubBuilder)({},()=>o,c,n,r.DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS)}),afterEach(()=>{i.close()}),it("should have an empty DeviceSession list",()=>{expect(e.getDeviceSessions()).toEqual([])}),describe("DeviceSessionService addDeviceSession",()=>{it("should add a DeviceSession if it does not already exist",()=>{e.addDeviceSession(i),expect(e.getDeviceSessions()).toEqual([i])}),it("should not add a DeviceSession if it already exists",()=>{e.addDeviceSession(i),e.addDeviceSession(i),expect(e.getDeviceSessions()).toEqual([i])})}),describe("DeviceSessionService removeDeviceSession",()=>{it("should remove the DeviceSession of given ID",()=>{e.addDeviceSession(i),e.removeDeviceSession(i.id),expect(e.getDeviceSessions()).toEqual([])}),it("should not remove the DeviceSession of given ID if it does not exist",()=>{e.addDeviceSession(i),e.removeDeviceSession("non-existent-id"),expect(e.getDeviceSessions()).toEqual([i])})}),describe("DeviceSessionService getDeviceSessionById",()=>{it("should get the DeviceSession of given ID if it exists",()=>{e.addDeviceSession(i),expect(e.getDeviceSessionById(i.id)).toEqual(s.Either.of(i))}),it("should not get the DeviceSession if it does not exist",()=>{e.addDeviceSession(i),expect(e.getDeviceSessionById("non-existent-id")).toEqual((0,s.Left)(new p.DeviceSessionNotFound))})}),describe("DeviceSessionService getDeviceSessionsByDeviceId",()=>{it("should not get device sessions by deviceId if none exist",()=>{e.addDeviceSession(i),expect(e.getDeviceSessionsByDeviceId("non-existent-device-id")).toEqual((0,s.Left)(new p.DeviceSessionNotFound))}),it("should get a single device session by deviceId",()=>{e.addDeviceSession(i),expect(e.getDeviceSessionsByDeviceId(i.connectedDevice.id)).toEqual(s.Either.of([i]))}),it("should get device sessions by deviceId",()=>{e.addDeviceSession(i),d=(0,a.deviceSessionStubBuilder)({connectedDevice:(0,u.connectedDeviceStubBuilder)({id:"device-1"}),id:"session-1"},()=>o,c,n,r.DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS),S=(0,a.deviceSessionStubBuilder)({connectedDevice:(0,u.connectedDeviceStubBuilder)({id:"device-1"}),id:"session-2"},()=>o,c,n,r.DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS),e.addDeviceSession(d),e.addDeviceSession(S),expect(e.getDeviceSessionsByDeviceId("device-1")).toEqual(s.Either.of([d,S])),d.close(),S.close()})}),it("should get all sessions",()=>{e.addDeviceSession(i),expect(e.getDeviceSessions()).toEqual([i])}),it("should retrieve sessionObs",()=>{expect(e.sessionsObs).toBeInstanceOf(f.Observable)}),it("should emit new session",()=>new Promise((t,v)=>{const D=e.sessionsObs.subscribe({next(l){try{expect(l).toStrictEqual(i),D.unsubscribe(),t()}catch(A){v(A)}}});e.addDeviceSession(i)})),it("should emit previous added session",()=>{const t=(0,a.deviceSessionStubBuilder)({id:"last-session"},()=>o,c,n,r.DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS),v=[];e.addDeviceSession(i),e.addDeviceSession(t);const D=e.sessionsObs.subscribe({next(l){v.push(l)}});t.close(),expect(v).toEqual([i,t]),D.unsubscribe()})});
|
|
2
2
|
//# sourceMappingURL=DefaultDeviceSessionService.test.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/service/DefaultDeviceSessionService.test.ts"],
|
|
4
|
-
"sourcesContent": ["import { Either, Left } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { type DmkConfig } from \"@api/DmkConfig\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { type DeviceSession } from \"@internal/device-session/model/DeviceSession\";\nimport { deviceSessionStubBuilder } from \"@internal/device-session/model/DeviceSession.stub\";\nimport { DeviceSessionNotFound } from \"@internal/device-session/model/Errors\";\nimport { DefaultLoggerPublisherService } from \"@internal/logger-publisher/service/DefaultLoggerPublisherService\";\nimport { AxiosManagerApiDataSource } from \"@internal/manager-api/data/AxiosManagerApiDataSource\";\nimport { type ManagerApiDataSource } from \"@internal/manager-api/data/ManagerApiDataSource\";\nimport { DefaultManagerApiService } from \"@internal/manager-api/service/DefaultManagerApiService\";\nimport type { ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { DefaultSecureChannelDataSource } from \"@internal/secure-channel/data/DefaultSecureChannelDataSource\";\nimport { type SecureChannelDataSource } from \"@internal/secure-channel/data/SecureChannelDataSource\";\nimport { DefaultSecureChannelService } from \"@internal/secure-channel/service/DefaultSecureChannelService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DefaultDeviceSessionService } from \"./DefaultDeviceSessionService\";\n\nvi.mock(\"@internal/logger-publisher/service/DefaultLoggerPublisherService\");\nvi.mock(\"@internal/manager-api/data/AxiosManagerApiDataSource\");\n\nlet sessionService: DefaultDeviceSessionService;\nlet loggerService: DefaultLoggerPublisherService;\nlet deviceSession: DeviceSession;\nlet managerApiDataSource: ManagerApiDataSource;\nlet managerApi: ManagerApiService;\nlet secureChannelDataSource: SecureChannelDataSource;\nlet secureChannel: SecureChannelService;\n\ndescribe(\"DefaultDeviceSessionService\", () => {\n
|
|
5
|
-
"mappings": "aAAA,IAAAA,EAA6B,qBAC7BC,EAA2B,gBAG3BC,EAAyD,qEAEzDC,EAAyC,6DACzCC,EAAsC,iDACtCC,EAA8C,4EAC9CC,EAA0C,gEAE1CC,EAAyC,kEAEzCC,EAA+C,wEAE/CC,EAA4C,wEAG5CC,EAA4C,yCAE5C,GAAG,KAAK,kEAAkE,EAC1E,GAAG,KAAK,sDAAsD,EAE9D,IAAIC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EAEJ,SAAS,8BAA+B,IAAM,
|
|
6
|
-
"names": ["import_purify_ts", "import_rxjs", "import_DeviceSessionRefresherConst", "import_DeviceSession", "import_Errors", "import_DefaultLoggerPublisherService", "import_AxiosManagerApiDataSource", "import_DefaultManagerApiService", "import_DefaultSecureChannelDataSource", "import_DefaultSecureChannelService", "import_DefaultDeviceSessionService", "sessionService", "loggerService", "deviceSession", "managerApiDataSource", "managerApi", "secureChannelDataSource", "secureChannel", "resolve", "reject", "subscription", "emittedDeviceSession", "error", "lastDeviceSession", "emittedSessions"]
|
|
4
|
+
"sourcesContent": ["import { Either, Left } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { type DmkConfig } from \"@api/DmkConfig\";\nimport { connectedDeviceStubBuilder } from \"@api/transport/model/TransportConnectedDevice.stub\";\nimport { DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS } from \"@internal/device-session/data/DeviceSessionRefresherConst\";\nimport { type DeviceSession } from \"@internal/device-session/model/DeviceSession\";\nimport { deviceSessionStubBuilder } from \"@internal/device-session/model/DeviceSession.stub\";\nimport { DeviceSessionNotFound } from \"@internal/device-session/model/Errors\";\nimport { DefaultLoggerPublisherService } from \"@internal/logger-publisher/service/DefaultLoggerPublisherService\";\nimport { AxiosManagerApiDataSource } from \"@internal/manager-api/data/AxiosManagerApiDataSource\";\nimport { type ManagerApiDataSource } from \"@internal/manager-api/data/ManagerApiDataSource\";\nimport { DefaultManagerApiService } from \"@internal/manager-api/service/DefaultManagerApiService\";\nimport type { ManagerApiService } from \"@internal/manager-api/service/ManagerApiService\";\nimport { DefaultSecureChannelDataSource } from \"@internal/secure-channel/data/DefaultSecureChannelDataSource\";\nimport { type SecureChannelDataSource } from \"@internal/secure-channel/data/SecureChannelDataSource\";\nimport { DefaultSecureChannelService } from \"@internal/secure-channel/service/DefaultSecureChannelService\";\nimport { type SecureChannelService } from \"@internal/secure-channel/service/SecureChannelService\";\n\nimport { DefaultDeviceSessionService } from \"./DefaultDeviceSessionService\";\n\nvi.mock(\"@internal/logger-publisher/service/DefaultLoggerPublisherService\");\nvi.mock(\"@internal/manager-api/data/AxiosManagerApiDataSource\");\n\nlet sessionService: DefaultDeviceSessionService;\nlet loggerService: DefaultLoggerPublisherService;\nlet deviceSession: DeviceSession;\nlet deviceSession1: DeviceSession;\nlet deviceSession2: DeviceSession;\nlet managerApiDataSource: ManagerApiDataSource;\nlet managerApi: ManagerApiService;\nlet secureChannelDataSource: SecureChannelDataSource;\nlet secureChannel: SecureChannelService;\n\ndescribe(\"DefaultDeviceSessionService\", () => {\n // Initialize shared resources\n loggerService = new DefaultLoggerPublisherService([], \"deviceSession\");\n managerApiDataSource = new AxiosManagerApiDataSource({} as DmkConfig);\n managerApi = new DefaultManagerApiService(managerApiDataSource);\n secureChannelDataSource = new DefaultSecureChannelDataSource({} as DmkConfig);\n secureChannel = new DefaultSecureChannelService(secureChannelDataSource);\n\n beforeEach(() => {\n vi.restoreAllMocks();\n // Create a new instance before each test\n sessionService = new DefaultDeviceSessionService(() => loggerService);\n // Create a device session stub with default properties\n deviceSession = deviceSessionStubBuilder(\n {},\n () => loggerService,\n managerApi,\n secureChannel,\n DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n );\n });\n\n afterEach(() => {\n deviceSession.close();\n });\n\n it(\"should have an empty DeviceSession list\", () => {\n expect(sessionService.getDeviceSessions()).toEqual([]);\n });\n\n describe(\"DeviceSessionService addDeviceSession\", () => {\n it(\"should add a DeviceSession if it does not already exist\", () => {\n sessionService.addDeviceSession(deviceSession);\n expect(sessionService.getDeviceSessions()).toEqual([deviceSession]);\n });\n it(\"should not add a DeviceSession if it already exists\", () => {\n sessionService.addDeviceSession(deviceSession);\n sessionService.addDeviceSession(deviceSession);\n expect(sessionService.getDeviceSessions()).toEqual([deviceSession]);\n });\n });\n\n describe(\"DeviceSessionService removeDeviceSession\", () => {\n it(\"should remove the DeviceSession of given ID\", () => {\n sessionService.addDeviceSession(deviceSession);\n sessionService.removeDeviceSession(deviceSession.id);\n expect(sessionService.getDeviceSessions()).toEqual([]);\n });\n it(\"should not remove the DeviceSession of given ID if it does not exist\", () => {\n sessionService.addDeviceSession(deviceSession);\n sessionService.removeDeviceSession(\"non-existent-id\");\n expect(sessionService.getDeviceSessions()).toEqual([deviceSession]);\n });\n });\n\n describe(\"DeviceSessionService getDeviceSessionById\", () => {\n it(\"should get the DeviceSession of given ID if it exists\", () => {\n sessionService.addDeviceSession(deviceSession);\n expect(sessionService.getDeviceSessionById(deviceSession.id)).toEqual(\n Either.of(deviceSession),\n );\n });\n it(\"should not get the DeviceSession if it does not exist\", () => {\n sessionService.addDeviceSession(deviceSession);\n expect(sessionService.getDeviceSessionById(\"non-existent-id\")).toEqual(\n Left(new DeviceSessionNotFound()),\n );\n });\n });\n\n describe(\"DeviceSessionService getDeviceSessionsByDeviceId\", () => {\n it(\"should not get device sessions by deviceId if none exist\", () => {\n sessionService.addDeviceSession(deviceSession);\n expect(\n sessionService.getDeviceSessionsByDeviceId(\"non-existent-device-id\"),\n ).toEqual(Left(new DeviceSessionNotFound()));\n });\n it(\"should get a single device session by deviceId\", () => {\n sessionService.addDeviceSession(deviceSession);\n expect(\n sessionService.getDeviceSessionsByDeviceId(\n deviceSession.connectedDevice.id,\n ),\n ).toEqual(Either.of([deviceSession]));\n });\n it(\"should get device sessions by deviceId\", () => {\n sessionService.addDeviceSession(deviceSession);\n deviceSession1 = deviceSessionStubBuilder(\n {\n connectedDevice: connectedDeviceStubBuilder({ id: \"device-1\" }),\n id: \"session-1\",\n },\n () => loggerService,\n managerApi,\n secureChannel,\n DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n );\n\n deviceSession2 = deviceSessionStubBuilder(\n {\n connectedDevice: connectedDeviceStubBuilder({ id: \"device-1\" }),\n id: \"session-2\",\n },\n () => loggerService,\n managerApi,\n secureChannel,\n DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n );\n sessionService.addDeviceSession(deviceSession1);\n sessionService.addDeviceSession(deviceSession2);\n expect(sessionService.getDeviceSessionsByDeviceId(\"device-1\")).toEqual(\n Either.of([deviceSession1, deviceSession2]),\n );\n deviceSession1.close();\n deviceSession2.close();\n });\n });\n\n it(\"should get all sessions\", () => {\n sessionService.addDeviceSession(deviceSession);\n expect(sessionService.getDeviceSessions()).toEqual([deviceSession]);\n });\n\n it(\"should retrieve sessionObs\", () => {\n expect(sessionService.sessionsObs).toBeInstanceOf(\n Observable<DeviceSession>,\n );\n });\n\n it(\"should emit new session\", () =>\n new Promise<void>((resolve, reject) => {\n const subscription = sessionService.sessionsObs.subscribe({\n next(emittedDeviceSession) {\n try {\n expect(emittedDeviceSession).toStrictEqual(deviceSession);\n subscription.unsubscribe();\n resolve();\n } catch (error) {\n reject(error);\n }\n },\n });\n sessionService.addDeviceSession(deviceSession);\n }));\n\n it(\"should emit previous added session\", () => {\n const lastDeviceSession = deviceSessionStubBuilder(\n { id: \"last-session\" },\n () => loggerService,\n managerApi,\n secureChannel,\n DEVICE_SESSION_REFRESHER_DEFAULT_OPTIONS,\n );\n const emittedSessions: DeviceSession[] = [];\n sessionService.addDeviceSession(deviceSession);\n sessionService.addDeviceSession(lastDeviceSession);\n\n const subscription = sessionService.sessionsObs.subscribe({\n next(emittedDeviceSession) {\n emittedSessions.push(emittedDeviceSession);\n },\n });\n lastDeviceSession.close();\n expect(emittedSessions).toEqual([deviceSession, lastDeviceSession]);\n subscription.unsubscribe();\n });\n});\n"],
|
|
5
|
+
"mappings": "aAAA,IAAAA,EAA6B,qBAC7BC,EAA2B,gBAG3BC,EAA2C,8DAC3CC,EAAyD,qEAEzDC,EAAyC,6DACzCC,EAAsC,iDACtCC,EAA8C,4EAC9CC,EAA0C,gEAE1CC,EAAyC,kEAEzCC,EAA+C,wEAE/CC,EAA4C,wEAG5CC,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gBC,CAAc,CAAC,CAC5C,EACAD,EAAe,MAAM,EACrBC,EAAe,MAAM,CACvB,CAAC,CACH,CAAC,EAED,GAAG,0BAA2B,IAAM,CAClCJ,EAAe,iBAAiBE,CAAa,EAC7C,OAAOF,EAAe,kBAAkB,CAAC,EAAE,QAAQ,CAACE,CAAa,CAAC,CACpE,CAAC,EAED,GAAG,6BAA8B,IAAM,CACrC,OAAOF,EAAe,WAAW,EAAE,eACjC,YACF,CACF,CAAC,EAED,GAAG,0BAA2B,IAC5B,IAAI,QAAc,CAACS,EAASC,IAAW,CACrC,MAAMC,EAAeX,EAAe,YAAY,UAAU,CACxD,KAAKY,EAAsB,CACzB,GAAI,CACF,OAAOA,CAAoB,EAAE,cAAcV,CAAa,EACxDS,EAAa,YAAY,EACzBF,EAAQ,CACV,OAASI,EAAO,CACdH,EAAOG,CAAK,CACd,CACF,CACF,CAAC,EACDb,EAAe,iBAAiBE,CAAa,CAC/C,CAAC,CAAC,EAEJ,GAAG,qCAAsC,IAAM,CAC7C,MAAMY,KAAoB,4BACxB,CAAE,GAAI,cAAe,EACrB,IAAMb,EACNK,EACAE,EACA,0CACF,EACMO,EAAmC,CAAC,EAC1Cf,EAAe,iBAAiBE,CAAa,EAC7CF,EAAe,iBAAiBc,CAAiB,EAEjD,MAAMH,EAAeX,EAAe,YAAY,UAAU,CACxD,KAAKY,EAAsB,CACzBG,EAAgB,KAAKH,CAAoB,CAC3C,CACF,CAAC,EACDE,EAAkB,MAAM,EACxB,OAAOC,CAAe,EAAE,QAAQ,CAACb,EAAeY,CAAiB,CAAC,EAClEH,EAAa,YAAY,CAC3B,CAAC,CACH,CAAC",
|
|
6
|
+
"names": ["import_purify_ts", "import_rxjs", "import_TransportConnectedDevice", "import_DeviceSessionRefresherConst", "import_DeviceSession", "import_Errors", "import_DefaultLoggerPublisherService", "import_AxiosManagerApiDataSource", "import_DefaultManagerApiService", "import_DefaultSecureChannelDataSource", "import_DefaultSecureChannelService", "import_DefaultDeviceSessionService", "sessionService", "loggerService", "deviceSession", "deviceSession1", "deviceSession2", "managerApiDataSource", "managerApi", "secureChannelDataSource", "secureChannel", "resolve", "reject", "subscription", "emittedDeviceSession", "error", "lastDeviceSession", "emittedSessions"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var r=Object.defineProperty;var
|
|
1
|
+
"use strict";var r=Object.defineProperty;var c=Object.getOwnPropertyDescriptor;var n=Object.getOwnPropertyNames;var t=Object.prototype.hasOwnProperty;var D=(i,e,v,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of n(e))!t.call(i,s)&&s!==v&&r(i,s,{get:()=>e[s],enumerable:!(o=c(e,s))||o.enumerable});return i};var S=i=>D(r({},"__esModule",{value:!0}),i);var m={};module.exports=S(m);
|
|
2
2
|
//# sourceMappingURL=DeviceSessionService.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/service/DeviceSessionService.ts"],
|
|
4
|
-
"sourcesContent": ["import { type Either } from \"purify-ts\";\nimport { type Observable } from \"rxjs\";\n\nimport { type DmkError } from \"@api/Error\";\nimport { type DeviceSession } from \"@internal/device-session/model/DeviceSession\";\n\nexport interface DeviceSessionService {\n addDeviceSession(deviceSession: DeviceSession): DeviceSessionService;\n getDeviceSessionById(sessionId: string): Either<DmkError, DeviceSession>;\n
|
|
4
|
+
"sourcesContent": ["import { type Either } from \"purify-ts\";\nimport { type Observable } from \"rxjs\";\n\nimport { type DmkError } from \"@api/Error\";\nimport { type DeviceId } from \"@api/types\";\nimport { type DeviceSession } from \"@internal/device-session/model/DeviceSession\";\n\nexport interface DeviceSessionService {\n /**\n * Add a device session.\n * @param deviceSession The device session to add.\n */\n addDeviceSession(deviceSession: DeviceSession): DeviceSessionService;\n\n /**\n * Get a device session by its ID.\n * @param sessionId The ID of the session to retrieve.\n * @returns The device session or an error if not found.\n */\n getDeviceSessionById(sessionId: string): Either<DmkError, DeviceSession>;\n\n /**\n * Get device sessions by device ID.\n * @param deviceId The ID of the device.\n * @returns The device sessions of the device or an error if not found.\n */\n getDeviceSessionsByDeviceId(\n deviceId: DeviceId,\n ): Either<DmkError, DeviceSession[]>;\n\n /**\n * Remove a device session by its ID.\n * @param sessionId The ID of the session to remove.\n */\n removeDeviceSession(sessionId: string): DeviceSessionService;\n\n /**\n * Get all device sessions.\n * @returns An array of device sessions.\n */\n getDeviceSessions(): DeviceSession[];\n\n /**\n * Get an observable of device sessions.\n * @returns An observable of device sessions.\n */\n get sessionsObs(): Observable<DeviceSession>;\n}\n"],
|
|
5
5
|
"mappings": "+WAAA,IAAAA,EAAA,kBAAAC,EAAAD",
|
|
6
6
|
"names": ["DeviceSessionService_exports", "__toCommonJS"]
|
|
7
7
|
}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var p=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var C=(n,e)=>{for(var s in e)p(n,s,{get:e[s],enumerable:!0})},T=(n,e,s,
|
|
1
|
+
"use strict";var p=Object.defineProperty;var S=Object.getOwnPropertyDescriptor;var _=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var C=(n,e)=>{for(var s in e)p(n,s,{get:e[s],enumerable:!0})},T=(n,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of _(e))!A.call(n,i)&&i!==s&&p(n,i,{get:()=>e[i],enumerable:!(r=S(e,i))||r.enumerable});return n};var I=n=>T(p({},"__esModule",{value:!0}),n),g=(n,e,s,r)=>{for(var i=r>1?void 0:r?S(e,s):e,o=n.length-1,t;o>=0;o--)(t=n[o])&&(i=(r?t(e,s,i):t(i))||i);return r&&i&&p(e,s,i),i},a=(n,e)=>(s,r)=>e(s,r,n);var E={};C(E,{ConnectUseCase:()=>v});module.exports=I(E);var c=require("inversify"),m=require("purify-ts"),h=require("../../../api/transport/model/Errors"),d=require("../../device-session/di/deviceSessionTypes"),l=require("../../device-session/model/DeviceSession"),f=require("../../logger-publisher/di/loggerTypes"),D=require("../../manager-api/di/managerApiTypes"),y=require("../../secure-channel/di/secureChannelTypes"),u=require("../../transport/di/transportDiTypes");let v=class{_transportService;_sessionService;_loggerFactory;_managerApi;_secureChannel;_logger;constructor(e,s,r,i,o){this._sessionService=s,this._transportService=e,this._loggerFactory=r,this._logger=r("ConnectUseCase"),this._managerApi=i,this._secureChannel=o}handleDeviceDisconnect(e){this._sessionService.getDeviceSessionsByDeviceId(e).ifRight(s=>{s.forEach(r=>{this._sessionService.removeDeviceSession(r.id),this._logger.info("Session removed",{data:{deviceId:e,sessionId:r.id}})})})}async execute({device:e,sessionRefresherOptions:s}){const r=this._transportService.getTransport(e.transport),i="sessionId"in e?e.sessionId:void 0;return m.EitherAsync.liftEither(r.toEither(new h.TransportNotSupportedError(new Error("Unknown transport")))).chain(async o=>o.connect({deviceId:e.id,onDisconnect:t=>this.handleDeviceDisconnect(t)})).ifLeft(o=>{this._logger.error("Error connecting to device",{data:{deviceId:e.id,error:o}})}).map(async o=>{const t=new l.DeviceSession({connectedDevice:o,id:i},this._loggerFactory,this._managerApi,this._secureChannel,s);return this._sessionService.addDeviceSession(t),await t.initialiseSession(),t.id}).caseOf({Left:o=>{throw o},Right:o=>o})}};v=g([(0,c.injectable)(),a(0,(0,c.inject)(u.transportDiTypes.TransportService)),a(1,(0,c.inject)(d.deviceSessionTypes.DeviceSessionService)),a(2,(0,c.inject)(f.loggerTypes.LoggerPublisherServiceFactory)),a(3,(0,c.inject)(D.managerApiTypes.ManagerApiService)),a(4,(0,c.inject)(y.secureChannelTypes.SecureChannelService))],v);0&&(module.exports={ConnectUseCase});
|
|
2
2
|
//# sourceMappingURL=ConnectUseCase.js.map
|