@ledgerhq/device-management-kit 0.0.0-legacy-speculos-datasource-20250821095840 → 0.0.0-log-apdu-format-20251022090324

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +3 -3
  2. package/lib/cjs/package.json +1 -1
  3. package/lib/cjs/src/api/DeviceManagementKit.js +1 -1
  4. package/lib/cjs/src/api/DeviceManagementKit.js.map +3 -3
  5. package/lib/cjs/src/api/DeviceManagementKit.test.js +1 -1
  6. package/lib/cjs/src/api/DeviceManagementKit.test.js.map +3 -3
  7. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
  8. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js.map +2 -2
  9. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
  10. package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
  11. package/lib/cjs/src/api/device/DeviceModel.js +1 -1
  12. package/lib/cjs/src/api/device/DeviceModel.js.map +2 -2
  13. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js +1 -1
  14. package/lib/cjs/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  15. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js +1 -1
  16. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js.map +3 -3
  17. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js +1 -1
  18. package/lib/cjs/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js.map +2 -2
  19. package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
  20. package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +2 -2
  21. package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.js +1 -1
  22. package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.js.map +2 -2
  23. package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.test.js +1 -1
  24. package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.test.js.map +2 -2
  25. package/lib/cjs/src/api/logger-subscriber/service/ConsoleLogger.js +1 -1
  26. package/lib/cjs/src/api/logger-subscriber/service/ConsoleLogger.js.map +3 -3
  27. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  28. package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +2 -2
  29. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  30. package/lib/cjs/src/api/transport/model/DeviceConnectionStateMachine.js.map +2 -2
  31. package/lib/cjs/src/api/transport/model/Errors.js +1 -1
  32. package/lib/cjs/src/api/transport/model/Errors.js.map +3 -3
  33. package/lib/cjs/src/api/utils/HexaString.js +1 -1
  34. package/lib/cjs/src/api/utils/HexaString.js.map +3 -3
  35. package/lib/cjs/src/api/utils/HexaString.test.js +1 -1
  36. package/lib/cjs/src/api/utils/HexaString.test.js.map +2 -2
  37. package/lib/cjs/src/internal/device-session/model/DeviceSession.js +1 -1
  38. package/lib/cjs/src/internal/device-session/model/DeviceSession.js.map +3 -3
  39. package/lib/cjs/src/internal/device-session/service/DefaultApduReceiverService.js +1 -1
  40. package/lib/cjs/src/internal/device-session/service/DefaultApduReceiverService.js.map +2 -2
  41. package/lib/cjs/src/internal/device-session/service/DefaultApduSenderService.js +1 -1
  42. package/lib/cjs/src/internal/device-session/service/DefaultApduSenderService.js.map +2 -2
  43. package/lib/cjs/src/internal/device-session/service/DefaultDeviceSessionService.js +1 -1
  44. package/lib/cjs/src/internal/device-session/service/DefaultDeviceSessionService.js.map +2 -2
  45. package/lib/esm/package.json +1 -1
  46. package/lib/esm/src/api/DeviceManagementKit.js +1 -1
  47. package/lib/esm/src/api/DeviceManagementKit.js.map +3 -3
  48. package/lib/esm/src/api/DeviceManagementKit.test.js +1 -1
  49. package/lib/esm/src/api/DeviceManagementKit.test.js.map +3 -3
  50. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
  51. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js.map +3 -3
  52. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
  53. package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
  54. package/lib/esm/src/api/device/DeviceModel.js +1 -1
  55. package/lib/esm/src/api/device/DeviceModel.js.map +2 -2
  56. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js +1 -1
  57. package/lib/esm/src/api/device-action/model/UserInteractionRequired.js.map +2 -2
  58. package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js +1 -1
  59. package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.js.map +3 -3
  60. package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js +1 -1
  61. package/lib/esm/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.test.js.map +2 -2
  62. package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
  63. package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +2 -2
  64. package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.js +1 -1
  65. package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.js.map +2 -2
  66. package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.test.js +1 -1
  67. package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.test.js.map +2 -2
  68. package/lib/esm/src/api/logger-subscriber/service/ConsoleLogger.js +1 -1
  69. package/lib/esm/src/api/logger-subscriber/service/ConsoleLogger.js.map +3 -3
  70. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
  71. package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +2 -2
  72. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js +1 -1
  73. package/lib/esm/src/api/transport/model/DeviceConnectionStateMachine.js.map +2 -2
  74. package/lib/esm/src/api/transport/model/Errors.js +1 -1
  75. package/lib/esm/src/api/transport/model/Errors.js.map +3 -3
  76. package/lib/esm/src/api/utils/HexaString.js +1 -1
  77. package/lib/esm/src/api/utils/HexaString.js.map +3 -3
  78. package/lib/esm/src/api/utils/HexaString.test.js +1 -1
  79. package/lib/esm/src/api/utils/HexaString.test.js.map +2 -2
  80. package/lib/esm/src/internal/device-session/model/DeviceSession.js +1 -1
  81. package/lib/esm/src/internal/device-session/model/DeviceSession.js.map +3 -3
  82. package/lib/esm/src/internal/device-session/service/DefaultApduReceiverService.js +1 -1
  83. package/lib/esm/src/internal/device-session/service/DefaultApduReceiverService.js.map +2 -2
  84. package/lib/esm/src/internal/device-session/service/DefaultApduSenderService.js +1 -1
  85. package/lib/esm/src/internal/device-session/service/DefaultApduSenderService.js.map +2 -2
  86. package/lib/esm/src/internal/device-session/service/DefaultDeviceSessionService.js +1 -1
  87. package/lib/esm/src/internal/device-session/service/DefaultDeviceSessionService.js.map +2 -2
  88. package/lib/types/src/api/DeviceManagementKit.d.ts +4 -0
  89. package/lib/types/src/api/DeviceManagementKit.d.ts.map +1 -1
  90. package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts +38 -0
  91. package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts.map +1 -1
  92. package/lib/types/src/api/device/DeviceModel.d.ts +1 -1
  93. package/lib/types/src/api/device/DeviceModel.d.ts.map +1 -1
  94. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts +2 -1
  95. package/lib/types/src/api/device-action/model/UserInteractionRequired.d.ts.map +1 -1
  96. package/lib/types/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.d.ts +1 -1
  97. package/lib/types/src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.d.ts.map +1 -1
  98. package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts +1 -0
  99. package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts.map +1 -1
  100. package/lib/types/src/api/logger-subscriber/service/ConsoleLogger.d.ts +1 -0
  101. package/lib/types/src/api/logger-subscriber/service/ConsoleLogger.d.ts.map +1 -1
  102. package/lib/types/src/api/transport/model/Errors.d.ts +5 -0
  103. package/lib/types/src/api/transport/model/Errors.d.ts.map +1 -1
  104. package/lib/types/src/api/utils/HexaString.d.ts +4 -3
  105. package/lib/types/src/api/utils/HexaString.d.ts.map +1 -1
  106. package/lib/types/src/internal/device-session/model/DeviceSession.d.ts.map +1 -1
  107. package/lib/types/src/internal/device-session/service/DefaultApduReceiverService.d.ts.map +1 -1
  108. package/lib/types/src/internal/device-session/service/DefaultDeviceSessionService.d.ts.map +1 -1
  109. package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
  110. package/package.json +5 -5
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/apdu/utils/ByteArrayBuilder.ts"],
4
- "sourcesContent": ["import { hexaStringToBuffer } from \"@api/utils/HexaString\";\n\nimport {\n type AppBuilderError,\n DataOverflowError,\n HexaStringEncodeError,\n ValueOverflowError,\n} from \"./AppBuilderError\";\n\nconst MAX_32_BIT_UINT = 0xffffffff;\n\n/**\n * ByteArrayBuilder is a utility class to help build APDU payloads.\n * It allows to easily add data to the payload of an APDU command\n * and to encode this data in different formats.\n *\n * @example\n * ```\n * const builder = new ByteArrayBuilder(255)\n * .add8BitUIntToData(0x05)\n * .add16BitUIntToData(0x0607)\n * .addHexaStringToData(\"0x0809\")\n * .addAsciiStringToData(\"hello\")\n *\n * const payload = builder.build();\n * const builderErrors = builder.getErrors();\n * ```\n */\nexport class ByteArrayBuilder {\n private data: Uint8Array = new Uint8Array();\n private readonly errors: AppBuilderError[] = []; // Custom Error\n\n constructor(private maxPayloadSize: number = MAX_32_BIT_UINT) {}\n\n // ==========\n // Public API\n // ==========\n\n /**\n * Build a new payload instance with the current state of the builder\n * @returns {payload} - Returns a new payload instance\n */\n build = (): Uint8Array => this.data;\n\n /**\n * Try to build a new payload instance with the current state of the builder\n * if the builder don't contain any error.\n * @returns {payload | undefined} - Returns a new payload instance or undefined\n */\n tryBuild = (): Uint8Array | undefined => {\n return this.hasErrors() ? undefined : this.data;\n };\n\n /**\n * Add a 8-bit unsigned integer to the payload (max value 0xff = 255)\n * @param value: number | bigint - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add8BitUIntToData = (value: number | bigint): ByteArrayBuilder => {\n return this.addNumberToData(value, 8n, false, false);\n };\n\n /**\n * Add a 16-bit unsigned integer to the payload (max value 0xffff = 65535)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add16BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 16n, false, bigEndian);\n };\n\n /**\n * Add a 32-bit unsigned integer to the payload (max value 0xffffffff = 4294967295)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add32BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 32n, false, bigEndian);\n };\n\n /**\n * Add a 64-bit unsigned integer to the payload (max value 0xffffffffffffffff = 18446744073709551615)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add64BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 64n, false, bigEndian);\n };\n\n /**\n * Add a 128-bit unsigned integer to the payload\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add128BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 128n, false, bigEndian);\n };\n\n /**\n * Add a 256-bit unsigned integer to the payload\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add256BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 256n, false, bigEndian);\n };\n\n /**\n * Add a 16-bit signed integer to the payload (value between -0x8000 to 0x7fff)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add16BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 16n, true, bigEndian);\n };\n\n /**\n * Add a 32-bit signed integer to the payload (value between -0x80000000 to 0x7fffffff)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add32BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 32n, true, bigEndian);\n };\n\n /**\n * Add a 64-bit signed integer to the payload (value between -0x8000000000000000 to 0x7fffffffffffffff)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add64BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 64n, true, bigEndian);\n };\n\n /**\n * Add a 128-bit signed integer to the payload\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add128BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 128n, true, bigEndian);\n };\n\n /**\n * Add a 256-bit signed integer to the payload\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add256BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 256n, true, bigEndian);\n };\n\n /**\n * Add a Uint8Array to the payload if it has enough remaining space\n * @param value: Uint8Array - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n addBufferToData = (value: Uint8Array): ByteArrayBuilder => {\n if (!this.hasEnoughLengthRemaining(value)) {\n this.errors.push(new DataOverflowError(value.toString()));\n return this;\n }\n\n this.data = Uint8Array.from([...this.data, ...value]);\n return this;\n };\n\n /**\n * Add a string to the payload if it has enough remaining space\n * and it can be formatted as a hexadecimal string\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n addHexaStringToData = (value: string): ByteArrayBuilder => {\n const result = hexaStringToBuffer(value);\n if (result === null || result.length === 0) {\n this.errors.push(new HexaStringEncodeError(value));\n return this;\n }\n this.addBufferToData(result);\n return this;\n };\n\n /**\n * Add an ascii string to the data field if it has enough remaining space\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n addAsciiStringToData = (value: string): ByteArrayBuilder => {\n const bytes = new TextEncoder().encode(value);\n this.addBufferToData(bytes);\n return this;\n };\n\n /**\n * Add a Length-Value encoded hexadecimal string to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInLVFromHexa = (value: string): ByteArrayBuilder => {\n const result = hexaStringToBuffer(value);\n if (result === null || result.length === 0) {\n this.errors.push(new HexaStringEncodeError(value));\n return this;\n }\n\n if (!this.hasEnoughLengthRemaining(result, true)) {\n this.errors.push(new DataOverflowError(value));\n return this;\n }\n // values are always being well formatted at this point\n // therefore no status test is needed\n this.add8BitUIntToData(result.length);\n this.addBufferToData(result);\n return this;\n };\n\n /**\n * Add a Length-Value encoded buffer to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param value: Uint8Array - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInLVFromBuffer = (value: Uint8Array): ByteArrayBuilder => {\n if (!this.hasEnoughLengthRemaining(value, true)) {\n this.errors.push(new DataOverflowError(value.toString()));\n return this;\n }\n\n this.add8BitUIntToData(value.length);\n this.addBufferToData(value);\n return this;\n };\n\n /**\n * Add a Length-Value encoded ascii string to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInLVFromAscii = (value: string): ByteArrayBuilder => {\n if (!this.hasEnoughLengthRemaining(value, true)) {\n this.errors.push(new DataOverflowError(value));\n return this;\n }\n\n this.add8BitUIntToData(value.length);\n this.addAsciiStringToData(value);\n return this;\n };\n\n /**\n * Add a Tag-Length-Value encoded hexadecimal string to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromHexa = (tag: number, value: string): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n return this.encodeInLVFromHexa(value);\n };\n\n /**\n * Add a Tag-Length-Value encoded hexadecimal string to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: Uint8Array - The buffer to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromBuffer = (\n tag: number,\n value: Uint8Array,\n ): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n return this.encodeInLVFromBuffer(value);\n };\n\n /**\n * Add a Tag-Length-Value encoded uint64 to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: number | bigint - The number to add\n * @param bigEndian: boolean - Endianness used to encode the number\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromUInt64 = (\n tag: number,\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n this.add8BitUIntToData(8);\n return this.add64BitUIntToData(value, bigEndian);\n };\n\n /**\n * Returns the remaining payload length\n * @returns {number}\n */\n getAvailablePayloadLength = (): number => {\n return this.maxPayloadSize - this.data.length;\n };\n\n /**\n * Returns the current errors\n * @returns {AppBuilderError[]} - Returns an array of errors\n */\n getErrors = (): AppBuilderError[] => this.errors;\n\n /**\n * Verifies if the builder contains errors\n * @returns {boolean} - Returns wether the builder contains errors or not\n */\n hasErrors = (): boolean => this.errors.length !== 0;\n\n // ===========\n // Private API\n // ===========\n\n /**\n * Check if there is enough space to add a value to the data field\n * @param value {string | Uint8Array | number[]} - Value to add to the data\n * @param hasLv {boolean} - Length-Value encoding flag\n * @returns {boolean} - Returns true if there is enough space to add the value\n */\n private hasEnoughLengthRemaining = (\n value: string | Uint8Array | number[],\n hasLv: boolean = false,\n ): boolean => {\n return (\n this.data.length + value.length + (hasLv ? 1 : 0) <= this.maxPayloadSize\n );\n };\n\n /**\n * Add a number to the payload\n * @param value: number | bigint - The value to add to the data\n * @param sizeInBits: bigint - The number size in bits, for example 16 for a uint16\n * @param signed: boolean - Whether the value is signed or unsigned.\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n private addNumberToData(\n value: number | bigint,\n sizeInBits: bigint,\n signed: boolean,\n bigEndian: boolean,\n ): ByteArrayBuilder {\n // Convert the number to two's complement and check its bounds\n let converted = this.checkBoundsAndConvert(value, sizeInBits, signed);\n if (converted === undefined) {\n return this;\n }\n\n // Compute the buffer\n const sizeInBytes = Number(sizeInBits) / 8;\n const buffer = new Uint8Array(sizeInBytes);\n if (bigEndian) {\n for (let i = sizeInBytes - 1; i >= 0; i--) {\n buffer[i] = Number(converted & 0xffn);\n converted >>= 8n;\n }\n } else {\n for (let i = 0; i < sizeInBytes; i++) {\n buffer[i] = Number(converted & 0xffn);\n converted >>= 8n;\n }\n }\n return this.addBufferToData(buffer);\n }\n\n /**\n * Checks the bounds of a signed or unsigned integer value and converts it to two's complement if it is signed and negative.\n * @param value The value to check and convert.\n * @param sizeInBits The size of the value in bits.\n * @param signed Whether the value is signed or unsigned.\n * @returns The converted value, or null if the value is out of bounds.\n */\n private checkBoundsAndConvert(\n value: number | bigint,\n sizeInBits: bigint,\n signed: boolean,\n ): bigint | undefined {\n // Normalize the value to a bigint\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value > Number.MAX_SAFE_INTEGER) {\n this.errors.push(new ValueOverflowError(value.toString()));\n return;\n }\n value = BigInt(value);\n }\n\n if (!signed) {\n // Check if the value is within the bounds of an unsigned integer\n const limit = 1n << sizeInBits;\n if (value < 0 || value >= limit) {\n this.errors.push(new ValueOverflowError(value.toString(), limit - 1n));\n return;\n }\n } else {\n // Check if the value is within the bounds of a signed integer\n const limit = 1n << (sizeInBits - 1n);\n if (value >= limit || value < -limit) {\n this.errors.push(new ValueOverflowError(value.toString(), limit - 1n));\n return;\n }\n\n // Convert the value to two's complement if it is negative\n // https://en.wikipedia.org/wiki/Two%27s_complement\n if (value < 0n) {\n const mask = (1n << sizeInBits) - 1n;\n value = -value;\n value = (~value & mask) + 1n;\n }\n }\n return value;\n }\n}\n"],
5
- "mappings": "AAAA,OAAS,sBAAAA,MAA0B,wBAEnC,OAEE,qBAAAC,EACA,yBAAAC,EACA,sBAAAC,MACK,oBAEP,MAAMC,EAAkB,WAmBjB,MAAMC,CAAiB,CAI5B,YAAoBC,EAAyBF,EAAiB,CAA1C,oBAAAE,CAA2C,CAHvD,KAAmB,IAAI,WACd,OAA4B,CAAC,EAY9C,MAAQ,IAAkB,KAAK,KAO/B,SAAW,IACF,KAAK,UAAU,EAAI,OAAY,KAAK,KAQ7C,kBAAqBC,GACZ,KAAK,gBAAgBA,EAAO,GAAI,GAAO,EAAK,EASrD,mBAAqB,CACnBA,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,IAAK,GAAOC,CAAS,EAS1D,mBAAqB,CACnBD,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,IAAK,GAAOC,CAAS,EAS1D,mBAAqB,CACnBD,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,IAAK,GAAOC,CAAS,EAS1D,oBAAsB,CACpBD,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,KAAM,GAAOC,CAAS,EAS3D,oBAAsB,CACpBD,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,KAAM,GAAOC,CAAS,EAS3D,kBAAoB,CAClBD,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,IAAK,GAAMC,CAAS,EASzD,kBAAoB,CAClBD,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,IAAK,GAAMC,CAAS,EASzD,kBAAoB,CAClBD,EACAC,EA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K,GAAKA,EAAQ,OAAO,iBAAkB,CAC/D,KAAK,OAAO,KAAK,IAAIJ,EAAmBI,EAAM,SAAS,CAAC,CAAC,EACzD,MACF,CACAA,EAAQ,OAAOA,CAAK,CACtB,CAEA,GAAKO,EAOE,CAEL,MAAMI,EAAQ,IAAOL,EAAa,GAClC,GAAIN,GAASW,GAASX,EAAQ,CAACW,EAAO,CACpC,KAAK,OAAO,KAAK,IAAIf,EAAmBI,EAAM,SAAS,EAAGW,EAAQ,EAAE,CAAC,EACrE,MACF,CAIA,GAAIX,EAAQ,GAAI,CACd,MAAMY,GAAQ,IAAMN,GAAc,GAClCN,EAAQ,CAACA,EACTA,GAAS,CAACA,EAAQY,GAAQ,EAC5B,CACF,KAtBa,CAEX,MAAMD,EAAQ,IAAML,EACpB,GAAIN,EAAQ,GAAKA,GAASW,EAAO,CAC/B,KAAK,OAAO,KAAK,IAAIf,EAAmBI,EAAM,SAAS,EAAGW,EAAQ,EAAE,CAAC,EACrE,MACF,CACF,CAgBA,OAAOX,CACT,CACF",
6
- "names": ["hexaStringToBuffer", "DataOverflowError", "HexaStringEncodeError", "ValueOverflowError", "MAX_32_BIT_UINT", "ByteArrayBuilder", "maxPayloadSize", "value", "bigEndian", "result", "bytes", "tag", "hasLv", "sizeInBits", "signed", "converted", "sizeInBytes", "buffer", "limit", "mask"]
4
+ "sourcesContent": ["import { hexaStringToBuffer } from \"@api/utils/HexaString\";\n\nimport {\n type AppBuilderError,\n DataOverflowError,\n HexaStringEncodeError,\n ValueOverflowError,\n} from \"./AppBuilderError\";\n\nconst MAX_32_BIT_UINT = 0xffffffff;\n\n/**\n * ByteArrayBuilder is a utility class to help build APDU payloads.\n * It allows to easily add data to the payload of an APDU command\n * and to encode this data in different formats.\n *\n * @example\n * ```\n * const builder = new ByteArrayBuilder(255)\n * .add8BitUIntToData(0x05)\n * .add16BitUIntToData(0x0607)\n * .addHexaStringToData(\"0x0809\")\n * .addAsciiStringToData(\"hello\")\n *\n * const payload = builder.build();\n * const builderErrors = builder.getErrors();\n * ```\n */\nexport class ByteArrayBuilder {\n private data: Uint8Array = new Uint8Array();\n private readonly errors: AppBuilderError[] = []; // Custom Error\n\n constructor(private maxPayloadSize: number = MAX_32_BIT_UINT) {}\n\n // ==========\n // Public API\n // ==========\n\n /**\n * Build a new payload instance with the current state of the builder\n * @returns {payload} - Returns a new payload instance\n */\n build = (): Uint8Array => this.data;\n\n /**\n * Try to build a new payload instance with the current state of the builder\n * if the builder don't contain any error.\n * @returns {payload | undefined} - Returns a new payload instance or undefined\n */\n tryBuild = (): Uint8Array | undefined => {\n return this.hasErrors() ? undefined : this.data;\n };\n\n /**\n * Add a 8-bit unsigned integer to the payload (max value 0xff = 255)\n * @param value: number | bigint - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add8BitUIntToData = (value: number | bigint): ByteArrayBuilder => {\n return this.addNumberToData(value, 8n, false, false);\n };\n\n /**\n * Add a 16-bit unsigned integer to the payload (max value 0xffff = 65535)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add16BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 16n, false, bigEndian);\n };\n\n /**\n * Add a 32-bit unsigned integer to the payload (max value 0xffffffff = 4294967295)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add32BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 32n, false, bigEndian);\n };\n\n /**\n * Add a 64-bit unsigned integer to the payload (max value 0xffffffffffffffff = 18446744073709551615)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add64BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 64n, false, bigEndian);\n };\n\n /**\n * Add a 128-bit unsigned integer to the payload\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add128BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 128n, false, bigEndian);\n };\n\n /**\n * Add a 256-bit unsigned integer to the payload\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add256BitUIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 256n, false, bigEndian);\n };\n\n /**\n * Add a 16-bit signed integer to the payload (value between -0x8000 to 0x7fff)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add16BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 16n, true, bigEndian);\n };\n\n /**\n * Add a 32-bit signed integer to the payload (value between -0x80000000 to 0x7fffffff)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add32BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 32n, true, bigEndian);\n };\n\n /**\n * Add a 64-bit signed integer to the payload (value between -0x8000000000000000 to 0x7fffffffffffffff)\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add64BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 64n, true, bigEndian);\n };\n\n /**\n * Add a 128-bit signed integer to the payload\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add128BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 128n, true, bigEndian);\n };\n\n /**\n * Add a 256-bit signed integer to the payload\n * @param value: number | bigint - The value to add to the data\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n add256BitIntToData = (\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n return this.addNumberToData(value, 256n, true, bigEndian);\n };\n\n /**\n * Add a Uint8Array to the payload if it has enough remaining space\n * @param value: Uint8Array - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n addBufferToData = (value: Uint8Array): ByteArrayBuilder => {\n if (!this.hasEnoughLengthRemaining(value)) {\n this.errors.push(new DataOverflowError(value.toString()));\n return this;\n }\n\n this.data = Uint8Array.from([...this.data, ...value]);\n return this;\n };\n\n /**\n * Add a string to the payload if it has enough remaining space\n * and it can be formatted as a hexadecimal string\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n addHexaStringToData = (value: string): ByteArrayBuilder => {\n const result = hexaStringToBuffer(value);\n if (result === null || result.length === 0) {\n this.errors.push(new HexaStringEncodeError(value));\n return this;\n }\n this.addBufferToData(result);\n return this;\n };\n\n /**\n * Add an ascii string to the data field if it has enough remaining space\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n addAsciiStringToData = (value: string): ByteArrayBuilder => {\n const bytes = new TextEncoder().encode(value);\n this.addBufferToData(bytes);\n return this;\n };\n\n /**\n * Add a Length-Value encoded hexadecimal string to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInLVFromHexa = (value: string): ByteArrayBuilder => {\n const result = hexaStringToBuffer(value);\n if (result === null || result.length === 0) {\n this.errors.push(new HexaStringEncodeError(value));\n return this;\n }\n\n if (!this.hasEnoughLengthRemaining(result, true)) {\n this.errors.push(new DataOverflowError(value));\n return this;\n }\n // values are always being well formatted at this point\n // therefore no status test is needed\n this.add8BitUIntToData(result.length);\n this.addBufferToData(result);\n return this;\n };\n\n /**\n * Add a Length-Value encoded buffer to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param value: Uint8Array - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInLVFromBuffer = (value: Uint8Array): ByteArrayBuilder => {\n if (!this.hasEnoughLengthRemaining(value, true)) {\n this.errors.push(new DataOverflowError(value.toString()));\n return this;\n }\n\n this.add8BitUIntToData(value.length);\n this.addBufferToData(value);\n return this;\n };\n\n /**\n * Add a Length-Value encoded ascii string to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInLVFromAscii = (value: string): ByteArrayBuilder => {\n if (!this.hasEnoughLengthRemaining(value, true)) {\n this.errors.push(new DataOverflowError(value));\n return this;\n }\n\n this.add8BitUIntToData(value.length);\n this.addAsciiStringToData(value);\n return this;\n };\n\n /**\n * Add a Tag-Length-Value encoded ascii string to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromAscii = (tag: number, value: string): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n return this.encodeInLVFromAscii(value);\n };\n\n /**\n * Add a Tag-Length-Value encoded hexadecimal string to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: string - The value to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromHexa = (tag: number, value: string): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n return this.encodeInLVFromHexa(value);\n };\n\n /**\n * Add a Tag-Length-Value encoded hexadecimal string to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: Uint8Array - The buffer to add to the data\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromBuffer = (\n tag: number,\n value: Uint8Array,\n ): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n return this.encodeInLVFromBuffer(value);\n };\n\n /**\n * Add a Tag-Length-Value encoded uint8 to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: number - The number to add\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromUInt8 = (tag: number, value: number): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n this.add8BitUIntToData(1);\n return this.add8BitUIntToData(value);\n };\n\n /**\n * Add a Tag-Length-Value encoded uint16 to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: number | bigint - The number to add\n * @param bigEndian: boolean - Endianness used to encode the number\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromUInt16 = (\n tag: number,\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n this.add8BitUIntToData(2);\n return this.add16BitUIntToData(value, bigEndian);\n };\n\n /**\n * Add a Tag-Length-Value encoded uint32 to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: number | bigint - The number to add\n * @param bigEndian: boolean - Endianness used to encode the number\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromUInt32 = (\n tag: number,\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n this.add8BitUIntToData(4);\n return this.add32BitUIntToData(value, bigEndian);\n };\n\n /**\n * Add a Tag-Length-Value encoded uint64 to the data field if it has enough remaining space\n * Length-Value encoding is a way to encode data in a binary format with the first byte\n * being the length of the data and the following bytes being the data itself\n * @param tag: number - The tag to add to the data\n * @param value: number | bigint - The number to add\n * @param bigEndian: boolean - Endianness used to encode the number\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n encodeInTLVFromUInt64 = (\n tag: number,\n value: number | bigint,\n bigEndian: boolean = true,\n ): ByteArrayBuilder => {\n this.add8BitUIntToData(tag);\n this.add8BitUIntToData(8);\n return this.add64BitUIntToData(value, bigEndian);\n };\n\n /**\n * Returns the remaining payload length\n * @returns {number}\n */\n getAvailablePayloadLength = (): number => {\n return this.maxPayloadSize - this.data.length;\n };\n\n /**\n * Returns the current errors\n * @returns {AppBuilderError[]} - Returns an array of errors\n */\n getErrors = (): AppBuilderError[] => this.errors;\n\n /**\n * Verifies if the builder contains errors\n * @returns {boolean} - Returns wether the builder contains errors or not\n */\n hasErrors = (): boolean => this.errors.length !== 0;\n\n // ===========\n // Private API\n // ===========\n\n /**\n * Check if there is enough space to add a value to the data field\n * @param value {string | Uint8Array | number[]} - Value to add to the data\n * @param hasLv {boolean} - Length-Value encoding flag\n * @returns {boolean} - Returns true if there is enough space to add the value\n */\n private hasEnoughLengthRemaining = (\n value: string | Uint8Array | number[],\n hasLv: boolean = false,\n ): boolean => {\n return (\n this.data.length + value.length + (hasLv ? 1 : 0) <= this.maxPayloadSize\n );\n };\n\n /**\n * Add a number to the payload\n * @param value: number | bigint - The value to add to the data\n * @param sizeInBits: bigint - The number size in bits, for example 16 for a uint16\n * @param signed: boolean - Whether the value is signed or unsigned.\n * @param bigEndian: boolean - True to encode in big endian, false for little endian\n * @returns {ByteArrayBuilder} - Returns the current instance of ByteArrayBuilder\n */\n private addNumberToData(\n value: number | bigint,\n sizeInBits: bigint,\n signed: boolean,\n bigEndian: boolean,\n ): ByteArrayBuilder {\n // Convert the number to two's complement and check its bounds\n let converted = this.checkBoundsAndConvert(value, sizeInBits, signed);\n if (converted === undefined) {\n return this;\n }\n\n // Compute the buffer\n const sizeInBytes = Number(sizeInBits) / 8;\n const buffer = new Uint8Array(sizeInBytes);\n if (bigEndian) {\n for (let i = sizeInBytes - 1; i >= 0; i--) {\n buffer[i] = Number(converted & 0xffn);\n converted >>= 8n;\n }\n } else {\n for (let i = 0; i < sizeInBytes; i++) {\n buffer[i] = Number(converted & 0xffn);\n converted >>= 8n;\n }\n }\n return this.addBufferToData(buffer);\n }\n\n /**\n * Checks the bounds of a signed or unsigned integer value and converts it to two's complement if it is signed and negative.\n * @param value The value to check and convert.\n * @param sizeInBits The size of the value in bits.\n * @param signed Whether the value is signed or unsigned.\n * @returns The converted value, or null if the value is out of bounds.\n */\n private checkBoundsAndConvert(\n value: number | bigint,\n sizeInBits: bigint,\n signed: boolean,\n ): bigint | undefined {\n // Normalize the value to a bigint\n if (typeof value === \"number\") {\n if (!Number.isInteger(value) || value > Number.MAX_SAFE_INTEGER) {\n this.errors.push(new ValueOverflowError(value.toString()));\n return;\n }\n value = BigInt(value);\n }\n\n if (!signed) {\n // Check if the value is within the bounds of an unsigned integer\n const limit = 1n << sizeInBits;\n if (value < 0 || value >= limit) {\n this.errors.push(new ValueOverflowError(value.toString(), limit - 1n));\n return;\n }\n } else {\n // Check if the value is within the bounds of a signed integer\n const limit = 1n << (sizeInBits - 1n);\n if (value >= limit || value < -limit) {\n this.errors.push(new ValueOverflowError(value.toString(), limit - 1n));\n return;\n }\n\n // Convert the value to two's complement if it is negative\n // https://en.wikipedia.org/wiki/Two%27s_complement\n if (value < 0n) {\n const mask = (1n << sizeInBits) - 1n;\n value = -value;\n value = (~value & mask) + 1n;\n }\n }\n return value;\n }\n}\n"],
5
+ "mappings": "AAAA,OAAS,sBAAAA,MAA0B,wBAEnC,OAEE,qBAAAC,EACA,yBAAAC,EACA,sBAAAC,MACK,oBAEP,MAAMC,EAAkB,WAmBjB,MAAMC,CAAiB,CAI5B,YAAoBC,EAAyBF,EAAiB,CAA1C,oBAAAE,CAA2C,CAHvD,KAAmB,IAAI,WACd,OAA4B,CAAC,EAY9C,MAAQ,IAAkB,KAAK,KAO/B,SAAW,IACF,KAAK,UAAU,EAAI,OAAY,KAAK,KAQ7C,kBAAqBC,GACZ,KAAK,gBAAgBA,EAAO,GAAI,GAAO,EAAK,EASrD,mBAAqB,CACnBA,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,IAAK,GAAOC,CAAS,EAS1D,mBAAqB,CACnBD,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,IAAK,GAAOC,CAAS,EAS1D,mBAAqB,CACnBD,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,IAAK,GAAOC,CAAS,EAS1D,oBAAsB,CACpBD,EACAC,EAAqB,KAEd,KAAK,gBAAgBD,EAAO,KAAM,GAAOC,CAA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AAQ,IAAMN,EACpB,GAAIN,EAAQ,GAAKA,GAASY,EAAO,CAC/B,KAAK,OAAO,KAAK,IAAIhB,EAAmBI,EAAM,SAAS,EAAGY,EAAQ,EAAE,CAAC,EACrE,MACF,CACF,CAgBA,OAAOZ,CACT,CACF",
6
+ "names": ["hexaStringToBuffer", "DataOverflowError", "HexaStringEncodeError", "ValueOverflowError", "MAX_32_BIT_UINT", "ByteArrayBuilder", "maxPayloadSize", "value", "bigEndian", "result", "bytes", "tag", "hasLv", "sizeInBits", "signed", "converted", "sizeInBytes", "buffer", "i", "limit", "mask"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{hexaStringToBuffer as b}from"../../utils/HexaString";import{APDU_MAX_PAYLOAD as a}from"./ApduBuilder";import{DataOverflowError as l,HexaStringEncodeError as i}from"./AppBuilderError";import{ByteArrayBuilder as n}from"./ByteArrayBuilder";const u=new Uint8Array([]),y=new Uint8Array([1]),A=new Uint8Array([128,129,130,131,132]),p=new Uint8Array([133,134,135,136]),E=new Uint8Array([3,161,162,163]),h=new Uint8Array([5,109,97,109,97,110]),s=new Uint8Array([2,240,241]),w=new Uint8Array([1,51,2,1,35,69,103,128,129,130,131,132,133,134,135,136,3,161,162,163,5,109,97,109,97,110,2,240,241]),x=new Uint8Array([...Array(255).fill(170)]),g=new Uint8Array([...Array(254).fill(170)]);let e;describe("ByteArrayBuilder",()=>{const d=(f,t,r,o)=>{if(o)switch(r){case 2:e.add16BitIntToData(f,t);break;case 4:e.add32BitIntToData(f,t);break;case 8:e.add64BitIntToData(f,t);break;case 16:e.add128BitIntToData(f,t);break;case 32:e.add256BitIntToData(f,t);break}else switch(r){case 2:e.add16BitUIntToData(f,t);break;case 4:e.add32BitUIntToData(f,t);break;case 8:e.add64BitUIntToData(f,t);break;case 16:e.add128BitUIntToData(f,t);break;case 32:e.add256BitUIntToData(f,t);break}};describe("clean",()=>{beforeEach(()=>{e=new n(a)}),it("should create an instance",()=>{expect(e).toBeDefined(),expect(e).toBeInstanceOf(n)})}),describe("simple",()=>{beforeEach(()=>{e=new n(a)}),it("should serialize with an empty body",()=>{expect(e.build()).toEqual(u)}),it("should serialize with an single byte body",()=>{e=new n(1),e.add8BitUIntToData(1),expect(e.build()).toEqual(y),expect(e.getErrors()).toEqual([])}),it.each([[2,!1,!0,13058,"3302"],[2,!1,!1,0x3302n,"0233"],[2,!0,!0,4200n,"1068"],[2,!0,!0,-4200n,"ef98"],[2,!0,!1,4200,"6810"],[2,!0,!1,-4200,"98ef"],[4,!1,!0,0x01234567n,"01234567"],[4,!1,!1,0x01234567n,"67452301"],[4,!0,!0,123456789,"075bcd15"],[4,!0,!0,-123456789,"f8a432eb"],[4,!0,!1,123456789,"15cd5b07"],[4,!0,!1,-123456789,"eb32a4f8"],[8,!1,!0,14147778004927559n,"0032435442584447"],[8,!1,!1,14147778004927559n,"4744584254433200"],[8,!0,!0,14147778004927559n,"0032435442584447"],[8,!0,!0,-14147778004927559n,"ffcdbcabbda7bbb9"],[8,!0,!1,14147778004927559n,"4744584254433200"],[8,!0,!1,-14147778004927559n,"b9bba7bdabbccdff"],[16,!1,!0,0x00324354425844470032435442584447n,"00324354425844470032435442584447"],[16,!1,!1,0x00324354425844470032435442584447n,"47445842544332004744584254433200"],[16,!0,!0,0x00324354425844470032435442584447n,"00324354425844470032435442584447"],[16,!0,!0,-0x00324354425844470032435442584447n,"ffcdbcabbda7bbb8ffcdbcabbda7bbb9"],[16,!0,!1,0x00324354425844470032435442584447n,"47445842544332004744584254433200"],[16,!0,!1,-0x00324354425844470032435442584447n,"b9bba7bdabbccdffb8bba7bdabbccdff"],[32,!1,!0,0x0032435442584447003243544258444700324354425844470032435442584447n,"0032435442584447003243544258444700324354425844470032435442584447"],[32,!1,!1,0x0032435442584447003243544258444700324354425844470032435442584447n,"4744584254433200474458425443320047445842544332004744584254433200"],[32,!0,!0,0x0032435442584447003243544258444700324354425844470032435442584447n,"0032435442584447003243544258444700324354425844470032435442584447"],[32,!0,!0,-0x0032435442584447003243544258444700324354425844470032435442584447n,"ffcdbcabbda7bbb8ffcdbcabbda7bbb8ffcdbcabbda7bbb8ffcdbcabbda7bbb9"],[32,!0,!1,0x0032435442584447003243544258444700324354425844470032435442584447n,"4744584254433200474458425443320047445842544332004744584254433200"],[32,!0,!1,-0x0032435442584447003243544258444700324354425844470032435442584447n,"b9bba7bdabbccdffb8bba7bdabbccdffb8bba7bdabbccdffb8bba7bdabbccdff"]])("serialize the following number: size %i, signed %s, bigEndian %s, value %i, expected %s",(f,t,r,o,c)=>{e=new n(f),d(o,r,f,t),expect(e.build()).toEqual(b(c)),expect(e.getErrors()).toEqual([]),e=new n(f-1),d(o,r,f,t),expect(e.getErrors().length).toEqual(1),expect(e.build()).toEqual(Uint8Array.from([]))}),it.each([[2,!1,!0,0xffffn,"ffff"],[2,!0,!0,0x7fffn,"7fff"],[2,!0,!0,-0x8000n,"8000"],[4,!1,!0,0xffffffffn,"ffffffff"],[4,!0,!0,0x7fffffffn,"7fffffff"],[4,!0,!0,-0x80000000n,"80000000"],[8,!1,!0,0xffffffffffffffffn,"ffffffffffffffff"],[8,!0,!0,0x7fffffffffffffffn,"7fffffffffffffff"],[8,!0,!0,-0x8000000000000000n,"8000000000000000"],[16,!1,!0,0xffffffffffffffffffffffffffffffffn,"ffffffffffffffffffffffffffffffff"],[16,!0,!0,0x7fffffffffffffffffffffffffffffffn,"7fffffffffffffffffffffffffffffff"],[16,!0,!0,-0x80000000000000000000000000000000n,"80000000000000000000000000000000"],[32,!1,!0,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"],[32,!0,!0,0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"],[32,!0,!0,-0x8000000000000000000000000000000000000000000000000000000000000000n,"8000000000000000000000000000000000000000000000000000000000000000"]])("serialize the number to the limit: size %i, signed %s, bigEndian %s, value %i, expected %s",(f,t,r,o,c)=>{e=new n(f),d(o,r,f,t),expect(e.build()).toEqual(b(c)),expect(e.getErrors()).toEqual([])}),it("Serialize from float to bigint",()=>{e=new n(4),e.add32BitIntToData(1234567893e-1,!1),expect(e.getErrors().length).toEqual(1),expect(e.build()).toEqual(Uint8Array.from([]))}),it("should serialize with an 5 byte body from an hexastring",()=>{e.addHexaStringToData("0x8081828384"),expect(e.build()).toEqual(A),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body from an hexastring without '0x'",()=>{e.addHexaStringToData("85868788"),expect(e.build()).toEqual(p),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body LV encoded from an hexastring",()=>{e.encodeInLVFromHexa("0xA1A2A3"),expect(e.build()).toEqual(E),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body LV encoded from an ascci string",()=>{e.encodeInLVFromAscii("maman"),expect(e.build()).toEqual(h),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body LV encoded from a buffer",()=>{const f=new Uint8Array([240,241]);e.encodeInLVFromBuffer(f),expect(e.build()).toEqual(s),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body LV encoded from a buffer",()=>{const f=new Uint8Array([240,241]);e.encodeInLVFromBuffer(f),expect(e.build()).toEqual(s),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from an hexastring",()=>{e.encodeInTLVFromHexa(5,"0xA1A2A3"),expect(e.build()).toEqual(Uint8Array.from([5,3,161,162,163])),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from a buffer",()=>{e.encodeInTLVFromBuffer(6,Uint8Array.from([161,162,163,164])),expect(e.build()).toEqual(Uint8Array.from([6,4,161,162,163,164])),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from an uint64",()=>{e.encodeInTLVFromUInt64(6,95075813176406),expect(e.build()).toEqual(Uint8Array.from([6,8,0,0,86,120,144,18,52,86])),expect(e.getErrors()).toEqual([])}),it("should serialize with an complete body of 0xAA",()=>{const f=new Uint8Array(255).fill(170,0,255);e.addBufferToData(f),expect(e.build()).toEqual(x),expect(e.getErrors()).toEqual([])})}),describe("mixed",()=>{beforeEach(()=>{e=new n(a)}),it("should serialize with all previous field",()=>{let f=a;e.add8BitUIntToData(1),f--,expect(e.getAvailablePayloadLength()).toBe(f),e.add16BitUIntToData(13058),f-=2,expect(e.getAvailablePayloadLength()).toBe(f),e.add32BitUIntToData(19088743),f-=4,expect(e.getAvailablePayloadLength()).toBe(f),e.addHexaStringToData("0x8081828384"),f-=5,expect(e.getAvailablePayloadLength()).toBe(f),e.addHexaStringToData("85868788"),f-=4,expect(e.getAvailablePayloadLength()).toBe(f),e.encodeInLVFromHexa("0xA1A2A3"),f-=4,expect(e.getAvailablePayloadLength()).toBe(f),e.encodeInLVFromAscii("maman"),f-=6,expect(e.getAvailablePayloadLength()).toBe(f);const t=new Uint8Array([240,241]);e.encodeInLVFromBuffer(t),f-=3,expect(e.getAvailablePayloadLength()).toBe(f),expect(e.build()).toEqual(w)})}),describe("error",()=>{beforeEach(()=>{e=new n(a)}),it.each([[2,!1,!0,0x10000n],[2,!0,!0,0x8000n],[2,!0,!0,-0x8001n],[4,!1,!0,0x100000000n],[4,!0,!0,0x80000000n],[4,!0,!0,-0x80000001n],[8,!1,!0,0x10000000000000000n],[8,!0,!0,0x8000000000000000n],[8,!0,!0,-0x8000000000000001n]])("serialize the number overflowed: size %i, signed %s, bigEndian %s, value %i",(f,t,r,o)=>{e=new n(f),d(o,r,f,t),expect(e.getErrors().length).toEqual(1),expect(e.build()).toEqual(Uint8Array.from([]))}),it("error due to a string not well coded",()=>{e.addHexaStringToData(":08081828384").addHexaStringToData("80818n8384").addHexaStringToData("808182838z"),expect(e.build()).toEqual(u),expect(e.getAvailablePayloadLength()).toBe(a),expect(e.getErrors()).toEqual([new i(":08081828384"),new i("80818n8384"),new i("808182838z")])}),it("error due direct overflow",()=>{const f=new Uint8Array(256).fill(170,0,256);e.addBufferToData(f),expect(e.build()).toEqual(u),expect(e.getAvailablePayloadLength()).toBe(a),expect(e.getErrors()).toEqual([new l(f.toString())])}),it("error due to subsequent overflow with 1-byte array",()=>{const f=new Uint8Array(a).fill(170,0,a);e.addBufferToData(f),expect(e.build()).toEqual(x),expect(e.getAvailablePayloadLength()).toBe(0);const t=new Uint8Array(1);t.set([255],0),e.addBufferToData(t),expect(e.build()).toEqual(x),expect(e.getAvailablePayloadLength()).toBe(0),expect(e.getErrors()).toEqual([new l(t.toString())])}),it("error due to subsequent overflow with 1-char ascii",()=>{const f=new Uint8Array(a).fill(170,0,a);e.addBufferToData(f),expect(e.build()).toEqual(x),expect(e.getAvailablePayloadLength()).toBe(0);const t="a";e.addAsciiStringToData(t),expect(e.build()).toEqual(x),expect(e.getAvailablePayloadLength()).toBe(0),expect(e.getErrors()).toEqual([new l(new TextEncoder().encode(t).toString())])}),it("error due to subsequent overflow with 1-char hexastring",()=>{const f=new Uint8Array(a).fill(170,0,a);e.addBufferToData(f),expect(e.build()).toEqual(x),expect(e.getAvailablePayloadLength()).toBe(0),e.addHexaStringToData("0xB4").addHexaStringToData("e1"),expect(e.build()).toEqual(x),expect(e.getAvailablePayloadLength()).toBe(0),expect(e.getErrors()).toEqual([new l("180"),new l("225")])}),it("error due to empty values",()=>{const f="";e.addHexaStringToData(f).encodeInLVFromHexa(f),expect(e.build()).toEqual(u),expect(e.getAvailablePayloadLength()).toBe(a),expect(e.getErrors()).toEqual([new i(f),new i(f)])}),it("error due to subsequent overflow with 1-char LV",()=>{const f=new Uint8Array(a-1).fill(170,0,a-1);e.addBufferToData(f),expect(e.build()).toEqual(g),expect(e.getAvailablePayloadLength()).toBe(1);const t="n",r="e1",o=new Uint8Array(1);o.set([255],0),e.encodeInLVFromAscii(t).encodeInLVFromHexa(r).encodeInLVFromBuffer(o),expect(e.build()).toEqual(g),expect(e.getAvailablePayloadLength()).toBe(1),expect(e.getErrors()).toEqual([new l(t),new l(r),new l(o.toString())])})})});
1
+ import{hexaStringToBuffer as b}from"../../utils/HexaString";import{APDU_MAX_PAYLOAD as a}from"./ApduBuilder";import{DataOverflowError as x,HexaStringEncodeError as i}from"./AppBuilderError";import{ByteArrayBuilder as n}from"./ByteArrayBuilder";const u=new Uint8Array([]),y=new Uint8Array([1]),A=new Uint8Array([128,129,130,131,132]),E=new Uint8Array([133,134,135,136]),p=new Uint8Array([3,161,162,163]),h=new Uint8Array([5,109,97,109,97,110]),s=new Uint8Array([2,240,241]),w=new Uint8Array([1,51,2,1,35,69,103,128,129,130,131,132,133,134,135,136,3,161,162,163,5,109,97,109,97,110,2,240,241]),l=new Uint8Array([...Array(255).fill(170)]),g=new Uint8Array([...Array(254).fill(170)]);let e;describe("ByteArrayBuilder",()=>{const d=(f,t,r,o)=>{if(o)switch(r){case 2:e.add16BitIntToData(f,t);break;case 4:e.add32BitIntToData(f,t);break;case 8:e.add64BitIntToData(f,t);break;case 16:e.add128BitIntToData(f,t);break;case 32:e.add256BitIntToData(f,t);break}else switch(r){case 2:e.add16BitUIntToData(f,t);break;case 4:e.add32BitUIntToData(f,t);break;case 8:e.add64BitUIntToData(f,t);break;case 16:e.add128BitUIntToData(f,t);break;case 32:e.add256BitUIntToData(f,t);break}};describe("clean",()=>{beforeEach(()=>{e=new n(a)}),it("should create an instance",()=>{expect(e).toBeDefined(),expect(e).toBeInstanceOf(n)})}),describe("simple",()=>{beforeEach(()=>{e=new n(a)}),it("should serialize with an empty body",()=>{expect(e.build()).toEqual(u)}),it("should serialize with an single byte body",()=>{e=new n(1),e.add8BitUIntToData(1),expect(e.build()).toEqual(y),expect(e.getErrors()).toEqual([])}),it.each([[2,!1,!0,13058,"3302"],[2,!1,!1,0x3302n,"0233"],[2,!0,!0,4200n,"1068"],[2,!0,!0,-4200n,"ef98"],[2,!0,!1,4200,"6810"],[2,!0,!1,-4200,"98ef"],[4,!1,!0,0x01234567n,"01234567"],[4,!1,!1,0x01234567n,"67452301"],[4,!0,!0,123456789,"075bcd15"],[4,!0,!0,-123456789,"f8a432eb"],[4,!0,!1,123456789,"15cd5b07"],[4,!0,!1,-123456789,"eb32a4f8"],[8,!1,!0,14147778004927559n,"0032435442584447"],[8,!1,!1,14147778004927559n,"4744584254433200"],[8,!0,!0,14147778004927559n,"0032435442584447"],[8,!0,!0,-14147778004927559n,"ffcdbcabbda7bbb9"],[8,!0,!1,14147778004927559n,"4744584254433200"],[8,!0,!1,-14147778004927559n,"b9bba7bdabbccdff"],[16,!1,!0,0x00324354425844470032435442584447n,"00324354425844470032435442584447"],[16,!1,!1,0x00324354425844470032435442584447n,"47445842544332004744584254433200"],[16,!0,!0,0x00324354425844470032435442584447n,"00324354425844470032435442584447"],[16,!0,!0,-0x00324354425844470032435442584447n,"ffcdbcabbda7bbb8ffcdbcabbda7bbb9"],[16,!0,!1,0x00324354425844470032435442584447n,"47445842544332004744584254433200"],[16,!0,!1,-0x00324354425844470032435442584447n,"b9bba7bdabbccdffb8bba7bdabbccdff"],[32,!1,!0,0x0032435442584447003243544258444700324354425844470032435442584447n,"0032435442584447003243544258444700324354425844470032435442584447"],[32,!1,!1,0x0032435442584447003243544258444700324354425844470032435442584447n,"4744584254433200474458425443320047445842544332004744584254433200"],[32,!0,!0,0x0032435442584447003243544258444700324354425844470032435442584447n,"0032435442584447003243544258444700324354425844470032435442584447"],[32,!0,!0,-0x0032435442584447003243544258444700324354425844470032435442584447n,"ffcdbcabbda7bbb8ffcdbcabbda7bbb8ffcdbcabbda7bbb8ffcdbcabbda7bbb9"],[32,!0,!1,0x0032435442584447003243544258444700324354425844470032435442584447n,"4744584254433200474458425443320047445842544332004744584254433200"],[32,!0,!1,-0x0032435442584447003243544258444700324354425844470032435442584447n,"b9bba7bdabbccdffb8bba7bdabbccdffb8bba7bdabbccdffb8bba7bdabbccdff"]])("serialize the following number: size %i, signed %s, bigEndian %s, value %i, expected %s",(f,t,r,o,c)=>{e=new n(f),d(o,r,f,t),expect(e.build()).toEqual(b(c)),expect(e.getErrors()).toEqual([]),e=new n(f-1),d(o,r,f,t),expect(e.getErrors().length).toEqual(1),expect(e.build()).toEqual(Uint8Array.from([]))}),it.each([[2,!1,!0,0xffffn,"ffff"],[2,!0,!0,0x7fffn,"7fff"],[2,!0,!0,-0x8000n,"8000"],[4,!1,!0,0xffffffffn,"ffffffff"],[4,!0,!0,0x7fffffffn,"7fffffff"],[4,!0,!0,-0x80000000n,"80000000"],[8,!1,!0,0xffffffffffffffffn,"ffffffffffffffff"],[8,!0,!0,0x7fffffffffffffffn,"7fffffffffffffff"],[8,!0,!0,-0x8000000000000000n,"8000000000000000"],[16,!1,!0,0xffffffffffffffffffffffffffffffffn,"ffffffffffffffffffffffffffffffff"],[16,!0,!0,0x7fffffffffffffffffffffffffffffffn,"7fffffffffffffffffffffffffffffff"],[16,!0,!0,-0x80000000000000000000000000000000n,"80000000000000000000000000000000"],[32,!1,!0,0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"],[32,!0,!0,0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"],[32,!0,!0,-0x8000000000000000000000000000000000000000000000000000000000000000n,"8000000000000000000000000000000000000000000000000000000000000000"]])("serialize the number to the limit: size %i, signed %s, bigEndian %s, value %i, expected %s",(f,t,r,o,c)=>{e=new n(f),d(o,r,f,t),expect(e.build()).toEqual(b(c)),expect(e.getErrors()).toEqual([])}),it("Serialize from float to bigint",()=>{e=new n(4),e.add32BitIntToData(1234567893e-1,!1),expect(e.getErrors().length).toEqual(1),expect(e.build()).toEqual(Uint8Array.from([]))}),it("should serialize with an 5 byte body from an hexastring",()=>{e.addHexaStringToData("0x8081828384"),expect(e.build()).toEqual(A),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body from an hexastring without '0x'",()=>{e.addHexaStringToData("85868788"),expect(e.build()).toEqual(E),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body LV encoded from an hexastring",()=>{e.encodeInLVFromHexa("0xA1A2A3"),expect(e.build()).toEqual(p),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body LV encoded from an ascci string",()=>{e.encodeInLVFromAscii("maman"),expect(e.build()).toEqual(h),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body LV encoded from a buffer",()=>{const f=new Uint8Array([240,241]);e.encodeInLVFromBuffer(f),expect(e.build()).toEqual(s),expect(e.getErrors()).toEqual([])}),it("should serialize with an 4 byte body LV encoded from a buffer",()=>{const f=new Uint8Array([240,241]);e.encodeInLVFromBuffer(f),expect(e.build()).toEqual(s),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from an ascii string",()=>{e.encodeInTLVFromAscii(5,"coucou"),expect(e.build()).toEqual(Uint8Array.from([5,6,99,111,117,99,111,117])),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from an hexastring",()=>{e.encodeInTLVFromHexa(5,"0xA1A2A3"),expect(e.build()).toEqual(Uint8Array.from([5,3,161,162,163])),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from a buffer",()=>{e.encodeInTLVFromBuffer(6,Uint8Array.from([161,162,163,164])),expect(e.build()).toEqual(Uint8Array.from([6,4,161,162,163,164])),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from an uint8",()=>{e.encodeInTLVFromUInt8(6,86),expect(e.build()).toEqual(Uint8Array.from([6,1,86])),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from an uint16",()=>{e.encodeInTLVFromUInt16(6,13398),expect(e.build()).toEqual(Uint8Array.from([6,2,52,86])),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from an uint32",()=>{e.encodeInTLVFromUInt32(6,2417112150),expect(e.build()).toEqual(Uint8Array.from([6,4,144,18,52,86])),expect(e.getErrors()).toEqual([])}),it("should serialize with an TLV encoded from an uint64",()=>{e.encodeInTLVFromUInt64(6,95075813176406),expect(e.build()).toEqual(Uint8Array.from([6,8,0,0,86,120,144,18,52,86])),expect(e.getErrors()).toEqual([])}),it("should serialize with an complete body of 0xAA",()=>{const f=new Uint8Array(255).fill(170,0,255);e.addBufferToData(f),expect(e.build()).toEqual(l),expect(e.getErrors()).toEqual([])})}),describe("mixed",()=>{beforeEach(()=>{e=new n(a)}),it("should serialize with all previous field",()=>{let f=a;e.add8BitUIntToData(1),f--,expect(e.getAvailablePayloadLength()).toBe(f),e.add16BitUIntToData(13058),f-=2,expect(e.getAvailablePayloadLength()).toBe(f),e.add32BitUIntToData(19088743),f-=4,expect(e.getAvailablePayloadLength()).toBe(f),e.addHexaStringToData("0x8081828384"),f-=5,expect(e.getAvailablePayloadLength()).toBe(f),e.addHexaStringToData("85868788"),f-=4,expect(e.getAvailablePayloadLength()).toBe(f),e.encodeInLVFromHexa("0xA1A2A3"),f-=4,expect(e.getAvailablePayloadLength()).toBe(f),e.encodeInLVFromAscii("maman"),f-=6,expect(e.getAvailablePayloadLength()).toBe(f);const t=new Uint8Array([240,241]);e.encodeInLVFromBuffer(t),f-=3,expect(e.getAvailablePayloadLength()).toBe(f),expect(e.build()).toEqual(w)})}),describe("error",()=>{beforeEach(()=>{e=new n(a)}),it.each([[2,!1,!0,0x10000n],[2,!0,!0,0x8000n],[2,!0,!0,-0x8001n],[4,!1,!0,0x100000000n],[4,!0,!0,0x80000000n],[4,!0,!0,-0x80000001n],[8,!1,!0,0x10000000000000000n],[8,!0,!0,0x8000000000000000n],[8,!0,!0,-0x8000000000000001n]])("serialize the number overflowed: size %i, signed %s, bigEndian %s, value %i",(f,t,r,o)=>{e=new n(f),d(o,r,f,t),expect(e.getErrors().length).toEqual(1),expect(e.build()).toEqual(Uint8Array.from([]))}),it("error due to a string not well coded",()=>{e.addHexaStringToData(":08081828384").addHexaStringToData("80818n8384").addHexaStringToData("808182838z"),expect(e.build()).toEqual(u),expect(e.getAvailablePayloadLength()).toBe(a),expect(e.getErrors()).toEqual([new i(":08081828384"),new i("80818n8384"),new i("808182838z")])}),it("error due direct overflow",()=>{const f=new Uint8Array(256).fill(170,0,256);e.addBufferToData(f),expect(e.build()).toEqual(u),expect(e.getAvailablePayloadLength()).toBe(a),expect(e.getErrors()).toEqual([new x(f.toString())])}),it("error due to subsequent overflow with 1-byte array",()=>{const f=new Uint8Array(a).fill(170,0,a);e.addBufferToData(f),expect(e.build()).toEqual(l),expect(e.getAvailablePayloadLength()).toBe(0);const t=new Uint8Array(1);t.set([255],0),e.addBufferToData(t),expect(e.build()).toEqual(l),expect(e.getAvailablePayloadLength()).toBe(0),expect(e.getErrors()).toEqual([new x(t.toString())])}),it("error due to subsequent overflow with 1-char ascii",()=>{const f=new Uint8Array(a).fill(170,0,a);e.addBufferToData(f),expect(e.build()).toEqual(l),expect(e.getAvailablePayloadLength()).toBe(0);const t="a";e.addAsciiStringToData(t),expect(e.build()).toEqual(l),expect(e.getAvailablePayloadLength()).toBe(0),expect(e.getErrors()).toEqual([new x(new TextEncoder().encode(t).toString())])}),it("error due to subsequent overflow with 1-char hexastring",()=>{const f=new Uint8Array(a).fill(170,0,a);e.addBufferToData(f),expect(e.build()).toEqual(l),expect(e.getAvailablePayloadLength()).toBe(0),e.addHexaStringToData("0xB4").addHexaStringToData("e1"),expect(e.build()).toEqual(l),expect(e.getAvailablePayloadLength()).toBe(0),expect(e.getErrors()).toEqual([new x("180"),new x("225")])}),it("error due to empty values",()=>{const f="";e.addHexaStringToData(f).encodeInLVFromHexa(f),expect(e.build()).toEqual(u),expect(e.getAvailablePayloadLength()).toBe(a),expect(e.getErrors()).toEqual([new i(f),new i(f)])}),it("error due to subsequent overflow with 1-char LV",()=>{const f=new Uint8Array(a-1).fill(170,0,a-1);e.addBufferToData(f),expect(e.build()).toEqual(g),expect(e.getAvailablePayloadLength()).toBe(1);const t="n",r="e1",o=new Uint8Array(1);o.set([255],0),e.encodeInLVFromAscii(t).encodeInLVFromHexa(r).encodeInLVFromBuffer(o),expect(e.build()).toEqual(g),expect(e.getAvailablePayloadLength()).toBe(1),expect(e.getErrors()).toEqual([new x(t),new x(r),new x(o.toString())])})})});
2
2
  //# sourceMappingURL=ByteArrayBuilder.test.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/apdu/utils/ByteArrayBuilder.test.ts"],
4
- "sourcesContent": ["import { hexaStringToBuffer } from \"@api/utils/HexaString\";\n\nimport { APDU_MAX_PAYLOAD } from \"./ApduBuilder\";\nimport { DataOverflowError, HexaStringEncodeError } from \"./AppBuilderError\";\nimport { ByteArrayBuilder } from \"./ByteArrayBuilder\";\n\nconst COMMAND_NO_BODY = new Uint8Array([]);\n\nconst COMMAND_BODY_SINGLE = new Uint8Array([0x01]);\n\nconst COMMAND_BODY_HEXA1 = new Uint8Array([0x80, 0x81, 0x82, 0x83, 0x84]);\n\nconst COMMAND_BODY_HEXA2 = new Uint8Array([0x85, 0x86, 0x87, 0x88]);\n\nconst COMMAND_BODY_LV_HEXA = new Uint8Array([0x03, 0xa1, 0xa2, 0xa3]);\n\nconst COMMAND_BODY_LV_ASCII = new Uint8Array([\n 0x05, 0x6d, 0x61, 0x6d, 0x61, 0x6e,\n]);\n\nconst COMMAND_BODY_LV_ARRAY = new Uint8Array([0x02, 0xf0, 0xf1]);\n\nconst COMMAND_BODY_COMBINED = new Uint8Array([\n 0x01, 0x33, 0x02, 0x01, 0x23, 0x45, 0x67, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85,\n 0x86, 0x87, 0x88, 0x03, 0xa1, 0xa2, 0xa3, 0x05, 0x6d, 0x61, 0x6d, 0x61, 0x6e,\n 0x02, 0xf0, 0xf1,\n]);\n\nconst COMMAND_BODY_MAX = new Uint8Array([...Array<number>(255).fill(0xaa)]);\n\nconst COMMAND_BODY_NEARLY = new Uint8Array([...Array<number>(254).fill(0xaa)]);\n\nlet builder: ByteArrayBuilder;\n\ndescribe(\"ByteArrayBuilder\", () => {\n const builderAddNumber = (\n num: number | bigint,\n bigEndian: boolean,\n sizeInBits: number,\n signed: boolean,\n ) => {\n if (signed) {\n switch (sizeInBits) {\n case 2:\n builder.add16BitIntToData(num, bigEndian);\n break;\n case 4:\n builder.add32BitIntToData(num, bigEndian);\n break;\n case 8:\n builder.add64BitIntToData(num, bigEndian);\n break;\n case 16:\n builder.add128BitIntToData(num, bigEndian);\n break;\n case 32:\n builder.add256BitIntToData(num, bigEndian);\n break;\n }\n } else {\n switch (sizeInBits) {\n case 2:\n builder.add16BitUIntToData(num, bigEndian);\n break;\n case 4:\n builder.add32BitUIntToData(num, bigEndian);\n break;\n case 8:\n builder.add64BitUIntToData(num, bigEndian);\n break;\n case 16:\n builder.add128BitUIntToData(num, bigEndian);\n break;\n case 32:\n builder.add256BitUIntToData(num, bigEndian);\n break;\n }\n }\n };\n\n describe(\"clean\", () => {\n beforeEach(() => {\n builder = new ByteArrayBuilder(APDU_MAX_PAYLOAD);\n });\n\n it(\"should create an instance\", () => {\n expect(builder).toBeDefined();\n expect(builder).toBeInstanceOf(ByteArrayBuilder);\n });\n });\n\n describe(\"simple\", () => {\n beforeEach(() => {\n builder = new ByteArrayBuilder(APDU_MAX_PAYLOAD);\n });\n\n it(\"should serialize with an empty body\", () => {\n expect(builder.build()).toEqual(COMMAND_NO_BODY);\n });\n\n it(\"should serialize with an single byte body\", () => {\n builder = new ByteArrayBuilder(1);\n builder.add8BitUIntToData(0x01);\n expect(builder.build()).toEqual(COMMAND_BODY_SINGLE);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it.each([\n [2, false, true, 0x3302, \"3302\"],\n [2, false, false, 0x3302n, \"0233\"],\n [2, true, true, 4200n, \"1068\"],\n [2, true, true, -4200n, \"ef98\"],\n [2, true, false, 4200, \"6810\"],\n [2, true, false, -4200, \"98ef\"],\n [4, false, true, 0x01234567n, \"01234567\"],\n [4, false, false, 0x01234567n, \"67452301\"],\n [4, true, true, 123456789, \"075bcd15\"],\n [4, true, true, -123456789, \"f8a432eb\"],\n [4, true, false, 123456789, \"15cd5b07\"],\n [4, true, false, -123456789, \"eb32a4f8\"],\n [8, false, true, 14147778004927559n, \"0032435442584447\"],\n [8, false, false, 14147778004927559n, \"4744584254433200\"],\n [8, true, true, 14147778004927559n, \"0032435442584447\"],\n [8, true, true, -14147778004927559n, \"ffcdbcabbda7bbb9\"],\n [8, true, false, 14147778004927559n, \"4744584254433200\"],\n [8, true, false, -14147778004927559n, \"b9bba7bdabbccdff\"],\n [\n 16,\n false,\n true,\n 0x00324354425844470032435442584447n,\n \"00324354425844470032435442584447\",\n ],\n [\n 16,\n false,\n false,\n 0x00324354425844470032435442584447n,\n \"47445842544332004744584254433200\",\n ],\n [\n 16,\n true,\n true,\n 0x00324354425844470032435442584447n,\n \"00324354425844470032435442584447\",\n ],\n [\n 16,\n true,\n true,\n -0x00324354425844470032435442584447n,\n \"ffcdbcabbda7bbb8ffcdbcabbda7bbb9\",\n ],\n [\n 16,\n true,\n false,\n 0x00324354425844470032435442584447n,\n \"47445842544332004744584254433200\",\n ],\n [\n 16,\n true,\n false,\n -0x00324354425844470032435442584447n,\n \"b9bba7bdabbccdffb8bba7bdabbccdff\",\n ],\n [\n 32,\n false,\n true,\n 0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"0032435442584447003243544258444700324354425844470032435442584447\",\n ],\n [\n 32,\n false,\n false,\n 0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"4744584254433200474458425443320047445842544332004744584254433200\",\n ],\n [\n 32,\n true,\n true,\n 0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"0032435442584447003243544258444700324354425844470032435442584447\",\n ],\n [\n 32,\n true,\n true,\n -0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"ffcdbcabbda7bbb8ffcdbcabbda7bbb8ffcdbcabbda7bbb8ffcdbcabbda7bbb9\",\n ],\n [\n 32,\n true,\n false,\n 0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"4744584254433200474458425443320047445842544332004744584254433200\",\n ],\n [\n 32,\n true,\n false,\n -0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"b9bba7bdabbccdffb8bba7bdabbccdffb8bba7bdabbccdffb8bba7bdabbccdff\",\n ],\n ])(\n \"serialize the following number: size %i, signed %s, bigEndian %s, value %i, expected %s\",\n (sizeInBits, signed, bigEndian, input, output) => {\n builder = new ByteArrayBuilder(sizeInBits);\n builderAddNumber(input, bigEndian, sizeInBits, signed);\n expect(builder.build()).toEqual(hexaStringToBuffer(output));\n expect(builder.getErrors()).toEqual([]);\n\n // Retry with a buffer too small\n builder = new ByteArrayBuilder(sizeInBits - 1);\n builderAddNumber(input, bigEndian, sizeInBits, signed);\n expect(builder.getErrors().length).toEqual(1);\n expect(builder.build()).toEqual(Uint8Array.from([]));\n },\n );\n\n it.each([\n [2, false, true, 0xffffn, \"ffff\"],\n [2, true, true, 0x7fffn, \"7fff\"],\n [2, true, true, -0x8000n, \"8000\"],\n [4, false, true, 0xffffffffn, \"ffffffff\"],\n [4, true, true, 0x7fffffffn, \"7fffffff\"],\n [4, true, true, -0x80000000n, \"80000000\"],\n [8, false, true, 0xffffffffffffffffn, \"ffffffffffffffff\"],\n [8, true, true, 0x7fffffffffffffffn, \"7fffffffffffffff\"],\n [8, true, true, -0x8000000000000000n, \"8000000000000000\"],\n [\n 16,\n false,\n true,\n 0xffffffffffffffffffffffffffffffffn,\n \"ffffffffffffffffffffffffffffffff\",\n ],\n [\n 16,\n true,\n true,\n 0x7fffffffffffffffffffffffffffffffn,\n \"7fffffffffffffffffffffffffffffff\",\n ],\n [\n 16,\n true,\n true,\n -0x80000000000000000000000000000000n,\n \"80000000000000000000000000000000\",\n ],\n [\n 32,\n false,\n true,\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,\n \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\",\n ],\n [\n 32,\n true,\n true,\n 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,\n \"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\",\n ],\n [\n 32,\n true,\n true,\n -0x8000000000000000000000000000000000000000000000000000000000000000n,\n \"8000000000000000000000000000000000000000000000000000000000000000\",\n ],\n ])(\n \"serialize the number to the limit: size %i, signed %s, bigEndian %s, value %i, expected %s\",\n (sizeInBits, signed, bigEndian, input, output) => {\n builder = new ByteArrayBuilder(sizeInBits);\n builderAddNumber(input, bigEndian, sizeInBits, signed);\n expect(builder.build()).toEqual(hexaStringToBuffer(output));\n expect(builder.getErrors()).toEqual([]);\n },\n );\n\n it(\"Serialize from float to bigint\", () => {\n builder = new ByteArrayBuilder(4);\n builder.add32BitIntToData(123456789.3, false);\n expect(builder.getErrors().length).toEqual(1);\n expect(builder.build()).toEqual(Uint8Array.from([]));\n });\n\n it(\"should serialize with an 5 byte body from an hexastring\", () => {\n builder.addHexaStringToData(\"0x8081828384\");\n expect(builder.build()).toEqual(COMMAND_BODY_HEXA1);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body from an hexastring without '0x'\", () => {\n builder.addHexaStringToData(\"85868788\");\n expect(builder.build()).toEqual(COMMAND_BODY_HEXA2);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body LV encoded from an hexastring\", () => {\n builder.encodeInLVFromHexa(\"0xA1A2A3\");\n expect(builder.build()).toEqual(COMMAND_BODY_LV_HEXA);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body LV encoded from an ascci string\", () => {\n builder.encodeInLVFromAscii(\"maman\");\n expect(builder.build()).toEqual(COMMAND_BODY_LV_ASCII);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body LV encoded from a buffer\", () => {\n const myarray = new Uint8Array([0xf0, 0xf1]);\n builder.encodeInLVFromBuffer(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_LV_ARRAY);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body LV encoded from a buffer\", () => {\n const myarray = new Uint8Array([0xf0, 0xf1]);\n builder.encodeInLVFromBuffer(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_LV_ARRAY);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from an hexastring\", () => {\n builder.encodeInTLVFromHexa(0x05, \"0xA1A2A3\");\n expect(builder.build()).toEqual(\n Uint8Array.from([0x05, 0x03, 0xa1, 0xa2, 0xa3]),\n );\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from a buffer\", () => {\n builder.encodeInTLVFromBuffer(\n 0x06,\n Uint8Array.from([0xa1, 0xa2, 0xa3, 0xa4]),\n );\n expect(builder.build()).toEqual(\n Uint8Array.from([0x06, 0x04, 0xa1, 0xa2, 0xa3, 0xa4]),\n );\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from an uint64\", () => {\n builder.encodeInTLVFromUInt64(0x06, 0x567890123456);\n expect(builder.build()).toEqual(\n Uint8Array.from([\n 0x06, 0x08, 0x00, 0x00, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56,\n ]),\n );\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an complete body of 0xAA\", () => {\n const myarray = new Uint8Array(255).fill(0xaa, 0, 255);\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getErrors()).toEqual([]);\n });\n });\n\n describe(\"mixed\", () => {\n beforeEach(() => {\n builder = new ByteArrayBuilder(APDU_MAX_PAYLOAD);\n });\n\n it(\"should serialize with all previous field\", () => {\n let available = APDU_MAX_PAYLOAD;\n builder.add8BitUIntToData(0x01);\n available--;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.add16BitUIntToData(0x3302);\n available -= 2;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.add32BitUIntToData(0x01234567);\n available -= 4;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.addHexaStringToData(\"0x8081828384\");\n available -= 5;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.addHexaStringToData(\"85868788\");\n available -= 4;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.encodeInLVFromHexa(\"0xA1A2A3\");\n available -= 4;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.encodeInLVFromAscii(\"maman\");\n available -= 6;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n const myarray = new Uint8Array([0xf0, 0xf1]);\n builder.encodeInLVFromBuffer(myarray);\n available -= 3;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n expect(builder.build()).toEqual(COMMAND_BODY_COMBINED);\n });\n });\n\n describe(\"error\", () => {\n beforeEach(() => {\n builder = new ByteArrayBuilder(APDU_MAX_PAYLOAD);\n });\n\n it.each([\n [2, false, true, 0x10000n],\n [2, true, true, 0x8000n],\n [2, true, true, -0x8001n],\n [4, false, true, 0x100000000n],\n [4, true, true, 0x80000000n],\n [4, true, true, -0x80000001n],\n [8, false, true, 0x10000000000000000n],\n [8, true, true, 0x8000000000000000n],\n [8, true, true, -0x8000000000000001n],\n ])(\n \"serialize the number overflowed: size %i, signed %s, bigEndian %s, value %i\",\n (sizeInBits, signed, bigEndian, input) => {\n builder = new ByteArrayBuilder(sizeInBits);\n builderAddNumber(input, bigEndian, sizeInBits, signed);\n expect(builder.getErrors().length).toEqual(1);\n expect(builder.build()).toEqual(Uint8Array.from([]));\n },\n );\n\n it(\"error due to a string not well coded\", () => {\n builder\n .addHexaStringToData(\":08081828384\")\n .addHexaStringToData(\"80818n8384\")\n .addHexaStringToData(\"808182838z\");\n\n expect(builder.build()).toEqual(COMMAND_NO_BODY);\n expect(builder.getAvailablePayloadLength()).toBe(APDU_MAX_PAYLOAD);\n expect(builder.getErrors()).toEqual([\n new HexaStringEncodeError(\":08081828384\"),\n new HexaStringEncodeError(\"80818n8384\"),\n new HexaStringEncodeError(\"808182838z\"),\n ]);\n });\n\n it(\"error due direct overflow\", () => {\n const myarray = new Uint8Array(256).fill(0xaa, 0, 256);\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_NO_BODY);\n expect(builder.getAvailablePayloadLength()).toBe(APDU_MAX_PAYLOAD);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError(myarray.toString()),\n ]);\n });\n\n it(\"error due to subsequent overflow with 1-byte array\", () => {\n const myarray = new Uint8Array(APDU_MAX_PAYLOAD).fill(\n 0xaa,\n 0,\n APDU_MAX_PAYLOAD,\n );\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n\n const mybuffer = new Uint8Array(1);\n mybuffer.set([0xff], 0);\n\n builder.addBufferToData(mybuffer);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError(mybuffer.toString()),\n ]);\n });\n\n it(\"error due to subsequent overflow with 1-char ascii\", () => {\n const myarray = new Uint8Array(APDU_MAX_PAYLOAD).fill(\n 0xaa,\n 0,\n APDU_MAX_PAYLOAD,\n );\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n\n const mystring = \"a\";\n\n builder.addAsciiStringToData(mystring);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError(new TextEncoder().encode(mystring).toString()),\n ]);\n });\n\n it(\"error due to subsequent overflow with 1-char hexastring\", () => {\n const myarray = new Uint8Array(APDU_MAX_PAYLOAD).fill(\n 0xaa,\n 0,\n APDU_MAX_PAYLOAD,\n );\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n\n const firstString = \"0xB4\";\n const secondString = \"e1\";\n\n builder\n .addHexaStringToData(firstString)\n .addHexaStringToData(secondString);\n\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError((0xb4).toString()),\n new DataOverflowError((0xe1).toString()),\n ]);\n });\n\n it(\"error due to empty values\", () => {\n const mystring = \"\";\n\n builder.addHexaStringToData(mystring).encodeInLVFromHexa(mystring);\n\n expect(builder.build()).toEqual(COMMAND_NO_BODY);\n expect(builder.getAvailablePayloadLength()).toBe(APDU_MAX_PAYLOAD);\n expect(builder.getErrors()).toEqual([\n new HexaStringEncodeError(mystring),\n new HexaStringEncodeError(mystring),\n ]);\n });\n\n it(\"error due to subsequent overflow with 1-char LV\", () => {\n const myarray = new Uint8Array(APDU_MAX_PAYLOAD - 1).fill(\n 0xaa,\n 0,\n APDU_MAX_PAYLOAD - 1,\n );\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_NEARLY);\n expect(builder.getAvailablePayloadLength()).toBe(1);\n\n const firstString = \"n\";\n const secondString = \"e1\";\n const mybuffer = new Uint8Array(1);\n mybuffer.set([0xff], 0);\n\n builder\n .encodeInLVFromAscii(firstString)\n .encodeInLVFromHexa(secondString)\n .encodeInLVFromBuffer(mybuffer);\n\n expect(builder.build()).toEqual(COMMAND_BODY_NEARLY);\n expect(builder.getAvailablePayloadLength()).toBe(1);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError(firstString),\n new DataOverflowError(secondString),\n new DataOverflowError(mybuffer.toString()),\n ]);\n });\n });\n});\n"],
5
- "mappings": "AAAA,OAAS,sBAAAA,MAA0B,wBAEnC,OAAS,oBAAAC,MAAwB,gBACjC,OAAS,qBAAAC,EAAmB,yBAAAC,MAA6B,oBACzD,OAAS,oBAAAC,MAAwB,qBAEjC,MAAMC,EAAkB,IAAI,WAAW,CAAC,CAAC,EAEnCC,EAAsB,IAAI,WAAW,CAAC,CAAI,CAAC,EAE3CC,EAAqB,IAAI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,CACH,CAAC",
4
+ "sourcesContent": ["import { hexaStringToBuffer } from \"@api/utils/HexaString\";\n\nimport { APDU_MAX_PAYLOAD } from \"./ApduBuilder\";\nimport { DataOverflowError, HexaStringEncodeError } from \"./AppBuilderError\";\nimport { ByteArrayBuilder } from \"./ByteArrayBuilder\";\n\nconst COMMAND_NO_BODY = new Uint8Array([]);\n\nconst COMMAND_BODY_SINGLE = new Uint8Array([0x01]);\n\nconst COMMAND_BODY_HEXA1 = new Uint8Array([0x80, 0x81, 0x82, 0x83, 0x84]);\n\nconst COMMAND_BODY_HEXA2 = new Uint8Array([0x85, 0x86, 0x87, 0x88]);\n\nconst COMMAND_BODY_LV_HEXA = new Uint8Array([0x03, 0xa1, 0xa2, 0xa3]);\n\nconst COMMAND_BODY_LV_ASCII = new Uint8Array([\n 0x05, 0x6d, 0x61, 0x6d, 0x61, 0x6e,\n]);\n\nconst COMMAND_BODY_LV_ARRAY = new Uint8Array([0x02, 0xf0, 0xf1]);\n\nconst COMMAND_BODY_COMBINED = new Uint8Array([\n 0x01, 0x33, 0x02, 0x01, 0x23, 0x45, 0x67, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85,\n 0x86, 0x87, 0x88, 0x03, 0xa1, 0xa2, 0xa3, 0x05, 0x6d, 0x61, 0x6d, 0x61, 0x6e,\n 0x02, 0xf0, 0xf1,\n]);\n\nconst COMMAND_BODY_MAX = new Uint8Array([...Array<number>(255).fill(0xaa)]);\n\nconst COMMAND_BODY_NEARLY = new Uint8Array([...Array<number>(254).fill(0xaa)]);\n\nlet builder: ByteArrayBuilder;\n\ndescribe(\"ByteArrayBuilder\", () => {\n const builderAddNumber = (\n num: number | bigint,\n bigEndian: boolean,\n sizeInBits: number,\n signed: boolean,\n ) => {\n if (signed) {\n switch (sizeInBits) {\n case 2:\n builder.add16BitIntToData(num, bigEndian);\n break;\n case 4:\n builder.add32BitIntToData(num, bigEndian);\n break;\n case 8:\n builder.add64BitIntToData(num, bigEndian);\n break;\n case 16:\n builder.add128BitIntToData(num, bigEndian);\n break;\n case 32:\n builder.add256BitIntToData(num, bigEndian);\n break;\n }\n } else {\n switch (sizeInBits) {\n case 2:\n builder.add16BitUIntToData(num, bigEndian);\n break;\n case 4:\n builder.add32BitUIntToData(num, bigEndian);\n break;\n case 8:\n builder.add64BitUIntToData(num, bigEndian);\n break;\n case 16:\n builder.add128BitUIntToData(num, bigEndian);\n break;\n case 32:\n builder.add256BitUIntToData(num, bigEndian);\n break;\n }\n }\n };\n\n describe(\"clean\", () => {\n beforeEach(() => {\n builder = new ByteArrayBuilder(APDU_MAX_PAYLOAD);\n });\n\n it(\"should create an instance\", () => {\n expect(builder).toBeDefined();\n expect(builder).toBeInstanceOf(ByteArrayBuilder);\n });\n });\n\n describe(\"simple\", () => {\n beforeEach(() => {\n builder = new ByteArrayBuilder(APDU_MAX_PAYLOAD);\n });\n\n it(\"should serialize with an empty body\", () => {\n expect(builder.build()).toEqual(COMMAND_NO_BODY);\n });\n\n it(\"should serialize with an single byte body\", () => {\n builder = new ByteArrayBuilder(1);\n builder.add8BitUIntToData(0x01);\n expect(builder.build()).toEqual(COMMAND_BODY_SINGLE);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it.each([\n [2, false, true, 0x3302, \"3302\"],\n [2, false, false, 0x3302n, \"0233\"],\n [2, true, true, 4200n, \"1068\"],\n [2, true, true, -4200n, \"ef98\"],\n [2, true, false, 4200, \"6810\"],\n [2, true, false, -4200, \"98ef\"],\n [4, false, true, 0x01234567n, \"01234567\"],\n [4, false, false, 0x01234567n, \"67452301\"],\n [4, true, true, 123456789, \"075bcd15\"],\n [4, true, true, -123456789, \"f8a432eb\"],\n [4, true, false, 123456789, \"15cd5b07\"],\n [4, true, false, -123456789, \"eb32a4f8\"],\n [8, false, true, 14147778004927559n, \"0032435442584447\"],\n [8, false, false, 14147778004927559n, \"4744584254433200\"],\n [8, true, true, 14147778004927559n, \"0032435442584447\"],\n [8, true, true, -14147778004927559n, \"ffcdbcabbda7bbb9\"],\n [8, true, false, 14147778004927559n, \"4744584254433200\"],\n [8, true, false, -14147778004927559n, \"b9bba7bdabbccdff\"],\n [\n 16,\n false,\n true,\n 0x00324354425844470032435442584447n,\n \"00324354425844470032435442584447\",\n ],\n [\n 16,\n false,\n false,\n 0x00324354425844470032435442584447n,\n \"47445842544332004744584254433200\",\n ],\n [\n 16,\n true,\n true,\n 0x00324354425844470032435442584447n,\n \"00324354425844470032435442584447\",\n ],\n [\n 16,\n true,\n true,\n -0x00324354425844470032435442584447n,\n \"ffcdbcabbda7bbb8ffcdbcabbda7bbb9\",\n ],\n [\n 16,\n true,\n false,\n 0x00324354425844470032435442584447n,\n \"47445842544332004744584254433200\",\n ],\n [\n 16,\n true,\n false,\n -0x00324354425844470032435442584447n,\n \"b9bba7bdabbccdffb8bba7bdabbccdff\",\n ],\n [\n 32,\n false,\n true,\n 0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"0032435442584447003243544258444700324354425844470032435442584447\",\n ],\n [\n 32,\n false,\n false,\n 0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"4744584254433200474458425443320047445842544332004744584254433200\",\n ],\n [\n 32,\n true,\n true,\n 0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"0032435442584447003243544258444700324354425844470032435442584447\",\n ],\n [\n 32,\n true,\n true,\n -0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"ffcdbcabbda7bbb8ffcdbcabbda7bbb8ffcdbcabbda7bbb8ffcdbcabbda7bbb9\",\n ],\n [\n 32,\n true,\n false,\n 0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"4744584254433200474458425443320047445842544332004744584254433200\",\n ],\n [\n 32,\n true,\n false,\n -0x0032435442584447003243544258444700324354425844470032435442584447n,\n \"b9bba7bdabbccdffb8bba7bdabbccdffb8bba7bdabbccdffb8bba7bdabbccdff\",\n ],\n ])(\n \"serialize the following number: size %i, signed %s, bigEndian %s, value %i, expected %s\",\n (sizeInBits, signed, bigEndian, input, output) => {\n builder = new ByteArrayBuilder(sizeInBits);\n builderAddNumber(input, bigEndian, sizeInBits, signed);\n expect(builder.build()).toEqual(hexaStringToBuffer(output));\n expect(builder.getErrors()).toEqual([]);\n\n // Retry with a buffer too small\n builder = new ByteArrayBuilder(sizeInBits - 1);\n builderAddNumber(input, bigEndian, sizeInBits, signed);\n expect(builder.getErrors().length).toEqual(1);\n expect(builder.build()).toEqual(Uint8Array.from([]));\n },\n );\n\n it.each([\n [2, false, true, 0xffffn, \"ffff\"],\n [2, true, true, 0x7fffn, \"7fff\"],\n [2, true, true, -0x8000n, \"8000\"],\n [4, false, true, 0xffffffffn, \"ffffffff\"],\n [4, true, true, 0x7fffffffn, \"7fffffff\"],\n [4, true, true, -0x80000000n, \"80000000\"],\n [8, false, true, 0xffffffffffffffffn, \"ffffffffffffffff\"],\n [8, true, true, 0x7fffffffffffffffn, \"7fffffffffffffff\"],\n [8, true, true, -0x8000000000000000n, \"8000000000000000\"],\n [\n 16,\n false,\n true,\n 0xffffffffffffffffffffffffffffffffn,\n \"ffffffffffffffffffffffffffffffff\",\n ],\n [\n 16,\n true,\n true,\n 0x7fffffffffffffffffffffffffffffffn,\n \"7fffffffffffffffffffffffffffffff\",\n ],\n [\n 16,\n true,\n true,\n -0x80000000000000000000000000000000n,\n \"80000000000000000000000000000000\",\n ],\n [\n 32,\n false,\n true,\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,\n \"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\",\n ],\n [\n 32,\n true,\n true,\n 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,\n \"7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\",\n ],\n [\n 32,\n true,\n true,\n -0x8000000000000000000000000000000000000000000000000000000000000000n,\n \"8000000000000000000000000000000000000000000000000000000000000000\",\n ],\n ])(\n \"serialize the number to the limit: size %i, signed %s, bigEndian %s, value %i, expected %s\",\n (sizeInBits, signed, bigEndian, input, output) => {\n builder = new ByteArrayBuilder(sizeInBits);\n builderAddNumber(input, bigEndian, sizeInBits, signed);\n expect(builder.build()).toEqual(hexaStringToBuffer(output));\n expect(builder.getErrors()).toEqual([]);\n },\n );\n\n it(\"Serialize from float to bigint\", () => {\n builder = new ByteArrayBuilder(4);\n builder.add32BitIntToData(123456789.3, false);\n expect(builder.getErrors().length).toEqual(1);\n expect(builder.build()).toEqual(Uint8Array.from([]));\n });\n\n it(\"should serialize with an 5 byte body from an hexastring\", () => {\n builder.addHexaStringToData(\"0x8081828384\");\n expect(builder.build()).toEqual(COMMAND_BODY_HEXA1);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body from an hexastring without '0x'\", () => {\n builder.addHexaStringToData(\"85868788\");\n expect(builder.build()).toEqual(COMMAND_BODY_HEXA2);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body LV encoded from an hexastring\", () => {\n builder.encodeInLVFromHexa(\"0xA1A2A3\");\n expect(builder.build()).toEqual(COMMAND_BODY_LV_HEXA);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body LV encoded from an ascci string\", () => {\n builder.encodeInLVFromAscii(\"maman\");\n expect(builder.build()).toEqual(COMMAND_BODY_LV_ASCII);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body LV encoded from a buffer\", () => {\n const myarray = new Uint8Array([0xf0, 0xf1]);\n builder.encodeInLVFromBuffer(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_LV_ARRAY);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an 4 byte body LV encoded from a buffer\", () => {\n const myarray = new Uint8Array([0xf0, 0xf1]);\n builder.encodeInLVFromBuffer(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_LV_ARRAY);\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from an ascii string\", () => {\n builder.encodeInTLVFromAscii(0x05, \"coucou\");\n expect(builder.build()).toEqual(\n Uint8Array.from([0x05, 0x06, 0x63, 0x6f, 0x75, 0x63, 0x6f, 0x75]),\n );\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from an hexastring\", () => {\n builder.encodeInTLVFromHexa(0x05, \"0xA1A2A3\");\n expect(builder.build()).toEqual(\n Uint8Array.from([0x05, 0x03, 0xa1, 0xa2, 0xa3]),\n );\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from a buffer\", () => {\n builder.encodeInTLVFromBuffer(\n 0x06,\n Uint8Array.from([0xa1, 0xa2, 0xa3, 0xa4]),\n );\n expect(builder.build()).toEqual(\n Uint8Array.from([0x06, 0x04, 0xa1, 0xa2, 0xa3, 0xa4]),\n );\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from an uint8\", () => {\n builder.encodeInTLVFromUInt8(0x06, 0x56);\n expect(builder.build()).toEqual(Uint8Array.from([0x06, 0x01, 0x56]));\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from an uint16\", () => {\n builder.encodeInTLVFromUInt16(0x06, 0x3456);\n expect(builder.build()).toEqual(\n Uint8Array.from([0x06, 0x02, 0x34, 0x56]),\n );\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from an uint32\", () => {\n builder.encodeInTLVFromUInt32(0x06, 0x90123456);\n expect(builder.build()).toEqual(\n Uint8Array.from([0x06, 0x04, 0x90, 0x12, 0x34, 0x56]),\n );\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an TLV encoded from an uint64\", () => {\n builder.encodeInTLVFromUInt64(0x06, 0x567890123456);\n expect(builder.build()).toEqual(\n Uint8Array.from([\n 0x06, 0x08, 0x00, 0x00, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56,\n ]),\n );\n expect(builder.getErrors()).toEqual([]);\n });\n\n it(\"should serialize with an complete body of 0xAA\", () => {\n const myarray = new Uint8Array(255).fill(0xaa, 0, 255);\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getErrors()).toEqual([]);\n });\n });\n\n describe(\"mixed\", () => {\n beforeEach(() => {\n builder = new ByteArrayBuilder(APDU_MAX_PAYLOAD);\n });\n\n it(\"should serialize with all previous field\", () => {\n let available = APDU_MAX_PAYLOAD;\n builder.add8BitUIntToData(0x01);\n available--;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.add16BitUIntToData(0x3302);\n available -= 2;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.add32BitUIntToData(0x01234567);\n available -= 4;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.addHexaStringToData(\"0x8081828384\");\n available -= 5;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.addHexaStringToData(\"85868788\");\n available -= 4;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.encodeInLVFromHexa(\"0xA1A2A3\");\n available -= 4;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n builder.encodeInLVFromAscii(\"maman\");\n available -= 6;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n const myarray = new Uint8Array([0xf0, 0xf1]);\n builder.encodeInLVFromBuffer(myarray);\n available -= 3;\n expect(builder.getAvailablePayloadLength()).toBe(available);\n\n expect(builder.build()).toEqual(COMMAND_BODY_COMBINED);\n });\n });\n\n describe(\"error\", () => {\n beforeEach(() => {\n builder = new ByteArrayBuilder(APDU_MAX_PAYLOAD);\n });\n\n it.each([\n [2, false, true, 0x10000n],\n [2, true, true, 0x8000n],\n [2, true, true, -0x8001n],\n [4, false, true, 0x100000000n],\n [4, true, true, 0x80000000n],\n [4, true, true, -0x80000001n],\n [8, false, true, 0x10000000000000000n],\n [8, true, true, 0x8000000000000000n],\n [8, true, true, -0x8000000000000001n],\n ])(\n \"serialize the number overflowed: size %i, signed %s, bigEndian %s, value %i\",\n (sizeInBits, signed, bigEndian, input) => {\n builder = new ByteArrayBuilder(sizeInBits);\n builderAddNumber(input, bigEndian, sizeInBits, signed);\n expect(builder.getErrors().length).toEqual(1);\n expect(builder.build()).toEqual(Uint8Array.from([]));\n },\n );\n\n it(\"error due to a string not well coded\", () => {\n builder\n .addHexaStringToData(\":08081828384\")\n .addHexaStringToData(\"80818n8384\")\n .addHexaStringToData(\"808182838z\");\n\n expect(builder.build()).toEqual(COMMAND_NO_BODY);\n expect(builder.getAvailablePayloadLength()).toBe(APDU_MAX_PAYLOAD);\n expect(builder.getErrors()).toEqual([\n new HexaStringEncodeError(\":08081828384\"),\n new HexaStringEncodeError(\"80818n8384\"),\n new HexaStringEncodeError(\"808182838z\"),\n ]);\n });\n\n it(\"error due direct overflow\", () => {\n const myarray = new Uint8Array(256).fill(0xaa, 0, 256);\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_NO_BODY);\n expect(builder.getAvailablePayloadLength()).toBe(APDU_MAX_PAYLOAD);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError(myarray.toString()),\n ]);\n });\n\n it(\"error due to subsequent overflow with 1-byte array\", () => {\n const myarray = new Uint8Array(APDU_MAX_PAYLOAD).fill(\n 0xaa,\n 0,\n APDU_MAX_PAYLOAD,\n );\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n\n const mybuffer = new Uint8Array(1);\n mybuffer.set([0xff], 0);\n\n builder.addBufferToData(mybuffer);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError(mybuffer.toString()),\n ]);\n });\n\n it(\"error due to subsequent overflow with 1-char ascii\", () => {\n const myarray = new Uint8Array(APDU_MAX_PAYLOAD).fill(\n 0xaa,\n 0,\n APDU_MAX_PAYLOAD,\n );\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n\n const mystring = \"a\";\n\n builder.addAsciiStringToData(mystring);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError(new TextEncoder().encode(mystring).toString()),\n ]);\n });\n\n it(\"error due to subsequent overflow with 1-char hexastring\", () => {\n const myarray = new Uint8Array(APDU_MAX_PAYLOAD).fill(\n 0xaa,\n 0,\n APDU_MAX_PAYLOAD,\n );\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n\n const firstString = \"0xB4\";\n const secondString = \"e1\";\n\n builder\n .addHexaStringToData(firstString)\n .addHexaStringToData(secondString);\n\n expect(builder.build()).toEqual(COMMAND_BODY_MAX);\n expect(builder.getAvailablePayloadLength()).toBe(0);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError((0xb4).toString()),\n new DataOverflowError((0xe1).toString()),\n ]);\n });\n\n it(\"error due to empty values\", () => {\n const mystring = \"\";\n\n builder.addHexaStringToData(mystring).encodeInLVFromHexa(mystring);\n\n expect(builder.build()).toEqual(COMMAND_NO_BODY);\n expect(builder.getAvailablePayloadLength()).toBe(APDU_MAX_PAYLOAD);\n expect(builder.getErrors()).toEqual([\n new HexaStringEncodeError(mystring),\n new HexaStringEncodeError(mystring),\n ]);\n });\n\n it(\"error due to subsequent overflow with 1-char LV\", () => {\n const myarray = new Uint8Array(APDU_MAX_PAYLOAD - 1).fill(\n 0xaa,\n 0,\n APDU_MAX_PAYLOAD - 1,\n );\n builder.addBufferToData(myarray);\n expect(builder.build()).toEqual(COMMAND_BODY_NEARLY);\n expect(builder.getAvailablePayloadLength()).toBe(1);\n\n const firstString = \"n\";\n const secondString = \"e1\";\n const mybuffer = new Uint8Array(1);\n mybuffer.set([0xff], 0);\n\n builder\n .encodeInLVFromAscii(firstString)\n .encodeInLVFromHexa(secondString)\n .encodeInLVFromBuffer(mybuffer);\n\n expect(builder.build()).toEqual(COMMAND_BODY_NEARLY);\n expect(builder.getAvailablePayloadLength()).toBe(1);\n expect(builder.getErrors()).toEqual([\n new DataOverflowError(firstString),\n new DataOverflowError(secondString),\n new DataOverflowError(mybuffer.toString()),\n ]);\n });\n });\n});\n"],
5
+ "mappings": "AAAA,OAAS,sBAAAA,MAA0B,wBAEnC,OAAS,oBAAAC,MAAwB,gBACjC,OAAS,qBAAAC,EAAmB,yBAAAC,MAA6B,oBACzD,OAAS,oBAAAC,MAAwB,qBAEjC,MAAMC,EAAkB,IAAI,WAAW,CAAC,CAAC,EAEnCC,EAAsB,IAAI,WAAW,CAAC,CAAI,CAAC,EAE3CC,EAAqB,IAAI,WAAW,CAAC,IAAM,IAAM,IAAM,IAAM,GAAI,CAAC,EAElEC,EAAqB,IAAI,WAAW,CAAC,IAAM,IAAM,IAAM,GAAI,CAAC,EAE5DC,EAAuB,IAAI,WAAW,CAAC,EAAM,IAAM,IAAM,GAAI,CAAC,EAE9DC,EAAwB,IAAI,WAAW,CAC3C,EAAM,IAAM,GAAM,IAAM,GAAM,GAChC,CAAC,EAEKC,EAAwB,IAAI,WAAW,CAAC,EAAM,IAAM,GAAI,CAAC,EAEzDC,EAAwB,IAAI,WAAW,CAC3C,EAAM,GAAM,EAAM,EAAM,GAAM,GAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IAAM,IACxE,IAAM,IAAM,IAAM,EAAM,IAAM,IAAM,IAAM,EAAM,IAAM,GAAM,IAAM,GAAM,IACxE,EAAM,IAAM,GACd,CAAC,EAEKC,EAAmB,IAAI,WAAW,CAAC,GAAG,MAAc,GAAG,EAAE,KAAK,GAAI,CAAC,CAAC,EAEpEC,EAAsB,IAAI,WAAW,CAAC,GAAG,MAAc,GAAG,EAAE,KAAK,GAAI,CAAC,CAAC,EAE7E,IAAIC,EAEJ,SAAS,mBAAoB,IAAM,CACjC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EAAQ,0BAA0B,CAAC,EAAE,KAAK,CAAC,EAClD,OAAOA,EAAQ,UAAU,CAAC,EAAE,QAAQ,CAClC,IAAIb,EAAkByB,CAAW,EACjC,IAAIzB,EAAkB0B,CAAY,EAClC,IAAI1B,EAAkBuB,EAAS,SAAS,CAAC,CAC3C,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
6
6
  "names": ["hexaStringToBuffer", "APDU_MAX_PAYLOAD", "DataOverflowError", "HexaStringEncodeError", "ByteArrayBuilder", "COMMAND_NO_BODY", "COMMAND_BODY_SINGLE", "COMMAND_BODY_HEXA1", "COMMAND_BODY_HEXA2", "COMMAND_BODY_LV_HEXA", "COMMAND_BODY_LV_ASCII", "COMMAND_BODY_LV_ARRAY", "COMMAND_BODY_COMBINED", "COMMAND_BODY_MAX", "COMMAND_BODY_NEARLY", "builder", "builderAddNumber", "num", "bigEndian", "sizeInBits", "signed", "input", "output", "myarray", "available", "mybuffer", "mystring", "firstString", "secondString"]
7
7
  }
@@ -1,2 +1,2 @@
1
- var t=(e=>(e.NANO_S="nanoS",e.NANO_SP="nanoSP",e.NANO_X="nanoX",e.STAX="stax",e.FLEX="flex",e.APEX="apex",e))(t||{});class i{id;model;name;constructor({id:n,model:o,name:r}){this.id=n,this.model=o,this.name=r}}const l=11415;export{i as DeviceModel,t as DeviceModelId,l as LEDGER_VENDOR_ID};
1
+ var t=(e=>(e.NANO_S="nanoS",e.NANO_SP="nanoSP",e.NANO_X="nanoX",e.STAX="stax",e.FLEX="flex",e.APEX="apexp",e))(t||{});class i{id;model;name;constructor({id:n,model:o,name:r}){this.id=n,this.model=o,this.name=r}}const l=11415;export{i as DeviceModel,t as DeviceModelId,l as LEDGER_VENDOR_ID};
2
2
  //# sourceMappingURL=DeviceModel.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/api/device/DeviceModel.ts"],
4
- "sourcesContent": ["export enum DeviceModelId {\n NANO_S = \"nanoS\",\n NANO_SP = \"nanoSP\",\n NANO_X = \"nanoX\",\n STAX = \"stax\",\n FLEX = \"flex\",\n APEX = \"apex\",\n}\n\n/**\n * Unique identifier for a device.\n *\n * NB: This identifier is generated at runtime and is not persisted. It cannot\n * be used to identify a device across sessions.\n * There is in fact no way to identify a device across sessions, which is a\n * privacy feature of Ledger devices.\n */\nexport type DeviceId = string;\n\nexport type DeviceModelArgs = {\n readonly id: DeviceId;\n readonly model: DeviceModelId;\n readonly name: string;\n};\n\nexport class DeviceModel {\n public readonly id: DeviceId;\n public readonly model: DeviceModelId;\n public readonly name: string;\n\n constructor({ id, model, name }: DeviceModelArgs) {\n this.id = id;\n this.model = model;\n this.name = name;\n }\n}\n\nexport const LEDGER_VENDOR_ID = 0x2c97;\n"],
5
- "mappings": "AAAO,IAAKA,OACVA,EAAA,OAAS,QACTA,EAAA,QAAU,SACVA,EAAA,OAAS,QACTA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,KAAO,OANGA,OAAA,IAyBL,MAAMC,CAAY,CACP,GACA,MACA,KAEhB,YAAY,CAAE,GAAAC,EAAI,MAAAC,EAAO,KAAAC,CAAK,EAAoB,CAChD,KAAK,GAAKF,EACV,KAAK,MAAQC,EACb,KAAK,KAAOC,CACd,CACF,CAEO,MAAMC,EAAmB",
4
+ "sourcesContent": ["export enum DeviceModelId {\n NANO_S = \"nanoS\",\n NANO_SP = \"nanoSP\",\n NANO_X = \"nanoX\",\n STAX = \"stax\",\n FLEX = \"flex\",\n APEX = \"apexp\",\n}\n\n/**\n * Unique identifier for a device.\n *\n * NB: This identifier is generated at runtime and is not persisted. It cannot\n * be used to identify a device across sessions.\n * There is in fact no way to identify a device across sessions, which is a\n * privacy feature of Ledger devices.\n */\nexport type DeviceId = string;\n\nexport type DeviceModelArgs = {\n readonly id: DeviceId;\n readonly model: DeviceModelId;\n readonly name: string;\n};\n\nexport class DeviceModel {\n public readonly id: DeviceId;\n public readonly model: DeviceModelId;\n public readonly name: string;\n\n constructor({ id, model, name }: DeviceModelArgs) {\n this.id = id;\n this.model = model;\n this.name = name;\n }\n}\n\nexport const LEDGER_VENDOR_ID = 0x2c97;\n"],
5
+ "mappings": "AAAO,IAAKA,OACVA,EAAA,OAAS,QACTA,EAAA,QAAU,SACVA,EAAA,OAAS,QACTA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,KAAO,QANGA,OAAA,IAyBL,MAAMC,CAAY,CACP,GACA,MACA,KAEhB,YAAY,CAAE,GAAAC,EAAI,MAAAC,EAAO,KAAAC,CAAK,EAAoB,CAChD,KAAK,GAAKF,EACV,KAAK,MAAQC,EACb,KAAK,KAAOC,CACd,CACF,CAEO,MAAMC,EAAmB",
6
6
  "names": ["DeviceModelId", "DeviceModel", "id", "model", "name", "LEDGER_VENDOR_ID"]
7
7
  }
@@ -1,2 +1,2 @@
1
- var p=(o=>(o.None="none",o.UnlockDevice="unlock-device",o.AllowSecureConnection="allow-secure-connection",o.ConfirmOpenApp="confirm-open-app",o.SignTransaction="sign-transaction",o.SignTypedData="sign-typed-data",o.AllowListApps="allow-list-apps",o.VerifyAddress="verify-address",o.SignPersonalMessage="sign-personal-message",o.SignDelegationAuthorization="sign-delegation-authorization",o.Web3ChecksOptIn="web3-checks-opt-in",o))(p||{});export{p as UserInteractionRequired};
1
+ var s=(p=>(p.None="none",p.UnlockDevice="unlock-device",p.AllowSecureConnection="allow-secure-connection",p.ConfirmOpenApp="confirm-open-app",p.SignTransaction="sign-transaction",p.SignTypedData="sign-typed-data",p.AllowListApps="allow-list-apps",p.VerifyAddress="verify-address",p.SignPersonalMessage="sign-personal-message",p.SignDelegationAuthorization="sign-delegation-authorization",p.Web3ChecksOptIn="web3-checks-opt-in",p.VerifySafeAddress="verify-safe-address",p))(s||{});export{s as UserInteractionRequired};
2
2
  //# sourceMappingURL=UserInteractionRequired.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/api/device-action/model/UserInteractionRequired.ts"],
4
- "sourcesContent": ["/**\n * The user interaction required on the device to move further in a device action.\n * This is used to inform the users about the action they need to take on the device.\n */\nexport enum UserInteractionRequired {\n None = \"none\",\n UnlockDevice = \"unlock-device\",\n AllowSecureConnection = \"allow-secure-connection\",\n ConfirmOpenApp = \"confirm-open-app\",\n SignTransaction = \"sign-transaction\",\n SignTypedData = \"sign-typed-data\",\n AllowListApps = \"allow-list-apps\",\n VerifyAddress = \"verify-address\",\n SignPersonalMessage = \"sign-personal-message\",\n SignDelegationAuthorization = \"sign-delegation-authorization\",\n Web3ChecksOptIn = \"web3-checks-opt-in\",\n}\n"],
5
- "mappings": "AAIO,IAAKA,OACVA,EAAA,KAAO,OACPA,EAAA,aAAe,gBACfA,EAAA,sBAAwB,0BACxBA,EAAA,eAAiB,mBACjBA,EAAA,gBAAkB,mBAClBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,iBAChBA,EAAA,oBAAsB,wBACtBA,EAAA,4BAA8B,gCAC9BA,EAAA,gBAAkB,qBAXRA,OAAA",
4
+ "sourcesContent": ["/**\n * The user interaction required on the device to move further in a device action.\n * This is used to inform the users about the action they need to take on the device.\n */\nexport enum UserInteractionRequired {\n None = \"none\",\n UnlockDevice = \"unlock-device\",\n AllowSecureConnection = \"allow-secure-connection\",\n ConfirmOpenApp = \"confirm-open-app\",\n SignTransaction = \"sign-transaction\",\n SignTypedData = \"sign-typed-data\",\n AllowListApps = \"allow-list-apps\",\n VerifyAddress = \"verify-address\",\n SignPersonalMessage = \"sign-personal-message\",\n SignDelegationAuthorization = \"sign-delegation-authorization\",\n Web3ChecksOptIn = \"web3-checks-opt-in\",\n VerifySafeAddress = \"verify-safe-address\",\n}\n"],
5
+ "mappings": "AAIO,IAAKA,OACVA,EAAA,KAAO,OACPA,EAAA,aAAe,gBACfA,EAAA,sBAAwB,0BACxBA,EAAA,eAAiB,mBACjBA,EAAA,gBAAkB,mBAClBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,kBAChBA,EAAA,cAAgB,iBAChBA,EAAA,oBAAsB,wBACtBA,EAAA,4BAA8B,gCAC9BA,EAAA,gBAAkB,qBAClBA,EAAA,kBAAoB,sBAZVA,OAAA",
6
6
  "names": ["UserInteractionRequired"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{Left as A,Right as m}from"purify-ts";import{Observable as y}from"rxjs";import{tap as g,timeout as k}from"rxjs/operators";import{assign as n,fromObservable as f,fromPromise as b,setup as E}from"xstate";import{isSuccessCommandResult as h}from"../../../command/model/CommandResult";import{GetAppAndVersionCommand as V}from"../../../command/os/GetAppAndVersionCommand";import{DeviceStatus as D}from"../../../device/DeviceStatus";import{UserInteractionRequired as c}from"../../../device-action/model/UserInteractionRequired";import{DEFAULT_UNLOCK_TIMEOUT_MS as U}from"../../../device-action/os/Const";import{DeviceLockedError as G,DeviceNotOnboardedError as x}from"../../../device-action/os/Errors";import{XStateDeviceAction as O}from"../../../device-action/xstate-utils/XStateDeviceAction";import{DeviceSessionStateType as l}from"../../../device-session/DeviceSessionState";class B extends O{makeStateMachine(r){const{getAppAndVersion:d,getDeviceSessionState:u,setDeviceSessionState:i,waitForDeviceUnlock:p,isDeviceOnboarded:o}=this.extractDependencies(r),a=this.input.unlockTimeout??U;return E({types:{input:{unlockTimeout:a},context:{},output:{}},actors:{getAppAndVersion:b(d),waitForDeviceUnlock:f(p)},guards:{isDeviceOnboarded:()=>o(),isDeviceLocked:({context:e})=>e._internalState.locked,hasError:({context:e})=>e._internalState.error!==null},actions:{assignErrorDeviceNotOnboarded:n({_internalState:e=>({...e.context._internalState,error:new x})}),assignErrorDeviceLocked:n({_internalState:e=>({...e.context._internalState,error:new G}),intermediateValue:{requiredUserInteraction:c.UnlockDevice}}),assignErrorFromEvent:n({_internalState:e=>({...e.context._internalState,error:e.event.error})}),assignNoUserActionNeeded:n({intermediateValue:e=>({...e.context.intermediateValue,requiredUserInteraction:c.None})}),assignUserActionUnlockNeeded:n({intermediateValue:e=>({...e.context.intermediateValue,requiredUserInteraction:c.UnlockDevice})})}}).createMachine({id:"GetDeviceStatusDeviceAction",initial:"DeviceReady",context:e=>{const t=u(),{sessionStateType:s}=t;return{input:{unlockTimeout:e.input.unlockTimeout},intermediateValue:{requiredUserInteraction:c.None},_internalState:{onboarded:!1,locked:!1,currentApp:s===l.ReadyWithoutSecureChannel?t.currentApp.name:null,currentAppVersion:null,error:null}}},states:{DeviceReady:{always:{target:"OnboardingCheck"}},OnboardingCheck:{always:[{guard:{type:"isDeviceOnboarded"},target:"AppAndVersionCheck",actions:n({_internalState:e=>({...e.context._internalState,onboarded:!0})})},{target:"Error",actions:"assignErrorDeviceNotOnboarded"}]},UserActionUnlockDevice:{entry:"assignUserActionUnlockNeeded",exit:"assignNoUserActionNeeded",invoke:{id:"UserActionUnlockDevice",src:"waitForDeviceUnlock",input:e=>({unlockTimeout:a}),onDone:{target:"AppAndVersionCheck",actions:n({_internalState:e=>({...e.context._internalState,locked:!1})})},onError:{target:"Error",actions:"assignErrorDeviceLocked"}}},AppAndVersionCheck:{invoke:{src:"getAppAndVersion",onDone:{target:"ApplicationAvailableResultCheck",actions:n({_internalState:e=>{if(h(e.event.output)){const t=u();return t.sessionStateType!==l.Connected?i({...t,currentApp:e.event.output.data}):i({deviceModelId:t.deviceModelId,sessionStateType:l.ReadyWithoutSecureChannel,deviceStatus:D.CONNECTED,currentApp:e.event.output.data,installedApps:[],isSecureConnectionAllowed:!1}),{...e.context._internalState,locked:!1,currentApp:e.event.output.data.name,currentAppVersion:e.event.output.data.version}}if("errorCode"in e.event.output.error){if(e.event.output.error.errorCode==="5515")return{...e.context._internalState,locked:!0};if(e.event.output.error.errorCode==="6e00")return{...e.context._internalState,locked:!1,currentApp:"BOLOS",currentAppVersion:"0.0.0"}}return{...e.context._internalState,error:e.event.output.error}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ApplicationAvailableResultCheck:{always:[{guard:"hasError",target:"Error"},{target:"UserActionUnlockDevice",guard:"isDeviceLocked"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:e=>{const{context:t}=e,{error:s,currentApp:S,currentAppVersion:v}=t._internalState;return s?A(s):m({currentApp:S,currentAppVersion:v})}})}extractDependencies(r){return{getAppAndVersion:()=>r.sendCommand(new V),waitForDeviceUnlock:({input:i})=>new y(p=>{const o=r.getDeviceSessionStateObservable().pipe(g(a=>{a.deviceStatus===D.CONNECTED&&(p.complete(),o.unsubscribe())})).subscribe();return()=>{o.unsubscribe()}}).pipe(k(i.unlockTimeout)),getDeviceSessionState:()=>r.getDeviceSessionState(),setDeviceSessionState:i=>r.setDeviceSessionState(i),isDeviceOnboarded:()=>!0}}}export{B as GetDeviceStatusDeviceAction};
1
+ import{Left as m,Right as y}from"purify-ts";import{EMPTY as k,from as g,interval as f,mergeMap as h,of as E,switchMap as V,take as U}from"rxjs";import{timeout as G}from"rxjs/operators";import{assign as r,fromObservable as b,fromPromise as x,setup as C}from"xstate";import{isSuccessCommandResult as D}from"../../../command/model/CommandResult";import{GetAppAndVersionCommand as S}from"../../../command/os/GetAppAndVersionCommand";import{DeviceStatus as I}from"../../../device/DeviceStatus";import{UserInteractionRequired as s}from"../../../device-action/model/UserInteractionRequired";import{DEFAULT_UNLOCK_TIMEOUT_MS as O}from"../../../device-action/os/Const";import{DeviceLockedError as M,DeviceNotOnboardedError as T}from"../../../device-action/os/Errors";import{XStateDeviceAction as w}from"../../../device-action/xstate-utils/XStateDeviceAction";import{DeviceSessionStateType as u}from"../../../device-session/DeviceSessionState";class z extends w{makeStateMachine(n){const{getAppAndVersion:p,getDeviceSessionState:c,setDeviceSessionState:i,waitForDeviceUnlock:o,isDeviceOnboarded:d}=this.extractDependencies(n),l=this.input.unlockTimeout??O;return C({types:{input:{unlockTimeout:l},context:{},output:{}},actors:{getAppAndVersion:x(p),waitForDeviceUnlock:b(o)},guards:{isDeviceOnboarded:()=>d(),isDeviceLocked:({context:e})=>e._internalState.locked,hasError:({context:e})=>e._internalState.error!==null},actions:{assignErrorDeviceNotOnboarded:r({_internalState:e=>({...e.context._internalState,error:new T})}),assignErrorDeviceLocked:r({_internalState:e=>({...e.context._internalState,error:new M}),intermediateValue:{requiredUserInteraction:s.UnlockDevice}}),assignErrorFromEvent:r({_internalState:e=>({...e.context._internalState,error:e.event.error})}),assignNoUserActionNeeded:r({intermediateValue:e=>({...e.context.intermediateValue,requiredUserInteraction:s.None})}),assignUserActionUnlockNeeded:r({intermediateValue:e=>({...e.context.intermediateValue,requiredUserInteraction:s.UnlockDevice})})}}).createMachine({id:"GetDeviceStatusDeviceAction",initial:"DeviceReady",context:e=>{const t=c(),{sessionStateType:a}=t;return{input:{unlockTimeout:e.input.unlockTimeout},intermediateValue:{requiredUserInteraction:s.None},_internalState:{onboarded:!1,locked:!1,currentApp:a===u.ReadyWithoutSecureChannel?t.currentApp.name:null,currentAppVersion:null,error:null}}},states:{DeviceReady:{always:{target:"OnboardingCheck"}},OnboardingCheck:{always:[{guard:{type:"isDeviceOnboarded"},target:"AppAndVersionCheck",actions:r({_internalState:e=>({...e.context._internalState,onboarded:!0})})},{target:"Error",actions:"assignErrorDeviceNotOnboarded"}]},UserActionUnlockDevice:{entry:"assignUserActionUnlockNeeded",exit:"assignNoUserActionNeeded",invoke:{id:"UserActionUnlockDevice",src:"waitForDeviceUnlock",input:e=>({unlockTimeout:l}),onDone:{target:"AppAndVersionCheck",actions:r({_internalState:e=>({...e.context._internalState,locked:!1})})},onError:{target:"Error",actions:"assignErrorDeviceLocked"}}},AppAndVersionCheck:{invoke:{src:"getAppAndVersion",onDone:{target:"ApplicationAvailableResultCheck",actions:r({_internalState:e=>{if(D(e.event.output)){const t=c();return t.sessionStateType!==u.Connected?i({...t,currentApp:e.event.output.data}):i({deviceModelId:t.deviceModelId,sessionStateType:u.ReadyWithoutSecureChannel,deviceStatus:I.CONNECTED,currentApp:e.event.output.data,installedApps:[],isSecureConnectionAllowed:!1}),{...e.context._internalState,locked:!1,currentApp:e.event.output.data.name,currentAppVersion:e.event.output.data.version}}if("errorCode"in e.event.output.error){if(e.event.output.error.errorCode==="5515")return{...e.context._internalState,locked:!0};if(e.event.output.error.errorCode==="6e00")return{...e.context._internalState,locked:!1,currentApp:"BOLOS",currentAppVersion:"0.0.0"}}return{...e.context._internalState,error:e.event.output.error}}})},onError:{target:"Error",actions:"assignErrorFromEvent"}}},ApplicationAvailableResultCheck:{always:[{guard:"hasError",target:"Error"},{target:"UserActionUnlockDevice",guard:"isDeviceLocked"},{target:"Success"}]},Success:{type:"final"},Error:{type:"final"}},output:e=>{const{context:t}=e,{error:a,currentApp:v,currentAppVersion:A}=t._internalState;return a?m(a):y({currentApp:v,currentAppVersion:A})}})}extractDependencies(n){return{getAppAndVersion:()=>n.sendCommand(new S),waitForDeviceUnlock:({input:i})=>f(1e3).pipe(V(()=>g(n.sendCommand(new S))),h(o=>!D(o)&&"errorCode"in o.error&&o.error.errorCode==="5515"?k:E(void 0)),U(1),G(i.unlockTimeout)),getDeviceSessionState:()=>n.getDeviceSessionState(),setDeviceSessionState:i=>n.setDeviceSessionState(i),isDeviceOnboarded:()=>!0}}}export{z as GetDeviceStatusDeviceAction};
2
2
  //# sourceMappingURL=GetDeviceStatusDeviceAction.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/api/device-action/os/GetDeviceStatus/GetDeviceStatusDeviceAction.ts"],
4
- "sourcesContent": ["import { Left, Right } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\nimport { tap, timeout } from \"rxjs/operators\";\nimport { assign, fromObservable, fromPromise, setup } from \"xstate\";\n\nimport { isSuccessCommandResult } from \"@api/command/model/CommandResult\";\nimport {\n GetAppAndVersionCommand,\n type GetAppAndVersionCommandResult,\n} from \"@api/command/os/GetAppAndVersionCommand\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { UserInteractionRequired } from \"@api/device-action/model/UserInteractionRequired\";\nimport { DEFAULT_UNLOCK_TIMEOUT_MS } from \"@api/device-action/os/Const\";\nimport {\n DeviceLockedError,\n DeviceNotOnboardedError,\n} from \"@api/device-action/os/Errors\";\nimport { type StateMachineTypes } from \"@api/device-action/xstate-utils/StateMachineTypes\";\nimport {\n type DeviceActionStateMachine,\n XStateDeviceAction,\n} from \"@api/device-action/xstate-utils/XStateDeviceAction\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\n\nimport {\n type GetDeviceStatusDAError,\n type GetDeviceStatusDAInput,\n type GetDeviceStatusDAIntermediateValue,\n type GetDeviceStatusDAOutput,\n} from \"./types\";\n\ntype GetDeviceStatusMachineInternalState = {\n readonly onboarded: boolean;\n readonly locked: boolean;\n readonly currentApp: string | null;\n readonly currentAppVersion: string | null;\n readonly error: GetDeviceStatusDAError | null;\n};\n\nexport type MachineDependencies = {\n readonly getAppAndVersion: () => Promise<GetAppAndVersionCommandResult>;\n readonly getDeviceSessionState: () => DeviceSessionState;\n readonly waitForDeviceUnlock: (args: {\n input: { unlockTimeout: number };\n }) => Observable<void>;\n readonly setDeviceSessionState: (\n state: DeviceSessionState,\n ) => DeviceSessionState;\n readonly isDeviceOnboarded: () => boolean;\n};\n\nexport type ExtractMachineDependencies = (\n internalApi: InternalApi,\n) => MachineDependencies;\n\nexport class GetDeviceStatusDeviceAction extends XStateDeviceAction<\n GetDeviceStatusDAOutput,\n GetDeviceStatusDAInput,\n GetDeviceStatusDAError,\n GetDeviceStatusDAIntermediateValue,\n GetDeviceStatusMachineInternalState\n> {\n makeStateMachine(\n internalApi: InternalApi,\n ): DeviceActionStateMachine<\n GetDeviceStatusDAOutput,\n GetDeviceStatusDAInput,\n GetDeviceStatusDAError,\n GetDeviceStatusDAIntermediateValue,\n GetDeviceStatusMachineInternalState\n > {\n type types = StateMachineTypes<\n GetDeviceStatusDAOutput,\n GetDeviceStatusDAInput,\n GetDeviceStatusDAError,\n GetDeviceStatusDAIntermediateValue,\n GetDeviceStatusMachineInternalState\n >;\n\n const {\n getAppAndVersion,\n getDeviceSessionState,\n setDeviceSessionState,\n waitForDeviceUnlock,\n isDeviceOnboarded,\n } = this.extractDependencies(internalApi);\n\n const unlockTimeout = this.input.unlockTimeout ?? DEFAULT_UNLOCK_TIMEOUT_MS;\n\n return setup({\n types: {\n input: {\n unlockTimeout,\n } as types[\"input\"],\n context: {} as types[\"context\"],\n output: {} as types[\"output\"],\n },\n actors: {\n getAppAndVersion: fromPromise(getAppAndVersion),\n waitForDeviceUnlock: fromObservable(waitForDeviceUnlock),\n },\n guards: {\n isDeviceOnboarded: () => isDeviceOnboarded(), // TODO: we don't have this info for now, this can be derived from the \"flags\" obtained in the getVersion command\n isDeviceLocked: ({ context }) => context._internalState.locked,\n hasError: ({ context }) => context._internalState.error !== null,\n },\n actions: {\n assignErrorDeviceNotOnboarded: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n error: new DeviceNotOnboardedError(),\n }),\n }),\n assignErrorDeviceLocked: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n error: new DeviceLockedError(),\n }),\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.UnlockDevice,\n },\n }),\n assignErrorFromEvent: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n error: _.event[\"error\"], // NOTE: it should never happen, the error is not typed anymore here\n }),\n }),\n assignNoUserActionNeeded: assign({\n intermediateValue: (_) =>\n ({\n ..._.context.intermediateValue,\n requiredUserInteraction: UserInteractionRequired.None,\n }) satisfies types[\"context\"][\"intermediateValue\"],\n }),\n assignUserActionUnlockNeeded: assign({\n intermediateValue: (_) =>\n ({\n ..._.context.intermediateValue,\n requiredUserInteraction: UserInteractionRequired.UnlockDevice,\n }) satisfies types[\"context\"][\"intermediateValue\"],\n }),\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QHEwBcAiYBuBLAxmAMpoCGaArrFnoQIL5q4D2AdgHQ0FgBKYpEAJ4BiANoAGAL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7GNS-LlU4H1wt9+3OvseSFBiGFrsDx01mZ15mHooReFaVj0fZ5Jci5zissYIKY3a2NvnxsrVITCrE8RoMdDucxWgx1jpZCELDHDgKTC9jg6mNXKLDSHPcbV3O7LG3bNH2SYioLB3EmCI1-HuVL6Cj4hU6eNjsIVD3UrWfKXVCj5cV5Wvtr5n6CShaFE-1JMkWzPgXpCjh+Faw3Mjq5jdOlJhGvo-RzRr3uvr79VjgFzQtWFpARVFnWxcHQNCylCBm+eKPjJL4jWMEdNww4O46vSFVsfyD5Nlj3na9KRAUPghCwPAIdV20QIR7e-RzOYbNK98cN7ndgR-BSzgo+YmdfYPOfSgAovkQ75MbyVtItehmSrJgcijz2uHD+pmXyQSQnyVLs2tQA */\n id: \"GetDeviceStatusDeviceAction\",\n initial: \"DeviceReady\",\n context: (_) => {\n const sessionState = getDeviceSessionState();\n const { sessionStateType } = sessionState;\n return {\n input: {\n unlockTimeout: _.input.unlockTimeout,\n },\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n _internalState: {\n onboarded: false, // we don't know how to check yet\n locked: false,\n currentApp:\n sessionStateType ===\n DeviceSessionStateType.ReadyWithoutSecureChannel\n ? sessionState.currentApp.name\n : null,\n currentAppVersion: null,\n error: null,\n },\n };\n },\n states: {\n DeviceReady: {\n always: {\n target: \"OnboardingCheck\",\n },\n },\n OnboardingCheck: {\n // TODO: we don't have this info for now\n always: [\n {\n guard: {\n type: \"isDeviceOnboarded\",\n },\n target: \"AppAndVersionCheck\",\n actions: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n onboarded: true,\n }),\n }),\n },\n {\n target: \"Error\",\n actions: \"assignErrorDeviceNotOnboarded\",\n },\n ],\n },\n UserActionUnlockDevice: {\n // we wait for the device to be unlocked (default timeout is 15s)\n entry: \"assignUserActionUnlockNeeded\",\n exit: \"assignNoUserActionNeeded\",\n invoke: {\n id: \"UserActionUnlockDevice\",\n src: \"waitForDeviceUnlock\",\n input: (_) => ({\n unlockTimeout,\n }),\n onDone: {\n target: \"AppAndVersionCheck\",\n actions: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n locked: false,\n }),\n }),\n },\n onError: {\n target: \"Error\",\n actions: \"assignErrorDeviceLocked\",\n },\n },\n },\n AppAndVersionCheck: {\n // We check the current app and version using the getAppAndVersion command\n invoke: {\n src: \"getAppAndVersion\",\n onDone: {\n target: \"ApplicationAvailableResultCheck\",\n actions: assign({\n _internalState: (_) => {\n if (isSuccessCommandResult(_.event.output)) {\n const state: DeviceSessionState = getDeviceSessionState();\n if (\n state.sessionStateType !==\n DeviceSessionStateType.Connected\n ) {\n // Update the current app\n setDeviceSessionState({\n ...state,\n currentApp: _.event.output.data,\n });\n } else {\n // The device can be set to Ready if GetAppAndVersionCommand was successful\n setDeviceSessionState({\n deviceModelId: state.deviceModelId,\n sessionStateType:\n DeviceSessionStateType.ReadyWithoutSecureChannel,\n deviceStatus: DeviceStatus.CONNECTED,\n currentApp: _.event.output.data,\n installedApps: [],\n isSecureConnectionAllowed: false,\n });\n }\n return {\n ..._.context._internalState,\n locked: false,\n currentApp: _.event.output.data.name,\n currentAppVersion: _.event.output.data.version,\n };\n }\n if (\"errorCode\" in _.event.output.error) {\n if (_.event.output.error.errorCode === \"5515\") {\n // Locked device error\n return {\n ..._.context._internalState,\n locked: true,\n };\n } else if (_.event.output.error.errorCode === \"6e00\") {\n // CLA not supported\n // GetAppAndVersion should always be supported by the firmware or any app.\n // But on old firmware versions, that APDU was not supported in the dashboard.\n // On those firmwares, it fails with CLA_NOT_SUPPORTED in BOLOS, and INS_NOT_SUPPORTED\n // in applications. Therefore if CLA is not supported, we can consider we're on the\n // dashboard on an old firmware. We should therefore return that information to\n // ensure the user can still update his firmware and is not blocked at this step.\n return {\n ..._.context._internalState,\n locked: false,\n currentApp: \"BOLOS\",\n currentAppVersion: \"0.0.0\",\n };\n }\n }\n return {\n ..._.context._internalState,\n error: _.event.output.error,\n };\n },\n }),\n },\n onError: {\n target: \"Error\",\n actions: \"assignErrorFromEvent\",\n },\n },\n },\n ApplicationAvailableResultCheck: {\n always: [\n {\n guard: \"hasError\",\n target: \"Error\",\n },\n {\n target: \"UserActionUnlockDevice\",\n guard: \"isDeviceLocked\",\n },\n {\n target: \"Success\",\n },\n ],\n },\n Success: {\n type: \"final\",\n },\n Error: {\n type: \"final\",\n },\n },\n output: (args) => {\n // TODO: instead we should rely on the current state (\"Success\" or \"Error\")\n const { context } = args;\n const { error, currentApp, currentAppVersion } = context._internalState;\n if (error) {\n return Left(error);\n }\n return Right<GetDeviceStatusDAOutput>({\n currentApp: currentApp!,\n currentAppVersion: currentAppVersion!,\n });\n },\n });\n }\n\n extractDependencies(internalApi: InternalApi): MachineDependencies {\n const getAppAndVersion = () => {\n return internalApi.sendCommand(new GetAppAndVersionCommand());\n };\n\n const waitForDeviceUnlock = ({\n input,\n }: {\n input: { unlockTimeout: number };\n }) =>\n new Observable<void>((subscriber) => {\n const inner = internalApi\n .getDeviceSessionStateObservable()\n .pipe(\n tap((state) => {\n if (state.deviceStatus === DeviceStatus.CONNECTED) {\n subscriber.complete();\n inner.unsubscribe();\n }\n }),\n )\n .subscribe();\n\n return () => {\n inner.unsubscribe();\n };\n }).pipe(timeout(input.unlockTimeout));\n\n return {\n getAppAndVersion,\n waitForDeviceUnlock,\n getDeviceSessionState: () => internalApi.getDeviceSessionState(),\n setDeviceSessionState: (state: DeviceSessionState) =>\n internalApi.setDeviceSessionState(state),\n isDeviceOnboarded: () => true, // TODO: we don't have this info for now\n };\n }\n}\n"],
5
- "mappings": "AAAA,OAAS,QAAAA,EAAM,SAAAC,MAAa,YAC5B,OAAS,cAAAC,MAAkB,OAC3B,OAAS,OAAAC,EAAK,WAAAC,MAAe,iBAC7B,OAAS,UAAAC,EAAQ,kBAAAC,EAAgB,eAAAC,EAAa,SAAAC,MAAa,SAE3D,OAAS,0BAAAC,MAA8B,mCACvC,OACE,2BAAAC,MAEK,0CACP,OAAS,gBAAAC,MAAoB,2BAE7B,OAAS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B0B,CAAC,CAC3B,MAAAyB,CACF,IAGE,IAAIjC,EAAkBkC,GAAe,CACnC,MAAMC,EAAQlB,EACX,gCAAgC,EAChC,KACChB,EAAK2B,GAAU,CACTA,EAAM,eAAiBnB,EAAa,YACtCyB,EAAW,SAAS,EACpBC,EAAM,YAAY,EAEtB,CAAC,CACH,EACC,UAAU,EAEb,MAAO,IAAM,CACXA,EAAM,YAAY,CACpB,CACF,CAAC,EAAE,KAAKjC,EAAQ+B,EAAM,aAAa,CAAC,EAKpC,sBAAuB,IAAMhB,EAAY,sBAAsB,EAC/D,sBAAwBW,GACtBX,EAAY,sBAAsBW,CAAK,EACzC,kBAAmB,IAAM,EAC3B,CACF,CACF",
6
- "names": ["Left", "Right", "Observable", "tap", "timeout", "assign", "fromObservable", "fromPromise", "setup", "isSuccessCommandResult", "GetAppAndVersionCommand", "DeviceStatus", "UserInteractionRequired", "DEFAULT_UNLOCK_TIMEOUT_MS", "DeviceLockedError", "DeviceNotOnboardedError", "XStateDeviceAction", "DeviceSessionStateType", "GetDeviceStatusDeviceAction", "internalApi", "getAppAndVersion", "getDeviceSessionState", "setDeviceSessionState", "waitForDeviceUnlock", "isDeviceOnboarded", "unlockTimeout", "context", "_", "sessionState", "sessionStateType", "state", "args", "error", "currentApp", "currentAppVersion", "input", "subscriber", "inner"]
4
+ "sourcesContent": ["import { Left, Right } from \"purify-ts\";\nimport {\n EMPTY,\n from,\n interval,\n mergeMap,\n type Observable,\n of,\n switchMap,\n take,\n} from \"rxjs\";\nimport { timeout } from \"rxjs/operators\";\nimport { assign, fromObservable, fromPromise, setup } from \"xstate\";\n\nimport { isSuccessCommandResult } from \"@api/command/model/CommandResult\";\nimport {\n GetAppAndVersionCommand,\n type GetAppAndVersionCommandResult,\n} from \"@api/command/os/GetAppAndVersionCommand\";\nimport { DeviceStatus } from \"@api/device/DeviceStatus\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { UserInteractionRequired } from \"@api/device-action/model/UserInteractionRequired\";\nimport { DEFAULT_UNLOCK_TIMEOUT_MS } from \"@api/device-action/os/Const\";\nimport {\n DeviceLockedError,\n DeviceNotOnboardedError,\n} from \"@api/device-action/os/Errors\";\nimport { type StateMachineTypes } from \"@api/device-action/xstate-utils/StateMachineTypes\";\nimport {\n type DeviceActionStateMachine,\n XStateDeviceAction,\n} from \"@api/device-action/xstate-utils/XStateDeviceAction\";\nimport {\n type DeviceSessionState,\n DeviceSessionStateType,\n} from \"@api/device-session/DeviceSessionState\";\n\nimport {\n type GetDeviceStatusDAError,\n type GetDeviceStatusDAInput,\n type GetDeviceStatusDAIntermediateValue,\n type GetDeviceStatusDAOutput,\n} from \"./types\";\n\ntype GetDeviceStatusMachineInternalState = {\n readonly onboarded: boolean;\n readonly locked: boolean;\n readonly currentApp: string | null;\n readonly currentAppVersion: string | null;\n readonly error: GetDeviceStatusDAError | null;\n};\n\nexport type MachineDependencies = {\n readonly getAppAndVersion: () => Promise<GetAppAndVersionCommandResult>;\n readonly getDeviceSessionState: () => DeviceSessionState;\n readonly waitForDeviceUnlock: (args: {\n input: { unlockTimeout: number };\n }) => Observable<void>;\n readonly setDeviceSessionState: (\n state: DeviceSessionState,\n ) => DeviceSessionState;\n readonly isDeviceOnboarded: () => boolean;\n};\n\nexport type ExtractMachineDependencies = (\n internalApi: InternalApi,\n) => MachineDependencies;\n\nexport class GetDeviceStatusDeviceAction extends XStateDeviceAction<\n GetDeviceStatusDAOutput,\n GetDeviceStatusDAInput,\n GetDeviceStatusDAError,\n GetDeviceStatusDAIntermediateValue,\n GetDeviceStatusMachineInternalState\n> {\n makeStateMachine(\n internalApi: InternalApi,\n ): DeviceActionStateMachine<\n GetDeviceStatusDAOutput,\n GetDeviceStatusDAInput,\n GetDeviceStatusDAError,\n GetDeviceStatusDAIntermediateValue,\n GetDeviceStatusMachineInternalState\n > {\n type types = StateMachineTypes<\n GetDeviceStatusDAOutput,\n GetDeviceStatusDAInput,\n GetDeviceStatusDAError,\n GetDeviceStatusDAIntermediateValue,\n GetDeviceStatusMachineInternalState\n >;\n\n const {\n getAppAndVersion,\n getDeviceSessionState,\n setDeviceSessionState,\n waitForDeviceUnlock,\n isDeviceOnboarded,\n } = this.extractDependencies(internalApi);\n\n const unlockTimeout = this.input.unlockTimeout ?? DEFAULT_UNLOCK_TIMEOUT_MS;\n\n return setup({\n types: {\n input: {\n unlockTimeout,\n } as types[\"input\"],\n context: {} as types[\"context\"],\n output: {} as types[\"output\"],\n },\n actors: {\n getAppAndVersion: fromPromise(getAppAndVersion),\n waitForDeviceUnlock: fromObservable(waitForDeviceUnlock),\n },\n guards: {\n isDeviceOnboarded: () => isDeviceOnboarded(), // TODO: we don't have this info for now, this can be derived from the \"flags\" obtained in the getVersion command\n isDeviceLocked: ({ context }) => context._internalState.locked,\n hasError: ({ context }) => context._internalState.error !== null,\n },\n actions: {\n assignErrorDeviceNotOnboarded: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n error: new DeviceNotOnboardedError(),\n }),\n }),\n assignErrorDeviceLocked: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n error: new DeviceLockedError(),\n }),\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.UnlockDevice,\n },\n }),\n assignErrorFromEvent: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n error: _.event[\"error\"], // NOTE: it should never happen, the error is not typed anymore here\n }),\n }),\n assignNoUserActionNeeded: assign({\n intermediateValue: (_) =>\n ({\n ..._.context.intermediateValue,\n requiredUserInteraction: UserInteractionRequired.None,\n }) satisfies types[\"context\"][\"intermediateValue\"],\n }),\n assignUserActionUnlockNeeded: assign({\n intermediateValue: (_) =>\n ({\n ..._.context.intermediateValue,\n requiredUserInteraction: UserInteractionRequired.UnlockDevice,\n }) satisfies types[\"context\"][\"intermediateValue\"],\n }),\n },\n }).createMachine({\n /** @xstate-layout N4IgpgJg5mDOIC5QHEwBcAiYBuBLAxmAMpoCGaArrFnoQIL5q4D2AdgHQ0FgBKYpEAJ4BiANoAGAL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7GNS-LlU4H1wt9+3OvseSFBiGFrsDx01mZ15mHooReFaVj0fZ5Jci5zissYIKY3a2NvnxsrVITCrE8RoMdDucxWgx1jpZCELDHDgKTC9jg6mNXKLDSHPcbV3O7LG3bNH2SYioLB3EmCI1-HuVL6Cj4hU6eNjsIVD3UrWfKXVCj5cV5Wvtr5n6CShaFE-1JMkWzPgXpCjh+Faw3Mjq5jdOlJhGvo-RzRr3uvr79VjgFzQtWFpARVFnWxcHQNCylCBm+eKPjJL4jWMEdNww4O46vSFVsfyD5Nlj3na9KRAUPghCwPAIdV20QIR7e-RzOYbNK98cN7ndgR-BSzgo+YmdfYPOfSgAovkQ75MbyVtItehmSrJgcijz2uHD+pmXyQSQnyVLs2tQA */\n id: \"GetDeviceStatusDeviceAction\",\n initial: \"DeviceReady\",\n context: (_) => {\n const sessionState = getDeviceSessionState();\n const { sessionStateType } = sessionState;\n return {\n input: {\n unlockTimeout: _.input.unlockTimeout,\n },\n intermediateValue: {\n requiredUserInteraction: UserInteractionRequired.None,\n },\n _internalState: {\n onboarded: false, // we don't know how to check yet\n locked: false,\n currentApp:\n sessionStateType ===\n DeviceSessionStateType.ReadyWithoutSecureChannel\n ? sessionState.currentApp.name\n : null,\n currentAppVersion: null,\n error: null,\n },\n };\n },\n states: {\n DeviceReady: {\n always: {\n target: \"OnboardingCheck\",\n },\n },\n OnboardingCheck: {\n // TODO: we don't have this info for now\n always: [\n {\n guard: {\n type: \"isDeviceOnboarded\",\n },\n target: \"AppAndVersionCheck\",\n actions: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n onboarded: true,\n }),\n }),\n },\n {\n target: \"Error\",\n actions: \"assignErrorDeviceNotOnboarded\",\n },\n ],\n },\n UserActionUnlockDevice: {\n // we wait for the device to be unlocked (default timeout is 15s)\n entry: \"assignUserActionUnlockNeeded\",\n exit: \"assignNoUserActionNeeded\",\n invoke: {\n id: \"UserActionUnlockDevice\",\n src: \"waitForDeviceUnlock\",\n input: (_) => ({\n unlockTimeout,\n }),\n onDone: {\n target: \"AppAndVersionCheck\",\n actions: assign({\n _internalState: (_) => ({\n ..._.context._internalState,\n locked: false,\n }),\n }),\n },\n onError: {\n target: \"Error\",\n actions: \"assignErrorDeviceLocked\",\n },\n },\n },\n AppAndVersionCheck: {\n // We check the current app and version using the getAppAndVersion command\n invoke: {\n src: \"getAppAndVersion\",\n onDone: {\n target: \"ApplicationAvailableResultCheck\",\n actions: assign({\n _internalState: (_) => {\n if (isSuccessCommandResult(_.event.output)) {\n const state: DeviceSessionState = getDeviceSessionState();\n if (\n state.sessionStateType !==\n DeviceSessionStateType.Connected\n ) {\n // Update the current app\n setDeviceSessionState({\n ...state,\n currentApp: _.event.output.data,\n });\n } else {\n // The device can be set to Ready if GetAppAndVersionCommand was successful\n setDeviceSessionState({\n deviceModelId: state.deviceModelId,\n sessionStateType:\n DeviceSessionStateType.ReadyWithoutSecureChannel,\n deviceStatus: DeviceStatus.CONNECTED,\n currentApp: _.event.output.data,\n installedApps: [],\n isSecureConnectionAllowed: false,\n });\n }\n return {\n ..._.context._internalState,\n locked: false,\n currentApp: _.event.output.data.name,\n currentAppVersion: _.event.output.data.version,\n };\n }\n if (\"errorCode\" in _.event.output.error) {\n if (_.event.output.error.errorCode === \"5515\") {\n // Locked device error\n return {\n ..._.context._internalState,\n locked: true,\n };\n } else if (_.event.output.error.errorCode === \"6e00\") {\n // CLA not supported\n // GetAppAndVersion should always be supported by the firmware or any app.\n // But on old firmware versions, that APDU was not supported in the dashboard.\n // On those firmwares, it fails with CLA_NOT_SUPPORTED in BOLOS, and INS_NOT_SUPPORTED\n // in applications. Therefore if CLA is not supported, we can consider we're on the\n // dashboard on an old firmware. We should therefore return that information to\n // ensure the user can still update his firmware and is not blocked at this step.\n return {\n ..._.context._internalState,\n locked: false,\n currentApp: \"BOLOS\",\n currentAppVersion: \"0.0.0\",\n };\n }\n }\n return {\n ..._.context._internalState,\n error: _.event.output.error,\n };\n },\n }),\n },\n onError: {\n target: \"Error\",\n actions: \"assignErrorFromEvent\",\n },\n },\n },\n ApplicationAvailableResultCheck: {\n always: [\n {\n guard: \"hasError\",\n target: \"Error\",\n },\n {\n target: \"UserActionUnlockDevice\",\n guard: \"isDeviceLocked\",\n },\n {\n target: \"Success\",\n },\n ],\n },\n Success: {\n type: \"final\",\n },\n Error: {\n type: \"final\",\n },\n },\n output: (args) => {\n // TODO: instead we should rely on the current state (\"Success\" or \"Error\")\n const { context } = args;\n const { error, currentApp, currentAppVersion } = context._internalState;\n if (error) {\n return Left(error);\n }\n return Right<GetDeviceStatusDAOutput>({\n currentApp: currentApp!,\n currentAppVersion: currentAppVersion!,\n });\n },\n });\n }\n\n extractDependencies(internalApi: InternalApi): MachineDependencies {\n const getAppAndVersion = () => {\n return internalApi.sendCommand(new GetAppAndVersionCommand());\n };\n\n const waitForDeviceUnlock = ({\n input,\n }: {\n input: { unlockTimeout: number };\n }) =>\n interval(1000).pipe(\n switchMap(() =>\n from(internalApi.sendCommand(new GetAppAndVersionCommand())),\n ),\n mergeMap((output) => {\n const isLocked =\n !isSuccessCommandResult(output) &&\n \"errorCode\" in output.error &&\n output.error.errorCode === \"5515\";\n if (isLocked) {\n return EMPTY; // Continue the polling\n }\n return of(undefined); // Complete the observable\n }),\n take(1),\n timeout(input.unlockTimeout),\n );\n\n return {\n getAppAndVersion,\n waitForDeviceUnlock,\n getDeviceSessionState: () => internalApi.getDeviceSessionState(),\n setDeviceSessionState: (state: DeviceSessionState) =>\n internalApi.setDeviceSessionState(state),\n isDeviceOnboarded: () => true, // TODO: we don't have this info for now\n };\n }\n}\n"],
5
+ "mappings": "AAAA,OAAS,QAAAA,EAAM,SAAAC,MAAa,YAC5B,OACE,SAAAC,EACA,QAAAC,EACA,YAAAC,EACA,YAAAC,EAEA,MAAAC,EACA,aAAAC,EACA,QAAAC,MACK,OACP,OAAS,WAAAC,MAAe,iBACxB,OAAS,UAAAC,EAAQ,kBAAAC,EAAgB,eAAAC,EAAa,SAAAC,MAAa,SAE3D,OA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f,EAA+C,CA4BjE,MAAO,CACL,iBA5BuB,IAChBA,EAAY,YAAY,IAAIT,CAAyB,EA4B5D,oBAzB0B,CAAC,CAC3B,MAAAyB,CACF,IAGEpC,EAAS,GAAI,EAAE,KACbG,EAAU,IACRJ,EAAKqB,EAAY,YAAY,IAAIT,CAAyB,CAAC,CAC7D,EACAV,EAAUoC,GAEN,CAAC3B,EAAuB2B,CAAM,GAC9B,cAAeA,EAAO,OACtBA,EAAO,MAAM,YAAc,OAEpBvC,EAEFI,EAAG,MAAS,CACpB,EACDE,EAAK,CAAC,EACNC,EAAQ+B,EAAM,aAAa,CAC7B,EAKA,sBAAuB,IAAMhB,EAAY,sBAAsB,EAC/D,sBAAwBW,GACtBX,EAAY,sBAAsBW,CAAK,EACzC,kBAAmB,IAAM,EAC3B,CACF,CACF",
6
+ "names": ["Left", "Right", "EMPTY", "from", "interval", "mergeMap", "of", "switchMap", "take", "timeout", "assign", "fromObservable", "fromPromise", "setup", "isSuccessCommandResult", "GetAppAndVersionCommand", "DeviceStatus", "UserInteractionRequired", "DEFAULT_UNLOCK_TIMEOUT_MS", "DeviceLockedError", "DeviceNotOnboardedError", "XStateDeviceAction", "DeviceSessionStateType", "GetDeviceStatusDeviceAction", "internalApi", "getAppAndVersion", "getDeviceSessionState", "setDeviceSessionState", "waitForDeviceUnlock", "isDeviceOnboarded", "unlockTimeout", "context", "_", "sessionState", "sessionStateType", "state", "args", "error", "currentApp", "currentAppVersion", "input", "output"]
7
7
  }
@@ -1,2 +1,2 @@
1
- import{interval as w,Observable as C}from"rxjs";import{CommandResultFactory as d}from"../../../command/model/CommandResult";import{GLOBAL_ERRORS as O,GlobalCommandError as h}from"../../../command/utils/GlobalCommandError";import{DeviceModelId as D}from"../../../device/DeviceModel";import{DeviceStatus as i}from"../../../device/DeviceStatus";import{makeDeviceActionInternalApiMock as u}from"../../../device-action/__test-utils__/makeInternalApi";import{testDeviceActionStates as p}from"../../../device-action/__test-utils__/testDeviceActionStates";import{DeviceActionStatus as t}from"../../../device-action/model/DeviceActionState";import{UserInteractionRequired as a}from"../../../device-action/model/UserInteractionRequired";import{DeviceLockedError as x,DeviceNotOnboardedError as b,UnknownDAError as T}from"../../../device-action/os/Errors";import{DeviceSessionStateType as s}from"../../../device-session/DeviceSessionState";import{GetDeviceStatusDeviceAction as l}from"./GetDeviceStatusDeviceAction";describe("GetDeviceStatusDeviceAction",()=>{const S=vi.fn(),v=vi.fn(),y=vi.fn(),E=vi.fn(),N=vi.fn();function A(){return{getAppAndVersion:S,getDeviceSessionState:v,waitForDeviceUnlock:y,setDeviceSessionState:E,isDeviceOnboarded:N}}const{sendCommand:V,getDeviceSessionState:R,getDeviceSessionStateObservable:f}=u();beforeEach(()=>{vi.resetAllMocks(),N.mockReturnValue(!0)}),describe("without overriding `extractDependencies`",()=>{it("should run the device action with an unlocked device",()=>new Promise((r,o)=>{const e=new l({input:{unlockTimeout:500}});R.mockReturnValue({sessionStateType:s.Connected,deviceStatus:i.CONNECTED,deviceModelId:D.NANO_X}),V.mockResolvedValue(d({data:{name:"BOLOS",version:"1.0.0"}}));const n=[{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"},status:t.Completed}];p(e,n,u(),{onDone:r,onError:o})})),it("should run the device action with a locked device",()=>new Promise((r,o)=>{const e=new l({input:{unlockTimeout:500}});R.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"},installedApps:[],deviceModelId:D.NANO_X,isSecureConnectionAllowed:!1}),f.mockImplementation(()=>new C(c=>{const m=w(50).subscribe({next:k=>{k>2?(c.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"},installedApps:[],deviceModelId:D.NANO_X,isSecureConnectionAllowed:!1}),c.complete()):c.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"},installedApps:[],deviceModelId:D.NANO_X,isSecureConnectionAllowed:!1})}});return()=>{m.unsubscribe()}})),V.mockResolvedValueOnce(d({error:new h({...O[5515],errorCode:"5515"})})).mockResolvedValueOnce(d({data:{name:"BOLOS",version:"1.0.0"}}));const n=[{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{intermediateValue:{requiredUserInteraction:a.UnlockDevice},status:t.Pending},{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"},status:t.Completed}];p(e,n,u(),{onDone:r,onError:o})})),it("should run the device action with an old firmware not supporting GetAppAndVersion",()=>new Promise((r,o)=>{const e=new l({input:{unlockTimeout:500}});R.mockReturnValue({sessionStateType:s.Connected,deviceStatus:i.CONNECTED,deviceModelId:D.NANO_X}),V.mockResolvedValue(d({error:new h({...O["6e00"],errorCode:"6e00"})}));const n=[{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{output:{currentApp:"BOLOS",currentAppVersion:"0.0.0"},status:t.Completed}];p(e,n,u(),{onDone:r,onError:o})}))}),describe("success cases",()=>{it("should return the device status if the device is unlocked",()=>new Promise((r,o)=>{v.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),S.mockResolvedValue(d({data:{name:"BOLOS",version:"1.0.0"}}));const e=new l({input:{unlockTimeout:void 0}});vi.spyOn(e,"extractDependencies").mockReturnValue(A());const n=[{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{status:t.Completed,output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"}}];p(e,n,u(),{onDone:()=>{expect(E).toHaveBeenCalledWith({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"BOLOS",version:"1.0.0"}}),r()},onError:o})})),it("should return the device status and update session if the device is not ready",()=>new Promise((r,o)=>{v.mockReturnValue({sessionStateType:s.Connected,deviceStatus:i.CONNECTED}),S.mockResolvedValue(d({data:{name:"BOLOS",version:"1.0.0"}}));const e=new l({input:{unlockTimeout:void 0}});vi.spyOn(e,"extractDependencies").mockReturnValue(A());const n=[{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{status:t.Completed,output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"}}];p(e,n,u(),{onDone:()=>{expect(E).toHaveBeenCalledWith({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"BOLOS",version:"1.0.0"},installedApps:[],isSecureConnectionAllowed:!1}),r()},onError:o})})),it("should return the device status if the device is locked and the user unlocks the device",()=>new Promise((r,o)=>{v.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),S.mockResolvedValueOnce(d({error:new h({...O[5515],errorCode:"5515"})})).mockResolvedValueOnce(d({data:{name:"BOLOS",version:"1.0.0"}})),y.mockImplementation(()=>new C(c=>{const m=w(50).subscribe({next:k=>{k>2?(c.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),c.complete()):c.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}})}});return()=>{m.unsubscribe()}}));const e=new l({input:{unlockTimeout:500}});vi.spyOn(e,"extractDependencies").mockReturnValue(A());const n=[{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{intermediateValue:{requiredUserInteraction:a.UnlockDevice},status:t.Pending},{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{status:t.Completed,output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"}}];p(e,n,u(),{onDone:r,onError:o})}))}),describe("errors cases",()=>{it("should end in an error if the device is not onboarded",()=>new Promise((r,o)=>{v.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),N.mockReturnValue(!1);const e=new l({input:{unlockTimeout:500}});vi.spyOn(e,"extractDependencies").mockReturnValue(A());const n=[{error:new b,status:t.Error}];p(e,n,u(),{onDone:r,onError:o})})),it("should end in an error if the device is locked and the user does not unlock",()=>new Promise((r,o)=>{v.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),S.mockResolvedValue(d({error:new h({...O[5515],errorCode:"5515"})})),f.mockImplementation(()=>new C(c=>{const m=w(200).subscribe({next:()=>{c.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"},installedApps:[],deviceModelId:D.NANO_X,isSecureConnectionAllowed:!1})}});return()=>{m.unsubscribe()}}));const e=new l({input:{unlockTimeout:500}});vi.spyOn(e,"extractDependencies").mockReturnValue(A());const n=[{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{intermediateValue:{requiredUserInteraction:a.UnlockDevice},status:t.Pending},{error:new x("Device locked."),status:t.Error}];p(e,n,u(),{onDone:r,onError:o})})),it("should end in an error if the GetAppAndVersion command fails",()=>new Promise((r,o)=>{v.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}});const e=new h({...O[5501],errorCode:"5501"});S.mockResolvedValue(d({error:e})),y.mockImplementation(()=>new C(m=>{const k=w(50).subscribe({next:g=>{g>2?(m.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),m.complete()):m.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}})}});return()=>{k.unsubscribe()}}));const n=new l({input:{unlockTimeout:500}});vi.spyOn(n,"extractDependencies").mockReturnValue(A());const c=[{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{error:e,status:t.Error}];p(n,c,u(),{onDone:r,onError:o})})),it("should end in an error if getAppAndVersion actor throws an error",()=>new Promise((r,o)=>{v.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),S.mockImplementation(()=>{throw new T("error")}),y.mockImplementation(()=>new C(c=>{c.complete()}));const e=new l({input:{unlockTimeout:500}});vi.spyOn(e,"extractDependencies").mockReturnValue(A());const n=[{intermediateValue:{requiredUserInteraction:a.None},status:t.Pending},{error:new T("error"),status:t.Error}];p(e,n,u(),{onDone:r,onError:o})}))}),it("should emit a stopped state if the action is cancelled",()=>new Promise((r,o)=>{R.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"},installedApps:[],deviceModelId:D.NANO_X,isSecureConnectionAllowed:!1}),V.mockResolvedValue(d({data:{name:"BOLOS",version:"1.0.0"}}));const e=new l({input:{unlockTimeout:500}}),n=[{status:t.Pending,intermediateValue:{requiredUserInteraction:a.None}},{status:t.Stopped}],{cancel:c}=p(e,n,u(),{onDone:r,onError:o});c()}))});
1
+ import{interval as N,Observable as y}from"rxjs";import{CommandResultFactory as a}from"../../../command/model/CommandResult";import{GLOBAL_ERRORS as A,GlobalCommandError as k}from"../../../command/utils/GlobalCommandError";import{DeviceModelId as C}from"../../../device/DeviceModel";import{DeviceStatus as i}from"../../../device/DeviceStatus";import{makeDeviceActionInternalApiMock as u}from"../../../device-action/__test-utils__/makeInternalApi";import{testDeviceActionStates as d}from"../../../device-action/__test-utils__/testDeviceActionStates";import{DeviceActionStatus as t}from"../../../device-action/model/DeviceActionState";import{UserInteractionRequired as c}from"../../../device-action/model/UserInteractionRequired";import{DeviceLockedError as T,DeviceNotOnboardedError as I,UnknownDAError as f}from"../../../device-action/os/Errors";import{DeviceSessionStateType as s}from"../../../device-session/DeviceSessionState";import{GetDeviceStatusDeviceAction as p}from"./GetDeviceStatusDeviceAction";describe("GetDeviceStatusDeviceAction",()=>{const v=vi.fn(),m=vi.fn(),V=vi.fn(),w=vi.fn(),R=vi.fn();function S(){return{getAppAndVersion:v,getDeviceSessionState:m,waitForDeviceUnlock:V,setDeviceSessionState:w,isDeviceOnboarded:R}}const{sendCommand:O,getDeviceSessionState:h,getDeviceSessionStateObservable:g}=u();beforeEach(()=>{vi.resetAllMocks(),R.mockReturnValue(!0)}),describe("without overriding `extractDependencies`",()=>{it("should run the device action with an unlocked device",()=>new Promise((r,o)=>{const e=new p({input:{unlockTimeout:500}});h.mockReturnValue({sessionStateType:s.Connected,deviceStatus:i.CONNECTED,deviceModelId:C.NANO_X}),O.mockResolvedValue(a({data:{name:"BOLOS",version:"1.0.0"}}));const n=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"},status:t.Completed}];d(e,n,u(),{onDone:r,onError:o})})),it("should run the device action with a locked device",()=>new Promise((r,o)=>{const e=new p({input:{unlockTimeout:1500}});h.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"},installedApps:[],deviceModelId:C.NANO_X,isSecureConnectionAllowed:!1}),O.mockResolvedValueOnce(a({error:new k({...A[5515],errorCode:"5515"})})).mockResolvedValue(a({data:{name:"BOLOS",version:"1.0.0"}}));const n=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{intermediateValue:{requiredUserInteraction:c.UnlockDevice},status:t.Pending},{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"},status:t.Completed}];d(e,n,u(),{onDone:r,onError:o})})),it("should timeout with a locked device",()=>new Promise((r,o)=>{const e=new p({input:{unlockTimeout:200}});h.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"},installedApps:[],deviceModelId:C.NANO_X,isSecureConnectionAllowed:!1}),O.mockResolvedValueOnce(a({error:new k({...A[5515],errorCode:"5515"})})).mockResolvedValue(a({data:{name:"BOLOS",version:"1.0.0"}}));const n=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{intermediateValue:{requiredUserInteraction:c.UnlockDevice},status:t.Pending},{error:new T("Device locked."),status:t.Error}];d(e,n,u(),{onDone:r,onError:o})})),it("should run the device action with an old firmware not supporting GetAppAndVersion",()=>new Promise((r,o)=>{const e=new p({input:{unlockTimeout:500}});h.mockReturnValue({sessionStateType:s.Connected,deviceStatus:i.CONNECTED,deviceModelId:C.NANO_X}),O.mockResolvedValue(a({error:new k({...A["6e00"],errorCode:"6e00"})}));const n=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{output:{currentApp:"BOLOS",currentAppVersion:"0.0.0"},status:t.Completed}];d(e,n,u(),{onDone:r,onError:o})}))}),describe("success cases",()=>{it("should return the device status if the device is unlocked",()=>new Promise((r,o)=>{m.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),v.mockResolvedValue(a({data:{name:"BOLOS",version:"1.0.0"}}));const e=new p({input:{unlockTimeout:void 0}});vi.spyOn(e,"extractDependencies").mockReturnValue(S());const n=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{status:t.Completed,output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"}}];d(e,n,u(),{onDone:()=>{expect(w).toHaveBeenCalledWith({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"BOLOS",version:"1.0.0"}}),r()},onError:o})})),it("should return the device status and update session if the device is not ready",()=>new Promise((r,o)=>{m.mockReturnValue({sessionStateType:s.Connected,deviceStatus:i.CONNECTED}),v.mockResolvedValue(a({data:{name:"BOLOS",version:"1.0.0"}}));const e=new p({input:{unlockTimeout:void 0}});vi.spyOn(e,"extractDependencies").mockReturnValue(S());const n=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{status:t.Completed,output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"}}];d(e,n,u(),{onDone:()=>{expect(w).toHaveBeenCalledWith({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"BOLOS",version:"1.0.0"},installedApps:[],isSecureConnectionAllowed:!1}),r()},onError:o})})),it("should return the device status if the device is locked and the user unlocks the device",()=>new Promise((r,o)=>{m.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),v.mockResolvedValueOnce(a({error:new k({...A[5515],errorCode:"5515"})})).mockResolvedValueOnce(a({data:{name:"BOLOS",version:"1.0.0"}})),V.mockImplementation(()=>new y(l=>{const D=N(50).subscribe({next:E=>{E>2?(l.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),l.complete()):l.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}})}});return()=>{D.unsubscribe()}}));const e=new p({input:{unlockTimeout:500}});vi.spyOn(e,"extractDependencies").mockReturnValue(S());const n=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{intermediateValue:{requiredUserInteraction:c.UnlockDevice},status:t.Pending},{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{status:t.Completed,output:{currentApp:"BOLOS",currentAppVersion:"1.0.0"}}];d(e,n,u(),{onDone:r,onError:o})}))}),describe("errors cases",()=>{it("should end in an error if the device is not onboarded",()=>new Promise((r,o)=>{m.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),R.mockReturnValue(!1);const e=new p({input:{unlockTimeout:500}});vi.spyOn(e,"extractDependencies").mockReturnValue(S());const n=[{error:new I,status:t.Error}];d(e,n,u(),{onDone:r,onError:o})})),it("should end in an error if the device is locked and the user does not unlock",()=>new Promise((r,o)=>{m.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),v.mockResolvedValue(a({error:new k({...A[5515],errorCode:"5515"})})),g.mockImplementation(()=>new y(l=>{const D=N(200).subscribe({next:()=>{l.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"},installedApps:[],deviceModelId:C.NANO_X,isSecureConnectionAllowed:!1})}});return()=>{D.unsubscribe()}}));const e=new p({input:{unlockTimeout:500}});vi.spyOn(e,"extractDependencies").mockReturnValue(S());const n=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{intermediateValue:{requiredUserInteraction:c.UnlockDevice},status:t.Pending},{error:new T("Device locked."),status:t.Error}];d(e,n,u(),{onDone:r,onError:o})})),it("should end in an error if the GetAppAndVersion command fails",()=>new Promise((r,o)=>{m.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}});const e=new k({...A[5501],errorCode:"5501"});v.mockResolvedValue(a({error:e})),V.mockImplementation(()=>new y(D=>{const E=N(50).subscribe({next:x=>{x>2?(D.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),D.complete()):D.next({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}})}});return()=>{E.unsubscribe()}}));const n=new p({input:{unlockTimeout:500}});vi.spyOn(n,"extractDependencies").mockReturnValue(S());const l=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{error:e,status:t.Error}];d(n,l,u(),{onDone:r,onError:o})})),it("should end in an error if getAppAndVersion actor throws an error",()=>new Promise((r,o)=>{m.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.LOCKED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"}}),v.mockImplementation(()=>{throw new f("error")}),V.mockImplementation(()=>new y(l=>{l.complete()}));const e=new p({input:{unlockTimeout:500}});vi.spyOn(e,"extractDependencies").mockReturnValue(S());const n=[{intermediateValue:{requiredUserInteraction:c.None},status:t.Pending},{error:new f("error"),status:t.Error}];d(e,n,u(),{onDone:r,onError:o})}))}),it("should emit a stopped state if the action is cancelled",()=>new Promise((r,o)=>{h.mockReturnValue({sessionStateType:s.ReadyWithoutSecureChannel,deviceStatus:i.CONNECTED,currentApp:{name:"mockedCurrentApp",version:"1.0.0"},installedApps:[],deviceModelId:C.NANO_X,isSecureConnectionAllowed:!1}),O.mockResolvedValue(a({data:{name:"BOLOS",version:"1.0.0"}}));const e=new p({input:{unlockTimeout:500}}),n=[{status:t.Pending,intermediateValue:{requiredUserInteraction:c.None}},{status:t.Stopped}],{cancel:l}=d(e,n,u(),{onDone:r,onError:o});l()}))});
2
2
  //# sourceMappingURL=GetDeviceStatusDeviceAction.test.js.map