@ledgerhq/device-management-kit 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/lib/cjs/package.json +1 -1
- package/lib/cjs/src/api/DeviceManagementKit.js +1 -1
- package/lib/cjs/src/api/DeviceManagementKit.js.map +3 -3
- package/lib/cjs/src/api/DeviceManagementKit.test.js +1 -1
- package/lib/cjs/src/api/DeviceManagementKit.test.js.map +3 -3
- package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
- package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.js.map +2 -2
- package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
- package/lib/cjs/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
- package/lib/cjs/src/api/device/DeviceModel.js +1 -1
- package/lib/cjs/src/api/device/DeviceModel.js.map +2 -2
- package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
- package/lib/cjs/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +2 -2
- package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.js +1 -1
- package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.js.map +2 -2
- package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.test.js +1 -1
- package/lib/cjs/src/api/device-model/data/StaticDeviceModelDataSource.test.js.map +2 -2
- package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
- package/lib/cjs/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +2 -2
- package/lib/cjs/src/api/utils/HexaString.js +1 -1
- package/lib/cjs/src/api/utils/HexaString.js.map +3 -3
- package/lib/cjs/src/api/utils/HexaString.test.js +1 -1
- package/lib/cjs/src/api/utils/HexaString.test.js.map +2 -2
- package/lib/cjs/src/internal/device-session/service/DefaultApduReceiverService.js +1 -1
- package/lib/cjs/src/internal/device-session/service/DefaultApduReceiverService.js.map +2 -2
- package/lib/cjs/src/internal/device-session/service/DefaultApduSenderService.js +1 -1
- package/lib/cjs/src/internal/device-session/service/DefaultApduSenderService.js.map +2 -2
- package/lib/esm/package.json +1 -1
- package/lib/esm/src/api/DeviceManagementKit.js +1 -1
- package/lib/esm/src/api/DeviceManagementKit.js.map +3 -3
- package/lib/esm/src/api/DeviceManagementKit.test.js +1 -1
- package/lib/esm/src/api/DeviceManagementKit.test.js.map +3 -3
- package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js +1 -1
- package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.js.map +3 -3
- package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js +1 -1
- package/lib/esm/src/api/apdu/utils/ByteArrayBuilder.test.js.map +2 -2
- package/lib/esm/src/api/device/DeviceModel.js +1 -1
- package/lib/esm/src/api/device/DeviceModel.js.map +2 -2
- package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js +1 -1
- package/lib/esm/src/api/device-action/xstate-utils/XStateDeviceAction.js.map +2 -2
- package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.js +1 -1
- package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.js.map +2 -2
- package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.test.js +1 -1
- package/lib/esm/src/api/device-model/data/StaticDeviceModelDataSource.test.js.map +2 -2
- package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js +1 -1
- package/lib/esm/src/api/secure-channel/task/ConnectToSecureChannelTask.js.map +2 -2
- package/lib/esm/src/api/utils/HexaString.js +1 -1
- package/lib/esm/src/api/utils/HexaString.js.map +3 -3
- package/lib/esm/src/api/utils/HexaString.test.js +1 -1
- package/lib/esm/src/api/utils/HexaString.test.js.map +2 -2
- package/lib/esm/src/internal/device-session/service/DefaultApduReceiverService.js +1 -1
- package/lib/esm/src/internal/device-session/service/DefaultApduReceiverService.js.map +2 -2
- package/lib/esm/src/internal/device-session/service/DefaultApduSenderService.js +1 -1
- package/lib/esm/src/internal/device-session/service/DefaultApduSenderService.js.map +2 -2
- package/lib/types/src/api/DeviceManagementKit.d.ts +4 -0
- package/lib/types/src/api/DeviceManagementKit.d.ts.map +1 -1
- package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts +38 -0
- package/lib/types/src/api/apdu/utils/ByteArrayBuilder.d.ts.map +1 -1
- package/lib/types/src/api/device/DeviceModel.d.ts +1 -1
- package/lib/types/src/api/device/DeviceModel.d.ts.map +1 -1
- package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts +1 -0
- package/lib/types/src/api/device-action/xstate-utils/XStateDeviceAction.d.ts.map +1 -1
- package/lib/types/src/api/utils/HexaString.d.ts +4 -3
- package/lib/types/src/api/utils/HexaString.d.ts.map +1 -1
- package/lib/types/src/internal/device-session/service/DefaultApduReceiverService.d.ts.map +1 -1
- package/lib/types/tsconfig.prod.tsbuildinfo +1 -1
- package/package.json +4 -4
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var i=Object.defineProperty;var s=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var d=(n,e)=>{for(var o in e)i(n,o,{get:e[o],enumerable:!0})},x=(n,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of p(e))!c.call(n,t)&&t!==o&&i(n,t,{get:()=>e[t],enumerable:!(a=s(e,t))||a.enumerable});return n};var y=n=>x(i({},"__esModule",{value:!0}),n);var N={};d(N,{DeviceModel:()=>m,DeviceModelId:()=>l,LEDGER_VENDOR_ID:()=>A});module.exports=y(N);var l=(r=>(r.NANO_S="nanoS",r.NANO_SP="nanoSP",r.NANO_X="nanoX",r.STAX="stax",r.FLEX="flex",r.APEX="
|
1
|
+
"use strict";var i=Object.defineProperty;var s=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var d=(n,e)=>{for(var o in e)i(n,o,{get:e[o],enumerable:!0})},x=(n,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of p(e))!c.call(n,t)&&t!==o&&i(n,t,{get:()=>e[t],enumerable:!(a=s(e,t))||a.enumerable});return n};var y=n=>x(i({},"__esModule",{value:!0}),n);var N={};d(N,{DeviceModel:()=>m,DeviceModelId:()=>l,LEDGER_VENDOR_ID:()=>A});module.exports=y(N);var l=(r=>(r.NANO_S="nanoS",r.NANO_SP="nanoSP",r.NANO_X="nanoX",r.STAX="stax",r.FLEX="flex",r.APEX="apexp",r))(l||{});class m{id;model;name;constructor({id:e,model:o,name:a}){this.id=e,this.model=o,this.name=a}}const A=11415;0&&(module.exports={DeviceModel,DeviceModelId,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 = \"
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,kBAAAC,EAAA,qBAAAC,IAAA,eAAAC,EAAAL,GAAO,IAAKG,OACVA,EAAA,OAAS,QACTA,EAAA,QAAU,SACVA,EAAA,OAAS,QACTA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,KAAO,
|
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": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,EAAA,kBAAAC,EAAA,qBAAAC,IAAA,eAAAC,EAAAL,GAAO,IAAKG,OACVA,EAAA,OAAS,QACTA,EAAA,QAAU,SACVA,EAAA,OAAS,QACTA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,KAAO,QANGA,OAAA,IAyBL,MAAMD,CAAY,CACP,GACA,MACA,KAEhB,YAAY,CAAE,GAAAI,EAAI,MAAAC,EAAO,KAAAC,CAAK,EAAoB,CAChD,KAAK,GAAKF,EACV,KAAK,MAAQC,EACb,KAAK,KAAOC,CACd,CACF,CAEO,MAAMJ,EAAmB",
|
6
6
|
"names": ["DeviceModel_exports", "__export", "DeviceModel", "DeviceModelId", "LEDGER_VENDOR_ID", "__toCommonJS", "id", "model", "name"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var s=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var
|
1
|
+
"use strict";var s=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var A=(a,e)=>{for(var t in e)s(a,t,{get:e[t],enumerable:!0})},E=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of y(e))!v.call(a,r)&&r!==t&&s(a,r,{get:()=>e[r],enumerable:!(n=b(e,r))||n.enumerable});return a};var x=a=>E(s({},"__esModule",{value:!0}),a);var M={};A(M,{XStateDeviceAction:()=>D});module.exports=x(M);var i=require("rxjs"),h=require("xstate"),c=require("../../device-action/model/DeviceActionState");class D{input;inspect=!1;constructor(e){this.input=e.input,this.inspect=!!e.inspect}_execute(e){const t=this.makeStateMachine(e);return this._subscribeToStateMachine(t)}_subscribeToStateMachine(e){const t=(0,h.createActor)(e,{input:this.input}),n=new i.ReplaySubject,r=o=>{const{context:u,status:m,output:S,error:I}=o;switch(m){case"active":n.next({status:c.DeviceActionStatus.Pending,intermediateValue:u.intermediateValue});break;case"done":S.caseOf({Left:p=>{n.next({status:c.DeviceActionStatus.Error,error:p})},Right:p=>{n.next({status:c.DeviceActionStatus.Completed,output:p})}}),n.complete();break;case"error":n.error(I),n.complete();break;case"stopped":n.next({status:c.DeviceActionStatus.Stopped}),n.complete();break;default:this._exhaustiveMatchingGuard(m)}},d=new i.Observable(o=>{const u=n.subscribe(o);return()=>{l.unsubscribe(),u.unsubscribe(),t.stop()}}),l=t.subscribe(r);return t.start(),{observable:d.pipe((0,i.share)()),cancel:()=>{t.stop(),l.unsubscribe(),r(t.getSnapshot())}}}_exhaustiveMatchingGuard(e){throw console.log("_exhaustiveMatchingGuard status",e),new Error(`Unhandled status: ${e}`)}}0&&(module.exports={XStateDeviceAction});
|
2
2
|
//# sourceMappingURL=XStateDeviceAction.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/api/device-action/xstate-utils/XStateDeviceAction.ts"],
|
4
|
-
"sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { Observable, ReplaySubject, share } from \"rxjs\";\nimport {\n createActor,\n type SnapshotFrom,\n type StateMachine,\n type StateSchema,\n} from \"xstate\";\n\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n type InternalApi,\n} from \"@api/device-action/DeviceAction\";\nimport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nimport { type DmkError } from \"@api/Error\";\n\nimport { type StateMachineTypes } from \"./StateMachineTypes\";\n\nexport type DeviceActionStateMachine<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n InternalState,\n> = StateMachine<\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"context\"], // context\n /**\n * The following usages `any` are OK because this is just a wrapper around the\n * state machine and we are not directly going to use these types.\n */\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any, // event\n any, // children\n any, // actor\n any, // action\n any, // guard\n any, // delay\n any, // state value\n any, // tag\n /* eslint-enable @typescript-eslint/no-explicit-any */\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"input\"],\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"output\"],\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n any,\n /* eslint-enable @typescript-eslint/no-explicit-any */\n StateSchema\n>;\n\n/**\n * A DeviceAction that uses an XState state machine to execute.\n * It maps the state machine snapshots to the DeviceActionState.\n * This class is abstract and should be extended to implement the state machine.\n */\nexport abstract class XStateDeviceAction<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n InternalState,\n> implements DeviceAction<Output, Input, Error, IntermediateValue>\n{\n readonly input: Input;\n readonly inspect: boolean = false;\n\n /**\n *\n * @param input The input for the DeviceAction\n * @param inspect If true, the state machine will be inspected in the browser\n */\n constructor(args: { input: Input; inspect?: boolean }) {\n this.input = args.input;\n this.inspect = Boolean(args.inspect);\n }\n\n protected abstract makeStateMachine(\n internalAPI: InternalApi,\n ): DeviceActionStateMachine<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >;\n\n _execute(\n internalApi: InternalApi,\n ): ExecuteDeviceActionReturnType<Output, Error, IntermediateValue> {\n const stateMachine = this.makeStateMachine(internalApi);\n\n const actor = createActor(stateMachine, {\n input: this.input,\n // optional inspector for debugging\n // inspect: this.inspect ? createBrowserInspector().inspect : undefined,\n });\n\n /**\n * Using a ReplaySubject is important because the first snapshots might be\n * emitted before the observable is subscribed (if the machine goes through\n * those states fully synchronously).\n * This way, we ensure that the subscriber always receives the latest snapshot.\n * */\n const subject = new ReplaySubject<\n DeviceActionState<Output, Error, IntermediateValue>\n >();\n\n const handleActorSnapshot = (\n snapshot: SnapshotFrom<typeof stateMachine>,\n ) => {\n const { context, status, output, error } = snapshot;\n switch (status) {\n case \"active\":\n subject.next({\n status: DeviceActionStatus.Pending,\n intermediateValue: context.intermediateValue,\n });\n break;\n case \"done\":\n output.caseOf({\n Left: (err) => {\n subject.next({\n status: DeviceActionStatus.Error,\n error: err,\n });\n },\n Right: (result) => {\n subject.next({\n status: DeviceActionStatus.Completed,\n output: result,\n });\n },\n });\n subject.complete();\n break;\n case \"error\":\n // this is an error in the execution of the state machine, it should not happen\n subject.error(error);\n subject.complete();\n break;\n case \"stopped\":\n subject.next({\n status: DeviceActionStatus.Stopped,\n });\n subject.complete();\n break;\n default:\n this._exhaustiveMatchingGuard(status);\n }\n };\n\n const observable = new Observable<\n DeviceActionState<Output, Error, IntermediateValue>\n >((subscriber) => {\n const subjectSubscription = subject.subscribe(subscriber);\n return () => {\n actorSubscription.unsubscribe();\n subjectSubscription.unsubscribe();\n actor.stop(); // stop the actor when the observable is unsubscribed\n };\n });\n\n const actorSubscription = actor.subscribe(handleActorSnapshot);\n actor.start();\n\n return {\n observable: observable.pipe(share()), // share to garantee that once there is no more observer, the actor is stopped\n cancel: () => {\n actor.stop();\n actorSubscription.unsubscribe();\n handleActorSnapshot(actor.getSnapshot());\n },\n };\n }\n\n private _exhaustiveMatchingGuard(status: never): never {\n console.log(\"_exhaustiveMatchingGuard status\", status);\n throw new Error(`Unhandled status: ${status}`);\n }\n}\n"],
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAiD,gBACjDC,EAKO,kBAQPC,EAGO,sDA2DA,MAAeJ,CAOtB,CACW,MACA,QAAmB,GAO5B,YAAYK,EAA2C,CACrD,KAAK,MAAQA,EAAK,MAClB,KAAK,QAAU,EAAQA,EAAK,OAC9B,CAYA,SACEC,EACiE,CACjE,MAAMC,EAAe,KAAK,iBAAiBD,CAAW,
|
4
|
+
"sourcesContent": ["// import { createBrowserInspector } from \"@statelyai/inspect\";\nimport { Observable, ReplaySubject, share } from \"rxjs\";\nimport {\n createActor,\n type SnapshotFrom,\n type StateMachine,\n type StateSchema,\n} from \"xstate\";\n\nimport {\n type DeviceAction,\n type DeviceActionIntermediateValue,\n type ExecuteDeviceActionReturnType,\n type InternalApi,\n} from \"@api/device-action/DeviceAction\";\nimport {\n type DeviceActionState,\n DeviceActionStatus,\n} from \"@api/device-action/model/DeviceActionState\";\nimport { type DmkError } from \"@api/Error\";\n\nimport { type StateMachineTypes } from \"./StateMachineTypes\";\n\nexport type DeviceActionStateMachine<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n InternalState,\n> = StateMachine<\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"context\"], // context\n /**\n * The following usages `any` are OK because this is just a wrapper around the\n * state machine and we are not directly going to use these types.\n */\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any, // event\n any, // children\n any, // actor\n any, // action\n any, // guard\n any, // delay\n any, // state value\n any, // tag\n /* eslint-enable @typescript-eslint/no-explicit-any */\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"input\"],\n StateMachineTypes<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >[\"output\"],\n /* eslint-disable @typescript-eslint/no-explicit-any */\n any,\n any,\n /* eslint-enable @typescript-eslint/no-explicit-any */\n StateSchema\n>;\n\n/**\n * A DeviceAction that uses an XState state machine to execute.\n * It maps the state machine snapshots to the DeviceActionState.\n * This class is abstract and should be extended to implement the state machine.\n */\nexport abstract class XStateDeviceAction<\n Output,\n Input,\n Error extends DmkError,\n IntermediateValue extends DeviceActionIntermediateValue,\n InternalState,\n> implements DeviceAction<Output, Input, Error, IntermediateValue>\n{\n readonly input: Input;\n readonly inspect: boolean = false;\n\n /**\n *\n * @param input The input for the DeviceAction\n * @param inspect If true, the state machine will be inspected in the browser\n */\n constructor(args: { input: Input; inspect?: boolean }) {\n this.input = args.input;\n this.inspect = Boolean(args.inspect);\n }\n\n protected abstract makeStateMachine(\n internalAPI: InternalApi,\n ): DeviceActionStateMachine<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >;\n\n _execute(\n internalApi: InternalApi,\n ): ExecuteDeviceActionReturnType<Output, Error, IntermediateValue> {\n const stateMachine = this.makeStateMachine(internalApi);\n return this._subscribeToStateMachine(stateMachine);\n }\n\n protected _subscribeToStateMachine(\n stateMachine: DeviceActionStateMachine<\n Output,\n Input,\n Error,\n IntermediateValue,\n InternalState\n >,\n ): ExecuteDeviceActionReturnType<Output, Error, IntermediateValue> {\n const actor = createActor(stateMachine, {\n input: this.input,\n // optional inspector for debugging\n // inspect: this.inspect ? createBrowserInspector().inspect : undefined,\n });\n\n /**\n * Using a ReplaySubject is important because the first snapshots might be\n * emitted before the observable is subscribed (if the machine goes through\n * those states fully synchronously).\n * This way, we ensure that the subscriber always receives the latest snapshot.\n * */\n const subject = new ReplaySubject<\n DeviceActionState<Output, Error, IntermediateValue>\n >();\n\n const handleActorSnapshot = (\n snapshot: SnapshotFrom<typeof stateMachine>,\n ) => {\n const { context, status, output, error } = snapshot;\n switch (status) {\n case \"active\":\n subject.next({\n status: DeviceActionStatus.Pending,\n intermediateValue: context.intermediateValue,\n });\n break;\n case \"done\":\n output.caseOf({\n Left: (err) => {\n subject.next({\n status: DeviceActionStatus.Error,\n error: err,\n });\n },\n Right: (result) => {\n subject.next({\n status: DeviceActionStatus.Completed,\n output: result,\n });\n },\n });\n subject.complete();\n break;\n case \"error\":\n // this is an error in the execution of the state machine, it should not happen\n subject.error(error);\n subject.complete();\n break;\n case \"stopped\":\n subject.next({\n status: DeviceActionStatus.Stopped,\n });\n subject.complete();\n break;\n default:\n this._exhaustiveMatchingGuard(status);\n }\n };\n\n const observable = new Observable<\n DeviceActionState<Output, Error, IntermediateValue>\n >((subscriber) => {\n const subjectSubscription = subject.subscribe(subscriber);\n return () => {\n actorSubscription.unsubscribe();\n subjectSubscription.unsubscribe();\n actor.stop(); // stop the actor when the observable is unsubscribed\n };\n });\n\n const actorSubscription = actor.subscribe(handleActorSnapshot);\n actor.start();\n\n return {\n observable: observable.pipe(share()), // share to garantee that once there is no more observer, the actor is stopped\n cancel: () => {\n actor.stop();\n actorSubscription.unsubscribe();\n handleActorSnapshot(actor.getSnapshot());\n },\n };\n }\n\n private _exhaustiveMatchingGuard(status: never): never {\n console.log(\"_exhaustiveMatchingGuard status\", status);\n throw new Error(`Unhandled status: ${status}`);\n }\n}\n"],
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,IAAA,eAAAC,EAAAH,GACA,IAAAI,EAAiD,gBACjDC,EAKO,kBAQPC,EAGO,sDA2DA,MAAeJ,CAOtB,CACW,MACA,QAAmB,GAO5B,YAAYK,EAA2C,CACrD,KAAK,MAAQA,EAAK,MAClB,KAAK,QAAU,EAAQA,EAAK,OAC9B,CAYA,SACEC,EACiE,CACjE,MAAMC,EAAe,KAAK,iBAAiBD,CAAW,EACtD,OAAO,KAAK,yBAAyBC,CAAY,CACnD,CAEU,yBACRA,EAOiE,CACjE,MAAMC,KAAQ,eAAYD,EAAc,CACtC,MAAO,KAAK,KAGd,CAAC,EAQKE,EAAU,IAAI,gBAIdC,EACJC,GACG,CACH,KAAM,CAAE,QAAAC,EAAS,OAAAC,EAAQ,OAAAC,EAAQ,MAAAC,CAAM,EAAIJ,EAC3C,OAAQE,EAAQ,CACd,IAAK,SACHJ,EAAQ,KAAK,CACX,OAAQ,qBAAmB,QAC3B,kBAAmBG,EAAQ,iBAC7B,CAAC,EACD,MACF,IAAK,OACHE,EAAO,OAAO,CACZ,KAAOE,GAAQ,CACbP,EAAQ,KAAK,CACX,OAAQ,qBAAmB,MAC3B,MAAOO,CACT,CAAC,CACH,EACA,MAAQC,GAAW,CACjBR,EAAQ,KAAK,CACX,OAAQ,qBAAmB,UAC3B,OAAQQ,CACV,CAAC,CACH,CACF,CAAC,EACDR,EAAQ,SAAS,EACjB,MACF,IAAK,QAEHA,EAAQ,MAAMM,CAAK,EACnBN,EAAQ,SAAS,EACjB,MACF,IAAK,UACHA,EAAQ,KAAK,CACX,OAAQ,qBAAmB,OAC7B,CAAC,EACDA,EAAQ,SAAS,EACjB,MACF,QACE,KAAK,yBAAyBI,CAAM,CACxC,CACF,EAEMK,EAAa,IAAI,aAEpBC,GAAe,CAChB,MAAMC,EAAsBX,EAAQ,UAAUU,CAAU,EACxD,MAAO,IAAM,CACXE,EAAkB,YAAY,EAC9BD,EAAoB,YAAY,EAChCZ,EAAM,KAAK,CACb,CACF,CAAC,EAEKa,EAAoBb,EAAM,UAAUE,CAAmB,EAC7D,OAAAF,EAAM,MAAM,EAEL,CACL,WAAYU,EAAW,QAAK,SAAM,CAAC,EACnC,OAAQ,IAAM,CACZV,EAAM,KAAK,EACXa,EAAkB,YAAY,EAC9BX,EAAoBF,EAAM,YAAY,CAAC,CACzC,CACF,CACF,CAEQ,yBAAyBK,EAAsB,CACrD,cAAQ,IAAI,kCAAmCA,CAAM,EAC/C,IAAI,MAAM,qBAAqBA,CAAM,EAAE,CAC/C,CACF",
|
6
6
|
"names": ["XStateDeviceAction_exports", "__export", "XStateDeviceAction", "__toCommonJS", "import_rxjs", "import_xstate", "import_DeviceActionState", "args", "internalApi", "stateMachine", "actor", "subject", "handleActorSnapshot", "snapshot", "context", "status", "output", "error", "err", "result", "observable", "subscriber", "subjectSubscription", "actorSubscription"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var l=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var I=(o,e,d)=>e in o?l(o,e,{enumerable:!0,configurable:!0,writable:!0,value:d}):o[e]=d;var a=(o,e)=>{for(var d in e)l(o,d,{get:e[d],enumerable:!0})},x=(o,e,d,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of f(e))!y.call(o,r)&&r!==d&&l(o,r,{get:()=>e[r],enumerable:!(t=m(e,r))||t.enumerable});return o};var N=o=>x(l({},"__esModule",{value:!0}),o),b=(o,e,d,t)=>{for(var r=t>1?void 0:t?m(e,d):e,c=o.length-1,n;c>=0;c--)(n=o[c])&&(r=(t?n(e,d,r):n(r))||r);return t&&r&&l(e,d,r),r};var v=(o,e,d)=>I(o,typeof e!="symbol"?e+"":e,d);var P={};a(P,{StaticDeviceModelDataSource:()=>s});module.exports=N(P);var U=require("inversify"),i=require("../../device/DeviceModel"),p=require("../../device-model/model/BleDeviceInfos"),u=require("../../device-model/model/DeviceModel");let s=class{getAllDeviceModels(){return Object.values(s.deviceModelByIds)}getDeviceModel(e){return s.deviceModelByIds[e.id]}filterDeviceModels(e){return this.getAllDeviceModels().filter(d=>Object.entries(e).every(([t,r])=>d[t]===r))}getBluetoothServicesInfos(){return Object.values(s.deviceModelByIds).reduce((e,d)=>{const{bluetoothSpec:t}=d;return t?{...e,...t.reduce((r,c)=>({...r,[c.serviceUuid]:new p.BleDeviceInfos(d,c.serviceUuid,c.writeUuid,c.writeCmdUuid,c.notifyUuid)}),{})}:e},{})}getBluetoothServices(){return Object.values(s.deviceModelByIds).map(e=>(e.bluetoothSpec||[]).map(d=>d.serviceUuid)).flat().filter(e=>!!e)}};v(s,"deviceModelByIds",{[i.DeviceModelId.
|
1
|
+
"use strict";var l=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var y=Object.prototype.hasOwnProperty;var I=(o,e,d)=>e in o?l(o,e,{enumerable:!0,configurable:!0,writable:!0,value:d}):o[e]=d;var a=(o,e)=>{for(var d in e)l(o,d,{get:e[d],enumerable:!0})},x=(o,e,d,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of f(e))!y.call(o,r)&&r!==d&&l(o,r,{get:()=>e[r],enumerable:!(t=m(e,r))||t.enumerable});return o};var N=o=>x(l({},"__esModule",{value:!0}),o),b=(o,e,d,t)=>{for(var r=t>1?void 0:t?m(e,d):e,c=o.length-1,n;c>=0;c--)(n=o[c])&&(r=(t?n(e,d,r):n(r))||r);return t&&r&&l(e,d,r),r};var v=(o,e,d)=>I(o,typeof e!="symbol"?e+"":e,d);var P={};a(P,{StaticDeviceModelDataSource:()=>s});module.exports=N(P);var U=require("inversify"),i=require("../../device/DeviceModel"),p=require("../../device-model/model/BleDeviceInfos"),u=require("../../device-model/model/DeviceModel");let s=class{getAllDeviceModels(){return Object.values(s.deviceModelByIds)}getDeviceModel(e){return s.deviceModelByIds[e.id]}filterDeviceModels(e){return this.getAllDeviceModels().filter(d=>Object.entries(e).every(([t,r])=>d[t]===r))}getBluetoothServicesInfos(){return Object.values(s.deviceModelByIds).reduce((e,d)=>{const{bluetoothSpec:t}=d;return t?{...e,...t.reduce((r,c)=>({...r,[c.serviceUuid]:new p.BleDeviceInfos(d,c.serviceUuid,c.writeUuid,c.writeCmdUuid,c.notifyUuid)}),{})}:e},{})}getBluetoothServices(){return Object.values(s.deviceModelByIds).map(e=>(e.bluetoothSpec||[]).map(d=>d.serviceUuid)).flat().filter(e=>!!e)}};v(s,"deviceModelByIds",{[i.DeviceModelId.NANO_S]:new u.TransportDeviceModel({id:i.DeviceModelId.NANO_S,productName:"Ledger Nano S",usbProductId:16,bootloaderUsbProductId:1,usbOnly:!0,memorySize:320*1024,blockSize:4*1024,masks:[823132160]}),[i.DeviceModelId.NANO_SP]:new u.TransportDeviceModel({id:i.DeviceModelId.NANO_SP,productName:"Ledger Nano S Plus",usbProductId:80,bootloaderUsbProductId:5,usbOnly:!0,memorySize:1533*1024,blockSize:32,masks:[856686592]}),[i.DeviceModelId.NANO_X]:new u.TransportDeviceModel({id:i.DeviceModelId.NANO_X,productName:"Ledger Nano X",usbProductId:64,bootloaderUsbProductId:4,usbOnly:!1,memorySize:2*1024*1024,blockSize:4*1024,masks:[855638016],bluetoothSpec:[{serviceUuid:"13d63400-2c97-0004-0000-4c6564676572",notifyUuid:"13d63400-2c97-0004-0001-4c6564676572",writeUuid:"13d63400-2c97-0004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-0004-0003-4c6564676572"}]}),[i.DeviceModelId.STAX]:new u.TransportDeviceModel({id:i.DeviceModelId.STAX,productName:"Ledger Stax",usbProductId:96,bootloaderUsbProductId:6,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[857735168],bluetoothSpec:[{serviceUuid:"13d63400-2c97-6004-0000-4c6564676572",notifyUuid:"13d63400-2c97-6004-0001-4c6564676572",writeUuid:"13d63400-2c97-6004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-6004-0003-4c6564676572"}]}),[i.DeviceModelId.FLEX]:new u.TransportDeviceModel({id:i.DeviceModelId.FLEX,productName:"Ledger Flex",usbProductId:112,bootloaderUsbProductId:7,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[858783744],bluetoothSpec:[{serviceUuid:"13d63400-2c97-3004-0000-4c6564676572",notifyUuid:"13d63400-2c97-3004-0001-4c6564676572",writeUuid:"13d63400-2c97-3004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-3004-0003-4c6564676572"}]}),[i.DeviceModelId.APEX]:new u.TransportDeviceModel({id:i.DeviceModelId.APEX,productName:"Ledger Apex",usbProductId:128,bootloaderUsbProductId:8,usbOnly:!1,memorySize:1533*1024,blockSize:32,masks:[859832320],bluetoothSpec:[{serviceUuid:"13d63400-2c97-8004-0000-4c6564676572",notifyUuid:"13d63400-2c97-8004-0001-4c6564676572",writeUuid:"13d63400-2c97-8004-0002-4c6564676572",writeCmdUuid:"13d63400-2c97-8004-0003-4c6564676572"}]})}),s=b([(0,U.injectable)()],s);0&&(module.exports={StaticDeviceModelDataSource});
|
2
2
|
//# sourceMappingURL=StaticDeviceModelDataSource.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/api/device-model/data/StaticDeviceModelDataSource.ts"],
|
4
|
-
"sourcesContent": ["import { injectable } from \"inversify\";\n\nimport { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { DeviceModelDataSource } from \"@api/device-model/data/DeviceModelDataSource\";\nimport { BleDeviceInfos } from \"@api/device-model/model/BleDeviceInfos\";\nimport { TransportDeviceModel } from \"@api/device-model/model/DeviceModel\";\n\n/**\n * Static/in memory implementation of the device model data source\n */\n@injectable()\nexport class StaticDeviceModelDataSource implements DeviceModelDataSource {\n private static deviceModelByIds: {\n [_key in DeviceModelId]: TransportDeviceModel;\n } = {\n [DeviceModelId.
|
5
|
-
"mappings": "mrBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAA2B,qBAE3BC,EAA8B,mCAE9BC,EAA+B,kDAC/BD,EAAqC,+CAM9B,IAAME,EAAN,KAAmE,CAkGxE,oBAA6C,CAC3C,OAAO,OAAO,OAAOA,EAA4B,gBAAgB,CACnE,CAEA,eAAeC,EAAqD,CAClE,OAAOD,EAA4B,iBAAiBC,EAAO,EAAE,CAC/D,CAKA,mBACEA,EACwB,CACxB,OAAO,KAAK,mBAAmB,EAAE,OAAQC,GAChC,OAAO,QAAQD,CAAM,EAAE,MAAM,CAAC,CAACE,EAAKC,CAAK,IACvCF,EAAYC,CAAiC,IAAMC,CAC3D,CACF,CACH,CAEA,2BAA4D,CAC1D,OAAO,OAAO,OAAOJ,EAA4B,gBAAgB,EAAE,OAEjE,CAACK,EAAKH,IAAgB,CACtB,KAAM,CAAE,cAAAI,CAAc,EAAIJ,EAC1B,OAAII,EACK,CACL,GAAGD,EACH,GAAGC,EAAc,OACf,CAACC,EAAgBC,KAAa,CAC5B,GAAGD,EACH,CAACC,EAAQ,WAAW,EAAG,IAAI,iBACzBN,EACAM,EAAQ,YACRA,EAAQ,UACRA,EAAQ,aACRA,EAAQ,UACV,CACF,GACA,CAAC,CACH,CACF,EAEKH,CACT,EAAG,CAAC,CAAC,CACP,CAEA,sBAAiC,CAC/B,OAAO,OAAO,OAAOL,EAA4B,gBAAgB,EAC9D,IAAKE,IACHA,EAAY,eAAiB,CAAC,GAAG,IAAKO,GAASA,EAAK,WAAW,CAClE,EACC,KAAK,EACL,OAAQC,GAAS,CAAC,CAACA,CAAI,CAC5B,CACF,EAzJEC,EADWX,EACI,mBAEX,CACF,CAAC,gBAAc,
|
4
|
+
"sourcesContent": ["import { injectable } from \"inversify\";\n\nimport { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { DeviceModelDataSource } from \"@api/device-model/data/DeviceModelDataSource\";\nimport { BleDeviceInfos } from \"@api/device-model/model/BleDeviceInfos\";\nimport { TransportDeviceModel } from \"@api/device-model/model/DeviceModel\";\n\n/**\n * Static/in memory implementation of the device model data source\n */\n@injectable()\nexport class StaticDeviceModelDataSource implements DeviceModelDataSource {\n private static deviceModelByIds: {\n [_key in DeviceModelId]: TransportDeviceModel;\n } = {\n [DeviceModelId.NANO_S]: new TransportDeviceModel({\n id: DeviceModelId.NANO_S,\n productName: \"Ledger Nano S\",\n usbProductId: 0x10,\n bootloaderUsbProductId: 0x0001,\n usbOnly: true,\n memorySize: 320 * 1024,\n blockSize: 4 * 1024,\n masks: [0x31100000],\n }),\n [DeviceModelId.NANO_SP]: new TransportDeviceModel({\n id: DeviceModelId.NANO_SP,\n productName: \"Ledger Nano S Plus\",\n usbProductId: 0x50,\n bootloaderUsbProductId: 0x0005,\n usbOnly: true,\n memorySize: 1533 * 1024,\n blockSize: 32,\n masks: [0x33100000],\n }),\n [DeviceModelId.NANO_X]: new TransportDeviceModel({\n id: DeviceModelId.NANO_X,\n productName: \"Ledger Nano X\",\n usbProductId: 0x40,\n bootloaderUsbProductId: 0x0004,\n usbOnly: false,\n memorySize: 2 * 1024 * 1024,\n blockSize: 4 * 1024,\n masks: [0x33000000],\n bluetoothSpec: [\n {\n serviceUuid: \"13d63400-2c97-0004-0000-4c6564676572\",\n notifyUuid: \"13d63400-2c97-0004-0001-4c6564676572\",\n writeUuid: \"13d63400-2c97-0004-0002-4c6564676572\",\n writeCmdUuid: \"13d63400-2c97-0004-0003-4c6564676572\",\n },\n ],\n }),\n [DeviceModelId.STAX]: new TransportDeviceModel({\n id: DeviceModelId.STAX,\n productName: \"Ledger Stax\",\n usbProductId: 0x60,\n bootloaderUsbProductId: 0x0006,\n usbOnly: false,\n memorySize: 1533 * 1024,\n blockSize: 32,\n masks: [0x33200000],\n bluetoothSpec: [\n {\n serviceUuid: \"13d63400-2c97-6004-0000-4c6564676572\",\n notifyUuid: \"13d63400-2c97-6004-0001-4c6564676572\",\n writeUuid: \"13d63400-2c97-6004-0002-4c6564676572\",\n writeCmdUuid: \"13d63400-2c97-6004-0003-4c6564676572\",\n },\n ],\n }),\n [DeviceModelId.FLEX]: new TransportDeviceModel({\n id: DeviceModelId.FLEX,\n productName: \"Ledger Flex\",\n usbProductId: 0x70,\n bootloaderUsbProductId: 0x0007,\n usbOnly: false,\n memorySize: 1533 * 1024,\n blockSize: 32,\n masks: [0x33300000],\n bluetoothSpec: [\n {\n serviceUuid: \"13d63400-2c97-3004-0000-4c6564676572\",\n notifyUuid: \"13d63400-2c97-3004-0001-4c6564676572\",\n writeUuid: \"13d63400-2c97-3004-0002-4c6564676572\",\n writeCmdUuid: \"13d63400-2c97-3004-0003-4c6564676572\",\n },\n ],\n }),\n [DeviceModelId.APEX]: new TransportDeviceModel({\n id: DeviceModelId.APEX,\n productName: \"Ledger Apex\",\n usbProductId: 0x80,\n bootloaderUsbProductId: 0x0008,\n usbOnly: false,\n memorySize: 1533 * 1024,\n blockSize: 32,\n masks: [0x33400000],\n bluetoothSpec: [\n {\n serviceUuid: \"13d63400-2c97-8004-0000-4c6564676572\",\n notifyUuid: \"13d63400-2c97-8004-0001-4c6564676572\",\n writeUuid: \"13d63400-2c97-8004-0002-4c6564676572\",\n writeCmdUuid: \"13d63400-2c97-8004-0003-4c6564676572\",\n },\n ],\n }),\n };\n\n getAllDeviceModels(): TransportDeviceModel[] {\n return Object.values(StaticDeviceModelDataSource.deviceModelByIds);\n }\n\n getDeviceModel(params: { id: DeviceModelId }): TransportDeviceModel {\n return StaticDeviceModelDataSource.deviceModelByIds[params.id];\n }\n\n /**\n * Returns the list of device models that match all the given parameters\n */\n filterDeviceModels(\n params: Partial<TransportDeviceModel>,\n ): TransportDeviceModel[] {\n return this.getAllDeviceModels().filter((deviceModel) => {\n return Object.entries(params).every(([key, value]) => {\n return deviceModel[key as keyof TransportDeviceModel] === value;\n });\n });\n }\n\n getBluetoothServicesInfos(): Record<string, BleDeviceInfos> {\n return Object.values(StaticDeviceModelDataSource.deviceModelByIds).reduce<\n Record<string, BleDeviceInfos>\n >((acc, deviceModel) => {\n const { bluetoothSpec } = deviceModel;\n if (bluetoothSpec) {\n return {\n ...acc,\n ...bluetoothSpec.reduce<Record<string, BleDeviceInfos>>(\n (serviceToModel, bleSpec) => ({\n ...serviceToModel,\n [bleSpec.serviceUuid]: new BleDeviceInfos(\n deviceModel,\n bleSpec.serviceUuid,\n bleSpec.writeUuid,\n bleSpec.writeCmdUuid,\n bleSpec.notifyUuid,\n ),\n }),\n {},\n ),\n };\n }\n return acc;\n }, {});\n }\n\n getBluetoothServices(): string[] {\n return Object.values(StaticDeviceModelDataSource.deviceModelByIds)\n .map((deviceModel) =>\n (deviceModel.bluetoothSpec || []).map((spec) => spec.serviceUuid),\n )\n .flat()\n .filter((uuid) => !!uuid);\n }\n}\n"],
|
5
|
+
"mappings": "mrBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAA2B,qBAE3BC,EAA8B,mCAE9BC,EAA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wB,EACxB,QAAS,GACT,WAAY,KAAO,KACnB,UAAW,GACX,MAAO,CAAC,SAAU,CACpB,CAAC,EACD,CAAC,gBAAc,MAAM,EAAG,IAAI,uBAAqB,CAC/C,GAAI,gBAAc,OAClB,YAAa,gBACb,aAAc,GACd,uBAAwB,EACxB,QAAS,GACT,WAAY,EAAI,KAAO,KACvB,UAAW,EAAI,KACf,MAAO,CAAC,SAAU,EAClB,cAAe,CACb,CACE,YAAa,uCACb,WAAY,uCACZ,UAAW,uCACX,aAAc,sCAChB,CACF,CACF,CAAC,EACD,CAAC,gBAAc,IAAI,EAAG,IAAI,uBAAqB,CAC7C,GAAI,gBAAc,KAClB,YAAa,cACb,aAAc,GACd,uBAAwB,EACxB,QAAS,GACT,WAAY,KAAO,KACnB,UAAW,GACX,MAAO,CAAC,SAAU,EAClB,cAAe,CACb,CACE,YAAa,uCACb,WAAY,uCACZ,UAAW,uCACX,aAAc,sCAChB,CACF,CACF,CAAC,EACD,CAAC,gBAAc,IAAI,EAAG,IAAI,uBAAqB,CAC7C,GAAI,gBAAc,KAClB,YAAa,cACb,aAAc,IACd,uBAAwB,EACxB,QAAS,GACT,WAAY,KAAO,KACnB,UAAW,GACX,MAAO,CAAC,SAAU,EAClB,cAAe,CACb,CACE,YAAa,uCACb,WAAY,uCACZ,UAAW,uCACX,aAAc,sCAChB,CACF,CACF,CAAC,EACD,CAAC,gBAAc,IAAI,EAAG,IAAI,uBAAqB,CAC7C,GAAI,gBAAc,KAClB,YAAa,cACb,aAAc,IACd,uBAAwB,EACxB,QAAS,GACT,WAAY,KAAO,KACnB,UAAW,GACX,MAAO,CAAC,SAAU,EAClB,cAAe,CACb,CACE,YAAa,uCACb,WAAY,uCACZ,UAAW,uCACX,aAAc,sCAChB,CACF,CACF,CAAC,CACH,GAhGWA,EAANY,EAAA,IADN,cAAW,GACCZ",
|
6
6
|
"names": ["StaticDeviceModelDataSource_exports", "__export", "StaticDeviceModelDataSource", "__toCommonJS", "import_inversify", "import_DeviceModel", "import_BleDeviceInfos", "StaticDeviceModelDataSource", "params", "deviceModel", "key", "value", "acc", "bluetoothSpec", "serviceToModel", "bleSpec", "spec", "uuid", "__publicField", "__decorateClass"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var e=require("../../device/DeviceModel"),
|
1
|
+
"use strict";var e=require("../../device/DeviceModel"),n=require("../../device-model/model/BleDeviceInfos"),i=require("./StaticDeviceModelDataSource");describe("StaticDeviceModelDataSource",()=>{describe("getAllDeviceModels",()=>{it("should return all device models",()=>{const c=new i.StaticDeviceModelDataSource().getAllDeviceModels();expect(c.length).toEqual(6),expect(c).toContainEqual(expect.objectContaining({id:e.DeviceModelId.APEX})),expect(c).toContainEqual(expect.objectContaining({id:e.DeviceModelId.NANO_S})),expect(c).toContainEqual(expect.objectContaining({id:e.DeviceModelId.NANO_SP})),expect(c).toContainEqual(expect.objectContaining({id:e.DeviceModelId.NANO_X})),expect(c).toContainEqual(expect.objectContaining({id:e.DeviceModelId.STAX})),expect(c).toContainEqual(expect.objectContaining({id:e.DeviceModelId.FLEX}))})}),describe("getDeviceModel",()=>{it("should return the associated device model",()=>{const t=new i.StaticDeviceModelDataSource,c=t.getDeviceModel({id:e.DeviceModelId.NANO_S});expect(c).toEqual(expect.objectContaining({id:e.DeviceModelId.NANO_S}));const o=t.getDeviceModel({id:e.DeviceModelId.NANO_SP});expect(o).toEqual(expect.objectContaining({id:e.DeviceModelId.NANO_SP}));const d=t.getDeviceModel({id:e.DeviceModelId.NANO_X});expect(d).toEqual(expect.objectContaining({id:e.DeviceModelId.NANO_X}));const l=t.getDeviceModel({id:e.DeviceModelId.STAX});expect(l).toEqual(expect.objectContaining({id:e.DeviceModelId.STAX}));const a=t.getDeviceModel({id:e.DeviceModelId.FLEX});expect(a).toEqual(expect.objectContaining({id:e.DeviceModelId.FLEX}))})}),describe("filterDeviceModels",()=>{it("should return the device models that match the given single parameter",()=>{const t=new i.StaticDeviceModelDataSource,c=t.filterDeviceModels({usbOnly:!0});expect(c.length).toEqual(2),expect(c).toContainEqual(expect.objectContaining({id:e.DeviceModelId.NANO_SP})),expect(c).toContainEqual(expect.objectContaining({id:e.DeviceModelId.NANO_S}));const o=t.filterDeviceModels({usbProductId:16});expect(o.length).toEqual(1),expect(o[0]).toEqual(expect.objectContaining({id:e.DeviceModelId.NANO_S}));const d=t.filterDeviceModels({usbProductId:64});expect(d.length).toEqual(1),expect(d[0]).toEqual(expect.objectContaining({id:e.DeviceModelId.NANO_X}));const l=t.filterDeviceModels({usbProductId:80});expect(l.length).toEqual(1),expect(l[0]).toEqual(expect.objectContaining({id:e.DeviceModelId.NANO_SP}));const a=t.filterDeviceModels({usbProductId:96});expect(a.length).toEqual(1),expect(a[0]).toEqual(expect.objectContaining({id:e.DeviceModelId.STAX}));const s=t.filterDeviceModels({usbProductId:0});expect(s.length).toEqual(0)}),it("should return the device models that match the given multiple parameters",()=>{const t=new i.StaticDeviceModelDataSource,c=t.filterDeviceModels({usbOnly:!1,usbProductId:64});expect(c.length).toEqual(1),expect(c[0]).toEqual(expect.objectContaining({id:e.DeviceModelId.NANO_X}));const o=t.filterDeviceModels({usbOnly:!0,usbProductId:80});expect(o.length).toEqual(1),expect(o[0]).toEqual(expect.objectContaining({id:e.DeviceModelId.NANO_SP}));const d=t.filterDeviceModels({usbOnly:!1,usbProductId:16});expect(d.length).toEqual(0)})}),describe("getBluetoothServicesInfos",()=>{it("should return the ble service infos record",()=>{const t=new i.StaticDeviceModelDataSource,c=t.getBluetoothServicesInfos();expect(c).toStrictEqual({"13d63400-2c97-0004-0000-4c6564676572":new n.BleDeviceInfos(t.getDeviceModel({id:e.DeviceModelId.NANO_X}),"13d63400-2c97-0004-0000-4c6564676572","13d63400-2c97-0004-0002-4c6564676572","13d63400-2c97-0004-0003-4c6564676572","13d63400-2c97-0004-0001-4c6564676572"),"13d63400-2c97-6004-0000-4c6564676572":new n.BleDeviceInfos(t.getDeviceModel({id:e.DeviceModelId.STAX}),"13d63400-2c97-6004-0000-4c6564676572","13d63400-2c97-6004-0002-4c6564676572","13d63400-2c97-6004-0003-4c6564676572","13d63400-2c97-6004-0001-4c6564676572"),"13d63400-2c97-3004-0000-4c6564676572":new n.BleDeviceInfos(t.getDeviceModel({id:e.DeviceModelId.FLEX}),"13d63400-2c97-3004-0000-4c6564676572","13d63400-2c97-3004-0002-4c6564676572","13d63400-2c97-3004-0003-4c6564676572","13d63400-2c97-3004-0001-4c6564676572"),"13d63400-2c97-8004-0000-4c6564676572":new n.BleDeviceInfos(t.getDeviceModel({id:e.DeviceModelId.APEX}),"13d63400-2c97-8004-0000-4c6564676572","13d63400-2c97-8004-0002-4c6564676572","13d63400-2c97-8004-0003-4c6564676572","13d63400-2c97-8004-0001-4c6564676572")})})}),describe("getBluetoothServices",()=>{it("should return the bluetooth services",()=>{const c=new i.StaticDeviceModelDataSource().getBluetoothServices();expect(c).toStrictEqual(["13d63400-2c97-0004-0000-4c6564676572","13d63400-2c97-6004-0000-4c6564676572","13d63400-2c97-3004-0000-4c6564676572","13d63400-2c97-8004-0000-4c6564676572"])})})});
|
2
2
|
//# sourceMappingURL=StaticDeviceModelDataSource.test.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/api/device-model/data/StaticDeviceModelDataSource.test.ts"],
|
4
|
-
"sourcesContent": ["import { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { BleDeviceInfos } from \"@api/device-model/model/BleDeviceInfos\";\n\nimport { StaticDeviceModelDataSource } from \"./StaticDeviceModelDataSource\";\n\ndescribe(\"StaticDeviceModelDataSource\", () => {\n describe(\"getAllDeviceModels\", () => {\n it(\"should return all device models\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n const deviceModels = dataSource.getAllDeviceModels();\n\n expect(deviceModels.length).toEqual(6);\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.APEX }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.FLEX }),\n );\n });\n });\n\n describe(\"getDeviceModel\", () => {\n it(\"should return the associated device model\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModel1 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n });\n expect(deviceModel1).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModel2 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_SP,\n });\n expect(deviceModel2).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n const deviceModel3 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_X,\n });\n expect(deviceModel3).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModel4 = dataSource.getDeviceModel({\n id: DeviceModelId.STAX,\n });\n expect(deviceModel4).toEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n\n const deviceModel5 = dataSource.getDeviceModel({\n id: DeviceModelId.FLEX,\n });\n expect(deviceModel5).toEqual(\n expect.objectContaining({ id: DeviceModelId.FLEX }),\n );\n });\n });\n\n describe(\"filterDeviceModels\", () => {\n it(\"should return the device models that match the given single parameter\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModels1 = dataSource.filterDeviceModels({ usbOnly: true });\n expect(deviceModels1.length).toEqual(2);\n expect(deviceModels1).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n expect(deviceModels1).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModels2 = dataSource.filterDeviceModels({\n usbProductId: 0x10,\n });\n expect(deviceModels2.length).toEqual(1);\n expect(deviceModels2[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModels3 = dataSource.filterDeviceModels({\n usbProductId: 0x40,\n });\n expect(deviceModels3.length).toEqual(1);\n expect(deviceModels3[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModels4 = dataSource.filterDeviceModels({\n usbProductId: 0x50,\n });\n expect(deviceModels4.length).toEqual(1);\n expect(deviceModels4[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n const deviceModels5 = dataSource.filterDeviceModels({\n usbProductId: 0x60,\n });\n expect(deviceModels5.length).toEqual(1);\n expect(deviceModels5[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n\n const deviceModels6 = dataSource.filterDeviceModels({\n usbProductId: 0x00,\n });\n expect(deviceModels6.length).toEqual(0);\n });\n\n it(\"should return the device models that match the given multiple parameters\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModels1 = dataSource.filterDeviceModels({\n usbOnly: false,\n usbProductId: 0x40,\n });\n expect(deviceModels1.length).toEqual(1);\n expect(deviceModels1[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModels2 = dataSource.filterDeviceModels({\n usbOnly: true,\n usbProductId: 0x50,\n });\n expect(deviceModels2.length).toEqual(1);\n expect(deviceModels2[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n // Nano S is usbOnly\n const deviceModels3 = dataSource.filterDeviceModels({\n usbOnly: false,\n usbProductId: 0x10,\n });\n expect(deviceModels3.length).toEqual(0);\n });\n });\n describe(\"getBluetoothServicesInfos\", () => {\n it(\"should return the ble service infos record\", () => {\n // given\n const dataSource = new StaticDeviceModelDataSource();\n // when\n const bleServiceInfos = dataSource.getBluetoothServicesInfos();\n // then\n expect(bleServiceInfos).toStrictEqual({\n \"13d63400-2c97-0004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.NANO_X }),\n \"13d63400-2c97-0004-0000-4c6564676572\",\n \"13d63400-2c97-0004-0002-4c6564676572\",\n \"13d63400-2c97-0004-0003-4c6564676572\",\n \"13d63400-2c97-0004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-6004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.STAX }),\n \"13d63400-2c97-6004-0000-4c6564676572\",\n \"13d63400-2c97-6004-0002-4c6564676572\",\n \"13d63400-2c97-6004-0003-4c6564676572\",\n \"13d63400-2c97-6004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-3004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.FLEX }),\n \"13d63400-2c97-3004-0000-4c6564676572\",\n \"13d63400-2c97-3004-0002-4c6564676572\",\n \"13d63400-2c97-3004-0003-4c6564676572\",\n \"13d63400-2c97-3004-0001-4c6564676572\",\n ),\n });\n });\n });\n describe(\"getBluetoothServices\", () => {\n it(\"should return the bluetooth services\", () => {\n // given\n const dataSource = new StaticDeviceModelDataSource();\n // when\n const bleServices = dataSource.getBluetoothServices();\n // then\n expect(bleServices).toStrictEqual([\n \"13d63400-2c97-
|
5
|
-
"mappings": "aAAA,IAAAA,EAA8B,mCAC9BC,EAA+B,kDAE/BC,EAA4C,yCAE5C,SAAS,8BAA+B,IAAM,CAC5C,SAAS,qBAAsB,IAAM,CACnC,GAAG,kCAAmC,IAAM,CAE1C,MAAMC,EADa,IAAI,8BAA4B,EACnB,mBAAmB,EAEnD,OAAOA,EAAa,MAAM,EAAE,QAAQ,CAAC,EACrC,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,IAAK,CAAC,CACpD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,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CACA,uCACA,uCACA,sCACF,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
|
4
|
+
"sourcesContent": ["import { DeviceModelId } from \"@api/device/DeviceModel\";\nimport { BleDeviceInfos } from \"@api/device-model/model/BleDeviceInfos\";\n\nimport { StaticDeviceModelDataSource } from \"./StaticDeviceModelDataSource\";\n\ndescribe(\"StaticDeviceModelDataSource\", () => {\n describe(\"getAllDeviceModels\", () => {\n it(\"should return all device models\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n const deviceModels = dataSource.getAllDeviceModels();\n\n expect(deviceModels.length).toEqual(6);\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.APEX }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n expect(deviceModels).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.FLEX }),\n );\n });\n });\n\n describe(\"getDeviceModel\", () => {\n it(\"should return the associated device model\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModel1 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_S,\n });\n expect(deviceModel1).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModel2 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_SP,\n });\n expect(deviceModel2).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n const deviceModel3 = dataSource.getDeviceModel({\n id: DeviceModelId.NANO_X,\n });\n expect(deviceModel3).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModel4 = dataSource.getDeviceModel({\n id: DeviceModelId.STAX,\n });\n expect(deviceModel4).toEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n\n const deviceModel5 = dataSource.getDeviceModel({\n id: DeviceModelId.FLEX,\n });\n expect(deviceModel5).toEqual(\n expect.objectContaining({ id: DeviceModelId.FLEX }),\n );\n });\n });\n\n describe(\"filterDeviceModels\", () => {\n it(\"should return the device models that match the given single parameter\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModels1 = dataSource.filterDeviceModels({ usbOnly: true });\n expect(deviceModels1.length).toEqual(2);\n expect(deviceModels1).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n expect(deviceModels1).toContainEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModels2 = dataSource.filterDeviceModels({\n usbProductId: 0x10,\n });\n expect(deviceModels2.length).toEqual(1);\n expect(deviceModels2[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_S }),\n );\n\n const deviceModels3 = dataSource.filterDeviceModels({\n usbProductId: 0x40,\n });\n expect(deviceModels3.length).toEqual(1);\n expect(deviceModels3[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModels4 = dataSource.filterDeviceModels({\n usbProductId: 0x50,\n });\n expect(deviceModels4.length).toEqual(1);\n expect(deviceModels4[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n const deviceModels5 = dataSource.filterDeviceModels({\n usbProductId: 0x60,\n });\n expect(deviceModels5.length).toEqual(1);\n expect(deviceModels5[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.STAX }),\n );\n\n const deviceModels6 = dataSource.filterDeviceModels({\n usbProductId: 0x00,\n });\n expect(deviceModels6.length).toEqual(0);\n });\n\n it(\"should return the device models that match the given multiple parameters\", () => {\n const dataSource = new StaticDeviceModelDataSource();\n\n const deviceModels1 = dataSource.filterDeviceModels({\n usbOnly: false,\n usbProductId: 0x40,\n });\n expect(deviceModels1.length).toEqual(1);\n expect(deviceModels1[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_X }),\n );\n\n const deviceModels2 = dataSource.filterDeviceModels({\n usbOnly: true,\n usbProductId: 0x50,\n });\n expect(deviceModels2.length).toEqual(1);\n expect(deviceModels2[0]).toEqual(\n expect.objectContaining({ id: DeviceModelId.NANO_SP }),\n );\n\n // Nano S is usbOnly\n const deviceModels3 = dataSource.filterDeviceModels({\n usbOnly: false,\n usbProductId: 0x10,\n });\n expect(deviceModels3.length).toEqual(0);\n });\n });\n describe(\"getBluetoothServicesInfos\", () => {\n it(\"should return the ble service infos record\", () => {\n // given\n const dataSource = new StaticDeviceModelDataSource();\n // when\n const bleServiceInfos = dataSource.getBluetoothServicesInfos();\n // then\n expect(bleServiceInfos).toStrictEqual({\n \"13d63400-2c97-0004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.NANO_X }),\n \"13d63400-2c97-0004-0000-4c6564676572\",\n \"13d63400-2c97-0004-0002-4c6564676572\",\n \"13d63400-2c97-0004-0003-4c6564676572\",\n \"13d63400-2c97-0004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-6004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.STAX }),\n \"13d63400-2c97-6004-0000-4c6564676572\",\n \"13d63400-2c97-6004-0002-4c6564676572\",\n \"13d63400-2c97-6004-0003-4c6564676572\",\n \"13d63400-2c97-6004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-3004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.FLEX }),\n \"13d63400-2c97-3004-0000-4c6564676572\",\n \"13d63400-2c97-3004-0002-4c6564676572\",\n \"13d63400-2c97-3004-0003-4c6564676572\",\n \"13d63400-2c97-3004-0001-4c6564676572\",\n ),\n \"13d63400-2c97-8004-0000-4c6564676572\": new BleDeviceInfos(\n dataSource.getDeviceModel({ id: DeviceModelId.APEX }),\n \"13d63400-2c97-8004-0000-4c6564676572\",\n \"13d63400-2c97-8004-0002-4c6564676572\",\n \"13d63400-2c97-8004-0003-4c6564676572\",\n \"13d63400-2c97-8004-0001-4c6564676572\",\n ),\n });\n });\n });\n describe(\"getBluetoothServices\", () => {\n it(\"should return the bluetooth services\", () => {\n // given\n const dataSource = new StaticDeviceModelDataSource();\n // when\n const bleServices = dataSource.getBluetoothServices();\n // then\n expect(bleServices).toStrictEqual([\n \"13d63400-2c97-0004-0000-4c6564676572\",\n \"13d63400-2c97-6004-0000-4c6564676572\",\n \"13d63400-2c97-3004-0000-4c6564676572\",\n \"13d63400-2c97-8004-0000-4c6564676572\",\n ]);\n });\n });\n});\n"],
|
5
|
+
"mappings": "aAAA,IAAAA,EAA8B,mCAC9BC,EAA+B,kDAE/BC,EAA4C,yCAE5C,SAAS,8BAA+B,IAAM,CAC5C,SAAS,qBAAsB,IAAM,CACnC,GAAG,kCAAmC,IAAM,CAE1C,MAAMC,EADa,IAAI,8BAA4B,EACnB,mBAAmB,EAEnD,OAAOA,EAAa,MAAM,EAAE,QAAQ,CAAC,EACrC,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,IAAK,CAAC,CACpD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,MAAO,CAAC,CACtD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,OAAQ,CAAC,CACvD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,MAAO,CAAC,CACtD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,IAAK,CAAC,CACpD,EACA,OAAOA,CAAY,EAAE,eACnB,OAAO,iBAAiB,CAAE,GAAI,gBAAc,IAAK,CAAC,CACpD,CACF,CAAC,CACH,CAAC,EAED,SAAS,iBAAkB,IAAM,CAC/B,GAAG,4CAA6C,IAA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,CAAE,GAAI,gBAAc,OAAQ,CAAC,CACvD,EAGA,MAAMC,EAAgBR,EAAW,mBAAmB,CAClD,QAAS,GACT,aAAc,EAChB,CAAC,EACD,OAAOQ,EAAc,MAAM,EAAE,QAAQ,CAAC,CACxC,CAAC,CACH,CAAC,EACD,SAAS,4BAA6B,IAAM,CAC1C,GAAG,6CAA8C,IAAM,CAErD,MAAMR,EAAa,IAAI,8BAEjBY,EAAkBZ,EAAW,0BAA0B,EAE7D,OAAOY,CAAe,EAAE,cAAc,CACpC,uCAAwC,IAAI,iBAC1CZ,EAAW,eAAe,CAAE,GAAI,gBAAc,MAAO,CAAC,EACtD,uCACA,uCACA,uCACA,sCACF,EACA,uCAAwC,IAAI,iBAC1CA,EAAW,eAAe,CAAE,GAAI,gBAAc,IAAK,CAAC,EACpD,uCACA,uCACA,uCACA,sCACF,EACA,uCAAwC,IAAI,iBAC1CA,EAAW,eAAe,CAAE,GAAI,gBAAc,IAAK,CAAC,EACpD,uCACA,uCACA,uCACA,sCACF,EACA,uCAAwC,IAAI,iBAC1CA,EAAW,eAAe,CAAE,GAAI,gBAAc,IAAK,CAAC,EACpD,uCACA,uCACA,uCACA,sCACF,CACF,CAAC,CACH,CAAC,CACH,CAAC,EACD,SAAS,uBAAwB,IAAM,CACrC,GAAG,uCAAwC,IAAM,CAI/C,MAAMa,EAFa,IAAI,8BAA4B,EAEpB,qBAAqB,EAEpD,OAAOA,CAAW,EAAE,cAAc,CAChC,uCACA,uCACA,uCACA,sCACF,CAAC,CACH,CAAC,CACH,CAAC,CACH,CAAC",
|
6
6
|
"names": ["import_DeviceModel", "import_BleDeviceInfos", "import_StaticDeviceModelDataSource", "deviceModels", "dataSource", "deviceModel1", "deviceModel2", "deviceModel3", "deviceModel4", "deviceModel5", "deviceModels1", "deviceModels2", "deviceModels3", "deviceModels4", "deviceModels5", "deviceModels6", "bleServiceInfos", "bleServices"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var R=Object.create;var E=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var U=(i,e)=>{for(var s in e)E(i,s,{get:e[s],enumerable:!0})},_=(i,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of O(e))!D.call(i,c)&&c!==s&&E(i,c,{get:()=>e[c],enumerable:!(r=T(e,c))||r.enumerable});return i};var N=(i,e,s)=>(s=i!=null?R(I(i)):{},_(e||!i||!i.__esModule?E(s,"default",{value:i,enumerable:!0}):s,i)),P=i=>_(E({},"__esModule",{value:!0}),i);var q={};U(q,{ConnectToSecureChannelTask:()=>W});module.exports=P(q);var A=N(require("isomorphic-ws")),x=require("rxjs"),g=require("../../command/utils/CommandUtils"),n=require("../../secure-channel/task/types"),M=require("../../secure-channel/utils"),m=require("../../utils/HexaString"),t=require("../../../internal/secure-channel/model/Errors");class W{constructor(e,s){this._api=e;this._args=s;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new t.SecureChannelError(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`)}_connection;run(){const e=this._api.disableRefresher("connectToSecureChannel");return new x.Observable(r=>{let c=!1,p=!1,v=!1;const l=y=>{r.next({type:n.SecureChannelEventType.Error,error:y}),r.complete(),p=!0};return this._connection.onopen=()=>{r.next({type:n.SecureChannelEventType.Opened})},this._connection.onerror=y=>{p||(r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:y.message})}),r.complete())},this._connection.onclose=()=>{p||(v?r.next({type:n.SecureChannelEventType.Closed}):r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),r.complete())},this._connection.onmessage=async y=>{if(c)return;let a;try{const o=JSON.parse(String(y.data));if(this.isInMessageType(o))a=o;else throw new Error("Data does not match InMessageType")}catch{l(new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid message received: ${String(y.data)}`}));return}switch(a.query){case n.InMessageQueryEnum.EXCHANGE:{const{nonce:o,data:d}=a;if(typeof d!="string"){l(new t.SecureChannelError(`${n.InMessageQueryEnum.EXCHANGE} data type should be an APDU`));return}const u=(0,m.hexaStringToBuffer)(d);if(u===null||u.length<5){l(new t.SecureChannelError(`Received invalid APDU data: ${d}`));return}r.next({type:n.SecureChannelEventType.PreExchange,payload:{nonce:o,apdu:u}});let f=!1;(0,M.willRequestPermission)(u)&&!this.isSecureConnectionAllowed()&&(f=!0,r.next({type:n.SecureChannelEventType.PermissionRequested}));const S=await this._api.sendApdu(u);if(c)return;S.caseOf({Left:h=>{l(new t.SecureChannelError(h))},Right:h=>{let C;const w=this.mapDeviceError(h);w===null?(C=n.OutMessageResponseEnum.SUCCESS,r.next({type:n.SecureChannelEventType.Exchange,payload:{nonce:o,apdu:u,data:h.data,status:h.statusCode}}),f&&r.next({type:n.SecureChannelEventType.PermissionGranted})):(C=n.OutMessageResponseEnum.ERROR,l(w));const k={nonce:o,response:C,data:(0,m.bufferToHexaString)(h.data)
|
1
|
+
"use strict";var R=Object.create;var E=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var I=Object.getPrototypeOf,D=Object.prototype.hasOwnProperty;var U=(i,e)=>{for(var s in e)E(i,s,{get:e[s],enumerable:!0})},_=(i,e,s,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of O(e))!D.call(i,c)&&c!==s&&E(i,c,{get:()=>e[c],enumerable:!(r=T(e,c))||r.enumerable});return i};var N=(i,e,s)=>(s=i!=null?R(I(i)):{},_(e||!i||!i.__esModule?E(s,"default",{value:i,enumerable:!0}):s,i)),P=i=>_(E({},"__esModule",{value:!0}),i);var q={};U(q,{ConnectToSecureChannelTask:()=>W});module.exports=P(q);var A=N(require("isomorphic-ws")),x=require("rxjs"),g=require("../../command/utils/CommandUtils"),n=require("../../secure-channel/task/types"),M=require("../../secure-channel/utils"),m=require("../../utils/HexaString"),t=require("../../../internal/secure-channel/model/Errors");class W{constructor(e,s){this._api=e;this._args=s;if(this._args.connection.isRight())this._connection=this._args.connection.extract();else throw new t.SecureChannelError(`Invalid WebSocket connection: ${String(this._args.connection.extract())}`)}_connection;run(){const e=this._api.disableRefresher("connectToSecureChannel");return new x.Observable(r=>{let c=!1,p=!1,v=!1;const l=y=>{r.next({type:n.SecureChannelEventType.Error,error:y}),r.complete(),p=!0};return this._connection.onopen=()=>{r.next({type:n.SecureChannelEventType.Opened})},this._connection.onerror=y=>{p||(r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:y.message})}),r.complete())},this._connection.onclose=()=>{p||(v?r.next({type:n.SecureChannelEventType.Closed}):r.next({type:n.SecureChannelEventType.Error,error:new t.SecureChannelError({url:this._connection.url,errorMessage:"Connection closed unexpectedly"})}),r.complete())},this._connection.onmessage=async y=>{if(c)return;let a;try{const o=JSON.parse(String(y.data));if(this.isInMessageType(o))a=o;else throw new Error("Data does not match InMessageType")}catch{l(new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid message received: ${String(y.data)}`}));return}switch(a.query){case n.InMessageQueryEnum.EXCHANGE:{const{nonce:o,data:d}=a;if(typeof d!="string"){l(new t.SecureChannelError(`${n.InMessageQueryEnum.EXCHANGE} data type should be an APDU`));return}const u=(0,m.hexaStringToBuffer)(d);if(u===null||u.length<5){l(new t.SecureChannelError(`Received invalid APDU data: ${d}`));return}r.next({type:n.SecureChannelEventType.PreExchange,payload:{nonce:o,apdu:u}});let f=!1;(0,M.willRequestPermission)(u)&&!this.isSecureConnectionAllowed()&&(f=!0,r.next({type:n.SecureChannelEventType.PermissionRequested}));const S=await this._api.sendApdu(u);if(c)return;S.caseOf({Left:h=>{l(new t.SecureChannelError(h))},Right:h=>{let C;const w=this.mapDeviceError(h);w===null?(C=n.OutMessageResponseEnum.SUCCESS,r.next({type:n.SecureChannelEventType.Exchange,payload:{nonce:o,apdu:u,data:h.data,status:h.statusCode}}),f&&r.next({type:n.SecureChannelEventType.PermissionGranted})):(C=n.OutMessageResponseEnum.ERROR,l(w));const k={nonce:o,response:C,data:(0,m.bufferToHexaString)(h.data,!1)};this._connection.send(JSON.stringify(k))}});break}case n.InMessageQueryEnum.BULK:{if(p=!0,this._connection.close(),!Array.isArray(a.data)||a.data.length===0||!a.data.every(o=>typeof o=="string")){l(new t.SecureChannelError("Invalid bulk data received"));return}for(let o=0,d=a.data.length;o<d;o++){const u=(0,m.hexaStringToBuffer)(a.data[o]);if(u===null||u.length<5){l(new t.SecureChannelError(`Received invalid APDU bulk data: ${a.data[o]}`));return}const f=await this._api.sendApdu(u);if(c)return;if(f.isLeft()){l(new t.SecureChannelError(f.extract()));return}else if(f.isRight()){const S=this.mapDeviceError(f.extract());if(S===null)r.next({type:n.SecureChannelEventType.Progress,payload:{progress:+Number((o+1)/d).toFixed(2),index:o,total:d}});else{l(S);return}}}v=!0,r.complete();break}case n.InMessageQueryEnum.SUCCESS:{if(p)break;const o=a.result??a.data;o&&r.next({type:n.SecureChannelEventType.Result,payload:o??""}),v=!0,r.complete();break}case n.InMessageQueryEnum.WARNING:{if(p)break;r.next({type:n.SecureChannelEventType.Warning,payload:{message:String(a.data)}});break}case n.InMessageQueryEnum.ERROR:{if(p)break;l(new t.SecureChannelError({url:this._connection.url,errorMessage:String(a.data)}))}}},()=>{e(),c=!0,this._connection.readyState===A.default.OPEN&&this._connection.close()}})}isSecureConnectionAllowed(){const e=this._api.getDeviceSessionState();return"isSecureConnectionAllowed"in e&&e.isSecureConnectionAllowed}isInMessageType(e){if(typeof e!="object"||!e)return!1;const s=e;return typeof s.uuid=="string"&&typeof s.session=="string"&&typeof s.query=="string"&&Object.values(n.InMessageQueryEnum).includes(s.query)&&typeof s.nonce=="number"}mapDeviceError(e){return g.CommandUtils.isSuccessResponse(e)?null:g.CommandUtils.isLockedDeviceResponse(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Device is locked"},t.SecureChannelErrorType.DeviceLocked):g.CommandUtils.isRefusedByUser(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"User refused on the device"},t.SecureChannelErrorType.RefusedByUser):g.CommandUtils.isAppAlreadyInstalled(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"App already installed"},t.SecureChannelErrorType.AppAlreadyInstalled):g.CommandUtils.isOutOfMemory(e)?new t.SecureChannelError({url:this._connection.url,errorMessage:"Out of memory"},t.SecureChannelErrorType.OutOfMemory):new t.SecureChannelError({url:this._connection.url,errorMessage:`Invalid status code: ${(0,m.bufferToHexaString)(e.statusCode)}`})}}0&&(module.exports={ConnectToSecureChannelTask});
|
2
2
|
//# sourceMappingURL=ConnectToSecureChannelTask.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/api/secure-channel/task/ConnectToSecureChannelTask.ts"],
|
4
|
-
"sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { willRequestPermission } from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data).slice(2),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
|
5
|
-
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAsB,4BAEtBC,EAA2B,gBAE3BC,EAA6B,2CAG7BC,EAOO,0CACPC,EAAsC,qCACtCC,EAAuD,iCACvDC,EAIO,iDAMA,MAAMR,CAA2B,CAEtC,YACmBS,EACAC,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AIzB,MAAMC,EAA0B,CAC9B,MAAAR,EACA,SAAUM,EACV,QAAM,sBAAmBD,EAAa,
|
4
|
+
"sourcesContent": ["import WebSocket from \"isomorphic-ws\";\nimport { type Either } from \"purify-ts\";\nimport { Observable } from \"rxjs\";\n\nimport { CommandUtils } from \"@api/command/utils/CommandUtils\";\nimport { type InternalApi } from \"@api/device-action/DeviceAction\";\nimport { type ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n InMessageQueryEnum,\n type InMessageType,\n OutMessageResponseEnum,\n type OutMessageType,\n type SecureChannelEvent,\n SecureChannelEventType,\n} from \"@api/secure-channel/task/types\";\nimport { willRequestPermission } from \"@api/secure-channel/utils\";\nimport { bufferToHexaString, hexaStringToBuffer } from \"@api/utils/HexaString\";\nimport {\n SecureChannelError,\n SecureChannelErrorType,\n type WebSocketConnectionError,\n} from \"@internal/secure-channel/model/Errors\";\n\nexport type ConnectToSecureChannelTaskArgs = {\n connection: Either<WebSocketConnectionError, WebSocket>;\n};\n\nexport class ConnectToSecureChannelTask {\n private readonly _connection: WebSocket;\n constructor(\n private readonly _api: InternalApi,\n private readonly _args: ConnectToSecureChannelTaskArgs,\n ) {\n if (this._args.connection.isRight()) {\n this._connection = this._args.connection.extract();\n } else {\n throw new SecureChannelError(\n `Invalid WebSocket connection: ${String(this._args.connection.extract())}`,\n );\n }\n }\n\n run(): Observable<SecureChannelEvent> {\n const reenableRefresher = this._api.disableRefresher(\n \"connectToSecureChannel\",\n );\n\n const obs = new Observable<SecureChannelEvent>((subscriber) => {\n let unsubscribed: boolean = false;\n let ignoreNetworkEvents = false;\n let communicationFinished = false;\n\n const notifyError = (error: SecureChannelError) => {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error,\n });\n subscriber.complete();\n\n // Netowrks events can be ignored once the obervable has been completed\n ignoreNetworkEvents = true;\n };\n\n this._connection.onopen = () => {\n subscriber.next({\n type: SecureChannelEventType.Opened,\n });\n };\n\n this._connection.onerror = (error) => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: error.message,\n }),\n });\n subscriber.complete();\n };\n\n this._connection.onclose = () => {\n if (ignoreNetworkEvents) {\n return;\n }\n\n if (communicationFinished) {\n subscriber.next({\n type: SecureChannelEventType.Closed,\n });\n } else {\n subscriber.next({\n type: SecureChannelEventType.Error,\n error: new SecureChannelError({\n url: this._connection.url,\n errorMessage: \"Connection closed unexpectedly\",\n }),\n });\n }\n subscriber.complete();\n };\n\n this._connection.onmessage = async (event) => {\n // When unsubscribed, ignore the message\n if (unsubscribed) {\n return;\n }\n\n // Parse input message\n let input: InMessageType;\n try {\n const jsonData = JSON.parse(String(event.data));\n if (this.isInMessageType(jsonData)) {\n input = jsonData;\n } else {\n throw new Error(\"Data does not match InMessageType\");\n }\n } catch (_) {\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid message received: ${String(event.data)}`,\n }),\n );\n return;\n }\n\n // Execute message query\n switch (input.query) {\n case InMessageQueryEnum.EXCHANGE: {\n const { nonce, data } = input;\n\n // Exchange query should contain a single APDU\n if (typeof data !== \"string\") {\n notifyError(\n new SecureChannelError(\n `${InMessageQueryEnum.EXCHANGE} data type should be an APDU`,\n ),\n );\n return;\n }\n\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(data);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(`Received invalid APDU data: ${data}`),\n );\n return;\n }\n subscriber.next({\n type: SecureChannelEventType.PreExchange,\n payload: { nonce, apdu },\n });\n\n // Notify permission requested\n let permissionRequested = false;\n if (\n willRequestPermission(apdu) &&\n !this.isSecureConnectionAllowed()\n ) {\n permissionRequested = true;\n subscriber.next({\n type: SecureChannelEventType.PermissionRequested,\n });\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n response.caseOf({\n Left: (error) => {\n notifyError(new SecureChannelError(error));\n },\n Right: (apduResponse: ApduResponse) => {\n let outMessageResponse: OutMessageResponseEnum;\n const deviceError = this.mapDeviceError(apduResponse);\n if (deviceError === null) {\n outMessageResponse = OutMessageResponseEnum.SUCCESS;\n\n // Emit event for the exchange\n subscriber.next({\n type: SecureChannelEventType.Exchange,\n payload: {\n nonce,\n apdu,\n data: apduResponse.data,\n status: apduResponse.statusCode,\n },\n });\n\n // If manager consent was requested, notify the \"granted\" event\n if (permissionRequested) {\n subscriber.next({\n type: SecureChannelEventType.PermissionGranted,\n });\n }\n } else {\n outMessageResponse = OutMessageResponseEnum.ERROR;\n notifyError(deviceError);\n }\n\n // Send the message back to the server\n const message: OutMessageType = {\n nonce,\n response: outMessageResponse,\n data: bufferToHexaString(apduResponse.data, false),\n };\n this._connection.send(JSON.stringify(message));\n },\n });\n break;\n }\n case InMessageQueryEnum.BULK: {\n // Network not needed anymore during bulk APDUs sending\n ignoreNetworkEvents = true;\n this._connection.close();\n\n // A valid array of APDUs is required in a bulk query\n if (\n !Array.isArray(input.data) ||\n input.data.length === 0 ||\n !input.data.every((data) => typeof data === \"string\")\n ) {\n notifyError(new SecureChannelError(\"Invalid bulk data received\"));\n return;\n }\n\n for (let i = 0, len = input.data.length; i < len; i++) {\n // APDU should be a valid hex string\n const apdu = hexaStringToBuffer(input.data[i]!);\n if (apdu === null || apdu.length < 5) {\n notifyError(\n new SecureChannelError(\n `Received invalid APDU bulk data: ${input.data[i]}`,\n ),\n );\n return;\n }\n\n // Send APDU to the device\n const response = await this._api.sendApdu(apdu);\n if (unsubscribed) {\n return;\n }\n\n // Map device response\n if (response.isLeft()) {\n notifyError(new SecureChannelError(response.extract()));\n return;\n } else if (response.isRight()) {\n const deviceError = this.mapDeviceError(response.extract());\n if (deviceError === null) {\n // Notify the progress\n subscriber.next({\n type: SecureChannelEventType.Progress,\n payload: {\n progress: +Number((i + 1) / len).toFixed(2),\n index: i,\n total: len,\n },\n });\n } else {\n notifyError(deviceError);\n return;\n }\n }\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.SUCCESS: {\n if (ignoreNetworkEvents) {\n break;\n }\n // Emit the result if there is any\n const payload = input.result ?? input.data;\n if (payload) {\n subscriber.next({\n type: SecureChannelEventType.Result,\n payload: payload ?? \"\",\n });\n }\n communicationFinished = true;\n subscriber.complete();\n break;\n }\n case InMessageQueryEnum.WARNING: {\n if (ignoreNetworkEvents) {\n break;\n }\n subscriber.next({\n type: SecureChannelEventType.Warning,\n payload: { message: String(input.data) },\n });\n break;\n }\n case InMessageQueryEnum.ERROR: {\n if (ignoreNetworkEvents) {\n break;\n }\n notifyError(\n new SecureChannelError({\n url: this._connection.url,\n errorMessage: String(input.data),\n }),\n );\n }\n }\n };\n\n return () => {\n reenableRefresher();\n unsubscribed = true;\n // Close the connection if it is open when unsubscribing\n if (this._connection.readyState === WebSocket.OPEN) {\n this._connection.close();\n }\n };\n });\n\n return obs;\n }\n\n /**\n * Determines if a secure connection is already allowed based on the current device session state.\n *\n * @returns {boolean} `true` if a secure connection is allowed, otherwise `false`.\n */\n isSecureConnectionAllowed(): boolean {\n const deviceSessionState = this._api.getDeviceSessionState();\n return (\n \"isSecureConnectionAllowed\" in deviceSessionState &&\n deviceSessionState.isSecureConnectionAllowed\n );\n }\n\n isInMessageType(data: unknown): data is InMessageType {\n if (typeof data !== \"object\" || !data) {\n return false;\n }\n\n const message = data as InMessageType;\n return (\n typeof message.uuid === \"string\" &&\n typeof message.session === \"string\" &&\n typeof message.query === \"string\" &&\n Object.values(InMessageQueryEnum).includes(message.query) &&\n typeof message.nonce === \"number\"\n );\n }\n\n mapDeviceError(apduResponse: ApduResponse): SecureChannelError | null {\n if (CommandUtils.isSuccessResponse(apduResponse)) {\n return null;\n }\n\n // Device is locked\n if (CommandUtils.isLockedDeviceResponse(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: `Device is locked`,\n },\n SecureChannelErrorType.DeviceLocked,\n );\n }\n\n // User refused the permission\n if (CommandUtils.isRefusedByUser(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"User refused on the device\",\n },\n SecureChannelErrorType.RefusedByUser,\n );\n }\n\n // App already installed\n if (CommandUtils.isAppAlreadyInstalled(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"App already installed\",\n },\n SecureChannelErrorType.AppAlreadyInstalled,\n );\n }\n\n // Out of memory\n if (CommandUtils.isOutOfMemory(apduResponse)) {\n return new SecureChannelError(\n {\n url: this._connection.url,\n errorMessage: \"Out of memory\",\n },\n SecureChannelErrorType.OutOfMemory,\n );\n }\n\n return new SecureChannelError({\n url: this._connection.url,\n errorMessage: `Invalid status code: ${bufferToHexaString(\n apduResponse.statusCode,\n )}`,\n });\n }\n}\n"],
|
5
|
+
"mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAsB,4BAEtBC,EAA2B,gBAE3BC,EAA6B,2CAG7BC,EAOO,0CACPC,EAAsC,qCACtCC,EAAuD,iCACvDC,EAIO,iDAMA,MAAMR,CAA2B,CAEtC,YACmBS,EACAC,EACjB,CAFiB,UAAAD,EACA,WAAAC,EAEjB,GAAI,KAAK,MAAM,WAAW,QAAQ,EAChC,KAAK,YAAc,KAAK,MAAM,WAAW,QAAQ,MAEjD,OAAM,IAAI,qBACR,iCAAiC,OAAO,KAAK,MAAM,WAAW,QAAQ,CAAC,CAAC,EAC1E,CAEJ,CAZiB,YAcjB,KAAsC,CACpC,MAAMC,EAAoB,KAAK,KAAK,iBAClC,wBACF,EA4RA,OA1RY,IAAI,aAAgCC,GAAe,CAC7D,IAAIC,EAAwB,GACxBC,EAAsB,GACtBC,EAAwB,GAE5B,MAAMC,EAAeC,GAA8B,CACjDL,EAAW,KAAK,CACd,KAAM,yBAAuB,MAC7B,MAAAK,CACF,CAAC,EACDL,EAAW,SAAS,EAGpB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EO,IAAM,CACXR,EAAkB,EAClBE,EAAe,GAEX,KAAK,YAAY,aAAe,EAAAoB,QAAU,MAC5C,KAAK,YAAY,MAAM,CAE3B,CACF,CAAC,CAGH,CAOA,2BAAqC,CACnC,MAAMC,EAAqB,KAAK,KAAK,sBAAsB,EAC3D,MACE,8BAA+BA,GAC/BA,EAAmB,yBAEvB,CAEA,gBAAgBZ,EAAsC,CACpD,GAAI,OAAOA,GAAS,UAAY,CAACA,EAC/B,MAAO,GAGT,MAAMO,EAAUP,EAChB,OACE,OAAOO,EAAQ,MAAS,UACxB,OAAOA,EAAQ,SAAY,UAC3B,OAAOA,EAAQ,OAAU,UACzB,OAAO,OAAO,oBAAkB,EAAE,SAASA,EAAQ,KAAK,GACxD,OAAOA,EAAQ,OAAU,QAE7B,CAEA,eAAeH,EAAuD,CACpE,OAAI,eAAa,kBAAkBA,CAAY,EACtC,KAIL,eAAa,uBAAuBA,CAAY,EAC3C,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,kBAChB,EACA,yBAAuB,YACzB,EAIE,eAAa,gBAAgBA,CAAY,EACpC,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,4BAChB,EACA,yBAAuB,aACzB,EAIE,eAAa,sBAAsBA,CAAY,EAC1C,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,uBAChB,EACA,yBAAuB,mBACzB,EAIE,eAAa,cAAcA,CAAY,EAClC,IAAI,qBACT,CACE,IAAK,KAAK,YAAY,IACtB,aAAc,eAChB,EACA,yBAAuB,WACzB,EAGK,IAAI,qBAAmB,CAC5B,IAAK,KAAK,YAAY,IACtB,aAAc,2BAAwB,sBACpCA,EAAa,UACf,CAAC,EACH,CAAC,CACH,CACF",
|
6
6
|
"names": ["ConnectToSecureChannelTask_exports", "__export", "ConnectToSecureChannelTask", "__toCommonJS", "import_isomorphic_ws", "import_rxjs", "import_CommandUtils", "import_types", "import_utils", "import_HexaString", "import_Errors", "_api", "_args", "reenableRefresher", "subscriber", "unsubscribed", "ignoreNetworkEvents", "communicationFinished", "notifyError", "error", "event", "input", "jsonData", "nonce", "data", "apdu", "permissionRequested", "response", "apduResponse", "outMessageResponse", "deviceError", "message", "i", "len", "payload", "WebSocket", "deviceSessionState"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var
|
1
|
+
"use strict";var f=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var a=Object.prototype.hasOwnProperty;var s=(r,t)=>{for(var n in t)f(r,n,{get:t[n],enumerable:!0})},g=(r,t,n,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of x(t))!a.call(r,i)&&i!==n&&f(r,i,{get:()=>t[i],enumerable:!(e=o(t,i))||e.enumerable});return r};var u=r=>g(f({},"__esModule",{value:!0}),r);var c={};s(c,{bufferToHexaString:()=>y,hexaStringToBuffer:()=>S,isHexaString:()=>p});module.exports=u(c);function p(r){return typeof r=="string"&&/^0x[0-9a-fA-F]*$/.test(r)}function S(r){if(r.startsWith("0x")&&(r=r.slice(2)),r.length===0)return new Uint8Array;if(r.length%2!==0&&(r="0"+r),/^[0-9a-fA-F]*$/.test(r)===!1)return null;const t=r.match(/.{1,2}/g)?.map(n=>parseInt(n,16));return!t||t.some(isNaN)?null:new Uint8Array(t)}function y(r,t=!0){return`${t?"0x":""}${Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}`}0&&(module.exports={bufferToHexaString,hexaStringToBuffer,isHexaString});
|
2
2
|
//# sourceMappingURL=HexaString.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../src/api/utils/HexaString.ts"],
|
4
|
-
"sourcesContent": ["export type HexaString = `0x${string}`;\n\nexport
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,uBAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAL,GAEO,
|
6
|
-
"names": ["HexaString_exports", "__export", "bufferToHexaString", "hexaStringToBuffer", "isHexaString", "__toCommonJS", "value", "bytes", "byte"]
|
4
|
+
"sourcesContent": ["export type HexaString = `0x${string}`;\n\nexport function isHexaString(value: unknown): value is HexaString {\n return typeof value === \"string\" && /^0x[0-9a-fA-F]*$/.test(value);\n}\n\nexport function hexaStringToBuffer(value: string): Uint8Array | null {\n if (value.startsWith(\"0x\")) {\n value = value.slice(2);\n }\n if (value.length === 0) {\n return new Uint8Array();\n }\n if (value.length % 2 !== 0) {\n value = \"0\" + value;\n }\n if (/^[0-9a-fA-F]*$/.test(value) === false) {\n return null;\n }\n const bytes = value.match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16));\n if (!bytes || bytes.some(isNaN)) {\n return null;\n }\n return new Uint8Array(bytes);\n}\n\nexport function bufferToHexaString(\n value: Uint8Array,\n withPrefix?: true,\n): HexaString;\nexport function bufferToHexaString(\n value: Uint8Array,\n withPrefix?: false,\n): string;\nexport function bufferToHexaString(\n value: Uint8Array,\n withPrefix: boolean = true,\n): HexaString | string {\n const prefix = withPrefix ? \"0x\" : \"\";\n return `${prefix}${Array.from(value, (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\")}`;\n}\n"],
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,wBAAAE,EAAA,uBAAAC,EAAA,iBAAAC,IAAA,eAAAC,EAAAL,GAEO,SAASI,EAAaE,EAAqC,CAChE,OAAO,OAAOA,GAAU,UAAY,mBAAmB,KAAKA,CAAK,CACnE,CAEO,SAASH,EAAmBG,EAAkC,CAInE,GAHIA,EAAM,WAAW,IAAI,IACvBA,EAAQA,EAAM,MAAM,CAAC,GAEnBA,EAAM,SAAW,EACnB,OAAO,IAAI,WAKb,GAHIA,EAAM,OAAS,IAAM,IACvBA,EAAQ,IAAMA,GAEZ,iBAAiB,KAAKA,CAAK,IAAM,GACnC,OAAO,KAET,MAAMC,EAAQD,EAAM,MAAM,SAAS,GAAG,IAAKE,GAAS,SAASA,EAAM,EAAE,CAAC,EACtE,MAAI,CAACD,GAASA,EAAM,KAAK,KAAK,EACrB,KAEF,IAAI,WAAWA,CAAK,CAC7B,CAUO,SAASL,EACdI,EACAG,EAAsB,GACD,CAErB,MAAO,GADQA,EAAa,KAAO,EACnB,GAAG,MAAM,KAAKH,EAAQE,GACpCA,EAAK,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CACnC,EAAE,KAAK,EAAE,CAAC,EACZ",
|
6
|
+
"names": ["HexaString_exports", "__export", "bufferToHexaString", "hexaStringToBuffer", "isHexaString", "__toCommonJS", "value", "bytes", "byte", "withPrefix"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var e=require("./HexaString");describe("HexaString",()=>{describe("isHexaString function",()=>{it("should return true if the value is a valid hex string",()=>{const t=(0,e.isHexaString)("0x1234abc");expect(t).toBeTruthy()}),it("should return true if no data",()=>{const t=(0,e.isHexaString)("0x");expect(t).toBeTruthy()}),it("should return false if the value contain an invalid letter",()=>{const t=(0,e.isHexaString)("0x1234z");expect(t).toBeFalsy()}),it("should return false if the value does not start with 0x",()=>{const t=(0,e.isHexaString)("1234abc");expect(t).toBeFalsy()}),it("should return false for an epmty string",()=>{const t=(0,e.isHexaString)("");expect(t).toBeFalsy()}),it.each([123,[],{},null,void 0,!0])("should return false for invalid input %p",
|
1
|
+
"use strict";var e=require("./HexaString");describe("HexaString",()=>{describe("isHexaString function",()=>{it("should return true if the value is a valid hex string",()=>{const t=(0,e.isHexaString)("0x1234abc");expect(t).toBeTruthy()}),it("should return true if no data",()=>{const t=(0,e.isHexaString)("0x");expect(t).toBeTruthy()}),it("should return false if the value contain an invalid letter",()=>{const t=(0,e.isHexaString)("0x1234z");expect(t).toBeFalsy()}),it("should return false if the value does not start with 0x",()=>{const t=(0,e.isHexaString)("1234abc");expect(t).toBeFalsy()}),it("should return false for an epmty string",()=>{const t=(0,e.isHexaString)("");expect(t).toBeFalsy()}),it.each([123,[],{},null,void 0,!0])("should return false for invalid input %p",r=>{const t=(0,e.isHexaString)(r);expect(t).toBeFalsy()})}),describe("hexaStringToBuffer function",()=>{it("should convert empty input to empty buffer",()=>{const t=(0,e.hexaStringToBuffer)("");expect(t).toStrictEqual(new Uint8Array)}),it("should fail on invalid string",()=>{const t=(0,e.hexaStringToBuffer)("bonjour");expect(t).toStrictEqual(null)}),it("should fail on invalid string with valid numbers",()=>{const t=(0,e.hexaStringToBuffer)("0x012n34");expect(t).toStrictEqual(null)}),it("should convert correct hexadecimal string",()=>{const t=(0,e.hexaStringToBuffer)("1a35669f0100");expect(t).toStrictEqual(new Uint8Array([26,53,102,159,1,0]))}),it("should support 0x prefix",()=>{const t=(0,e.hexaStringToBuffer)("0x1a35");expect(t).toStrictEqual(new Uint8Array([26,53]))}),it("should be case insensitive",()=>{const t=(0,e.hexaStringToBuffer)("0xcCDd");expect(t).toStrictEqual(new Uint8Array([204,221]))}),it("should pad with 0",()=>{const t=(0,e.hexaStringToBuffer)("0xa35");expect(t).toStrictEqual(new Uint8Array([10,53]))})}),describe("bufferToHexaString function",()=>{it("should convert a buffer into a hexa string",()=>{const r=Uint8Array.from([0,1,2,255,254]),t=(0,e.bufferToHexaString)(r);expect(t).toStrictEqual("0x000102fffe")}),it("should convert a buffer into a hexa string without prefix",()=>{const r=Uint8Array.from([0,1,2,255,254]),t=(0,e.bufferToHexaString)(r,!1);expect(t).toStrictEqual("000102fffe")})})});
|
2
2
|
//# sourceMappingURL=HexaString.test.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../src/api/utils/HexaString.test.ts"],
|
4
|
-
"sourcesContent": ["import {\n bufferToHexaString,\n hexaStringToBuffer,\n isHexaString,\n} from \"./HexaString\";\n\ndescribe(\"HexaString\", () => {\n describe(\"isHexaString function\", () => {\n it(\"should return true if the value is a valid hex string\", () => {\n // GIVEN\n const value = \"0x1234abc\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeTruthy();\n });\n\n it(\"should return true if no data\", () => {\n // GIVEN\n const value = \"0x\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeTruthy();\n });\n\n it(\"should return false if the value contain an invalid letter\", () => {\n // GIVEN\n const value = \"0x1234z\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it(\"should return false if the value does not start with 0x\", () => {\n // GIVEN\n const value = \"1234abc\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it(\"should return false for an epmty string\", () => {\n // GIVEN\n const value = \"\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it.each([123, [], {}, null, undefined, true])(\n \"should return false for invalid input %p\",\n (value) => {\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n },\n );\n });\n\n describe(\"hexaStringToBuffer function\", () => {\n it(\"should convert empty input to empty buffer\", () => {\n // GIVEN\n const value = \"\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array());\n });\n\n it(\"should fail on invalid string\", () => {\n // GIVEN\n const value = \"bonjour\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(null);\n });\n\n it(\"should fail on invalid string with valid numbers\", () => {\n // GIVEN\n const value = \"0x012n34\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(null);\n });\n\n it(\"should convert correct hexadecimal string\", () => {\n // GIVEN\n const value = \"1a35669f0100\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(\n new Uint8Array([0x1a, 0x35, 0x66, 0x9f, 0x01, 0x00]),\n );\n });\n\n it(\"should support 0x prefix\", () => {\n // GIVEN\n const value = \"0x1a35\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0x1a, 0x35]));\n });\n\n it(\"should be case insensitive\", () => {\n // GIVEN\n const value = \"0xcCDd\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0xcc, 0xdd]));\n });\n\n it(\"should pad with 0\", () => {\n // GIVEN\n const value = \"0xa35\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0x0a, 0x35]));\n });\n });\n\n describe(\"bufferToHexaString function\", () => {\n it(\"should convert a buffer into a hexa string\", () => {\n // GIVEN\n const value = Uint8Array.from([0, 1, 2, 0xff, 0xfe]);\n\n // WHEN\n const result = bufferToHexaString(value);\n\n // THEN\n expect(result).toStrictEqual(\"0x000102fffe\");\n });\n });\n});\n"],
|
5
|
-
"mappings": "aAAA,IAAAA,EAIO,wBAEP,SAAS,aAAc,IAAM,CAC3B,SAAS,wBAAyB,IAAM,CACtC,GAAG,wDAAyD,IAAM,CAKhE,MAAMC,KAAS,gBAHD,WAGmB,EAGjC,OAAOA,CAAM,EAAE,WAAW,CAC5B,CAAC,EAED,GAAG,gCAAiC,IAAM,CAKxC,MAAMA,KAAS,gBAHD,IAGmB,EAGjC,OAAOA,CAAM,EAAE,WAAW,CAC5B,CAAC,EAED,GAAG,6DAA8D,IAAM,CAKrE,MAAMA,KAAS,gBAHD,SAGmB,EAGjC,OAAOA,CAAM,EAAE,UAAU,CAC3B,CAAC,EAED,GAAG,0DAA2D,IAAM,CAKlE,MAAMA,KAAS,gBAHD,SAGmB,EAGjC,OAAOA,CAAM,EAAE,UAAU,CAC3B,CAAC,EAED,GAAG,0CAA2C,IAAM,CAKlD,MAAMA,KAAS,gBAHD,EAGmB,EAGjC,OAAOA,CAAM,EAAE,UAAU,CAC3B,CAAC,EAED,GAAG,KAAK,C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AAW,KAAK,CAAC,EAAG,EAAG,EAAG,IAAM,GAAI,CAAC,EAG7CD,KAAS,sBAAmBC,CAAK,EAGvC,OAAOD,CAAM,EAAE,cAAc,cAAc,CAC7C,CAAC,CACH,CAAC,CACH,CAAC",
|
4
|
+
"sourcesContent": ["import {\n bufferToHexaString,\n hexaStringToBuffer,\n isHexaString,\n} from \"./HexaString\";\n\ndescribe(\"HexaString\", () => {\n describe(\"isHexaString function\", () => {\n it(\"should return true if the value is a valid hex string\", () => {\n // GIVEN\n const value = \"0x1234abc\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeTruthy();\n });\n\n it(\"should return true if no data\", () => {\n // GIVEN\n const value = \"0x\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeTruthy();\n });\n\n it(\"should return false if the value contain an invalid letter\", () => {\n // GIVEN\n const value = \"0x1234z\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it(\"should return false if the value does not start with 0x\", () => {\n // GIVEN\n const value = \"1234abc\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it(\"should return false for an epmty string\", () => {\n // GIVEN\n const value = \"\";\n\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n });\n\n it.each([123, [], {}, null, undefined, true])(\n \"should return false for invalid input %p\",\n (value) => {\n // WHEN\n const result = isHexaString(value);\n\n // THEN\n expect(result).toBeFalsy();\n },\n );\n });\n\n describe(\"hexaStringToBuffer function\", () => {\n it(\"should convert empty input to empty buffer\", () => {\n // GIVEN\n const value = \"\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array());\n });\n\n it(\"should fail on invalid string\", () => {\n // GIVEN\n const value = \"bonjour\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(null);\n });\n\n it(\"should fail on invalid string with valid numbers\", () => {\n // GIVEN\n const value = \"0x012n34\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(null);\n });\n\n it(\"should convert correct hexadecimal string\", () => {\n // GIVEN\n const value = \"1a35669f0100\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(\n new Uint8Array([0x1a, 0x35, 0x66, 0x9f, 0x01, 0x00]),\n );\n });\n\n it(\"should support 0x prefix\", () => {\n // GIVEN\n const value = \"0x1a35\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0x1a, 0x35]));\n });\n\n it(\"should be case insensitive\", () => {\n // GIVEN\n const value = \"0xcCDd\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0xcc, 0xdd]));\n });\n\n it(\"should pad with 0\", () => {\n // GIVEN\n const value = \"0xa35\";\n\n // WHEN\n const result = hexaStringToBuffer(value);\n\n // THEN\n expect(result).toStrictEqual(new Uint8Array([0x0a, 0x35]));\n });\n });\n\n describe(\"bufferToHexaString function\", () => {\n it(\"should convert a buffer into a hexa string\", () => {\n // GIVEN\n const value = Uint8Array.from([0, 1, 2, 0xff, 0xfe]);\n\n // WHEN\n const result = bufferToHexaString(value);\n\n // THEN\n expect(result).toStrictEqual(\"0x000102fffe\");\n });\n\n it(\"should convert a buffer into a hexa string without prefix\", () => {\n // GIVEN\n const value = Uint8Array.from([0, 1, 2, 0xff, 0xfe]);\n\n // WHEN\n const result = bufferToHexaString(value, false);\n\n // THEN\n expect(result).toStrictEqual(\"000102fffe\");\n });\n });\n});\n"],
|
5
|
+
"mappings": "aAAA,IAAAA,EAIO,wBAEP,SAAS,aAAc,IAAM,CAC3B,SAAS,wBAAyB,IAAM,CACtC,GAAG,wDAAyD,IAAM,CAKhE,MAAMC,KAAS,gBAHD,WAGmB,EAGjC,OAAOA,CA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,EAGvC,OAAOA,CAAM,EAAE,cAAc,IAAI,WAAW,CAAC,GAAM,EAAI,CAAC,CAAC,CAC3D,CAAC,EAED,GAAG,6BAA8B,IAAM,CAKrC,MAAMA,KAAS,sBAHD,QAGyB,EAGvC,OAAOA,CAAM,EAAE,cAAc,IAAI,WAAW,CAAC,IAAM,GAAI,CAAC,CAAC,CAC3D,CAAC,EAED,GAAG,oBAAqB,IAAM,CAK5B,MAAMA,KAAS,sBAHD,OAGyB,EAGvC,OAAOA,CAAM,EAAE,cAAc,IAAI,WAAW,CAAC,GAAM,EAAI,CAAC,CAAC,CAC3D,CAAC,CACH,CAAC,EAED,SAAS,8BAA+B,IAAM,CAC5C,GAAG,6CAA8C,IAAM,CAErD,MAAMC,EAAQ,WAAW,KAAK,CAAC,EAAG,EAAG,EAAG,IAAM,GAAI,CAAC,EAG7CD,KAAS,sBAAmBC,CAAK,EAGvC,OAAOD,CAAM,EAAE,cAAc,cAAc,CAC7C,CAAC,EAED,GAAG,4DAA6D,IAAM,CAEpE,MAAMC,EAAQ,WAAW,KAAK,CAAC,EAAG,EAAG,EAAG,IAAM,GAAI,CAAC,EAG7CD,KAAS,sBAAmBC,EAAO,EAAK,EAG9C,OAAOD,CAAM,EAAE,cAAc,YAAY,CAC3C,CAAC,CACH,CAAC,CACH,CAAC",
|
6
6
|
"names": ["import_HexaString", "result", "value"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var p=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var D=(o,e)=>{for(var r in e)p(o,r,{get:e[r],enumerable:!0})},G=(o,e,r,
|
1
|
+
"use strict";var p=Object.defineProperty;var F=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var C=Object.prototype.hasOwnProperty;var D=(o,e)=>{for(var r in e)p(o,r,{get:e[r],enumerable:!0})},G=(o,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of H(e))!C.call(o,t)&&t!==r&&p(o,t,{get:()=>e[t],enumerable:!(n=F(e,t))||n.enumerable});return o};var P=o=>G(p({},"__esModule",{value:!0}),o),_=(o,e,r,n)=>{for(var t=n>1?void 0:n?F(e,r):e,s=o.length-1,m;s>=0;s--)(m=o[s])&&(t=(n?m(e,r,t):m(t))||t);return n&&t&&p(e,r,t),t},A=(o,e)=>(r,n)=>e(r,n,o);var z={};D(z,{DefaultApduReceiverService:()=>c});module.exports=P(z);var d=require("inversify"),a=require("purify-ts"),f=require("uuid"),y=require("../../../api/device-session/ApduResponse"),i=require("../../../api/device-session/data/FramerConst"),h=require("../../../api/device-session/utils/FramerUtils"),l=require("../../device-session/data/ApduResponseConst"),u=require("../../device-session/model/Errors"),v=require("../../device-session/model/Frame"),E=require("../../device-session/model/FrameHeader"),L=require("../../logger-publisher/di/loggerTypes");let c=class{_channel;_logger;_pendingFrames;constructor({channel:e=a.Maybe.zero()},r){this._channel=e,this._logger=r("ApduReceiverService"),this._pendingFrames=[]}handleFrame(e){return this.getFrameFromBytes(e).map(n=>{if(this._pendingFrames.push(n),!this._pendingFrames[0])return a.Nothing;const t=this._pendingFrames[0].getHeader().getDataLength();return this.getCompleteFrame(t)})}getCompleteFrame(e){return e.chain(r=>{if(!this.isComplete(r))return this._logger.debug("frame is not complete, waiting for more"),a.Nothing;const n=h.FramerUtils.getFirstBytesFrom(this.concatFrames(this._pendingFrames),r),t=h.FramerUtils.getFirstBytesFrom(n,n.length-l.APDU_RESPONSE_STATUS_CODE_LENGTH),s=h.FramerUtils.getLastBytesFrom(n,l.APDU_RESPONSE_STATUS_CODE_LENGTH);return this._pendingFrames=[],(0,a.Just)(new y.ApduResponse({data:t,statusCode:s}))})}getFrameFromBytes(e){const r=this._channel.caseOf({Just:()=>i.CHANNEL_LENGTH,Nothing:()=>0}),n=e.slice(r,r+i.HEAD_TAG_LENGTH),t=e.slice(r+i.HEAD_TAG_LENGTH,r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH),s=t.reduce((T,U)=>T+U,0)===0;if(!s&&this._pendingFrames.length===0)return(0,a.Left)(new u.ReceiverApduError);const m=r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH,g=s?i.APDU_DATA_LENGTH_LENGTH:0;if(e.length<r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH+g)return(0,a.Left)(new u.ReceiverApduError("Unable to parse header from apdu"));const b=s?(0,a.Just)(e.slice(m,m+g)):a.Nothing,S=m+g,N=e.slice(S),R=new v.Frame({header:new E.FrameHeader({uuid:(0,f.v4)(),channel:this._channel,dataSize:b,headTag:n,index:t,length:r+i.HEAD_TAG_LENGTH+i.INDEX_LENGTH+g}),data:N});return(0,a.Right)(R)}isComplete(e){return this._pendingFrames.reduce((n,t)=>n+t.getData().length,0)>=e}concatFrames(e){return e.reduce((r,n)=>Uint8Array.from([...r,...n.getData()]),new Uint8Array(0))}};c=_([(0,d.injectable)(),A(1,(0,d.inject)(L.loggerTypes.LoggerPublisherServiceFactory))],c);0&&(module.exports={DefaultApduReceiverService});
|
2
2
|
//# sourceMappingURL=DefaultApduReceiverService.js.map
|
@@ -1,7 +1,7 @@
|
|
1
1
|
{
|
2
2
|
"version": 3,
|
3
3
|
"sources": ["../../../../../../src/internal/device-session/service/DefaultApduReceiverService.ts"],
|
4
|
-
"sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Either, Just, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { v4 } from \"uuid\";\n\nimport { ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n APDU_DATA_LENGTH_LENGTH,\n CHANNEL_LENGTH,\n HEAD_TAG_LENGTH,\n INDEX_LENGTH,\n} from \"@api/device-session/data/FramerConst\";\nimport {\n type ApduReceiverConstructorArgs,\n ApduReceiverService,\n} from \"@api/device-session/service/ApduReceiverService\";\nimport { FramerUtils } from \"@api/device-session/utils/FramerUtils\";\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { APDU_RESPONSE_STATUS_CODE_LENGTH } from \"@internal/device-session/data/ApduResponseConst\";\nimport { ReceiverApduError } from \"@internal/device-session/model/Errors\";\nimport { Frame } from \"@internal/device-session/model/Frame\";\nimport { FrameHeader } from \"@internal/device-session/model/FrameHeader\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n@injectable()\nexport class DefaultApduReceiverService implements ApduReceiverService {\n private readonly _channel: Maybe<Uint8Array>;\n private readonly _logger: LoggerPublisherService;\n private _pendingFrames: Frame[];\n\n constructor(\n { channel = Maybe.zero() }: ApduReceiverConstructorArgs,\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._channel = channel;\n this._logger = loggerModuleFactory(\"ApduReceiverService\");\n this._pendingFrames = [];\n }\n\n /*\n * Return\n * - A complete ApduResponse\n * - Or a Nothing if not all the data has been received\n * - Or a ReceiverApduError if the apdu is not formatted correctly\n *\n * @param Uint8Array\n */\n public handleFrame(\n frameBytes: Uint8Array,\n ): Either<ReceiverApduError, Maybe<ApduResponse>> {\n const frame = this.getFrameFromBytes(frameBytes);\n\n return frame.map((value) => {\n this.
|
5
|
-
"mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBACnCC,EAA0D,qBAC1DC,EAAmB,gBAEnBC,EAA6B,4CAC7BC,EAKO,gDAKPC,EAA4B,iDAE5BC,EAAiD,2DACjDC,EAAkC,iDAClCC,EAAsB,gDACtBC,EAA4B,sDAC5BC,EAA4B,qDAGrB,IAAMC,EAAN,KAAgE,CACpD,SACA,QACT,eAER,YACE,CAAE,QAAAC,EAAU,QAAM,KAAK,CAAE,EAEzBC,EACA,CACA,KAAK,SAAWD,EAChB,KAAK,QAAUC,EAAoB,qBAAqB,EACxD,KAAK,eAAiB,CAAC,CACzB,CAUO,YACLC,EACgD,CAGhD,OAFc,KAAK,kBAAkBA,CAAU,EAElC,IAAKC,GAAU,
|
4
|
+
"sourcesContent": ["import { inject, injectable } from \"inversify\";\nimport { Either, Just, Left, Maybe, Nothing, Right } from \"purify-ts\";\nimport { v4 } from \"uuid\";\n\nimport { ApduResponse } from \"@api/device-session/ApduResponse\";\nimport {\n APDU_DATA_LENGTH_LENGTH,\n CHANNEL_LENGTH,\n HEAD_TAG_LENGTH,\n INDEX_LENGTH,\n} from \"@api/device-session/data/FramerConst\";\nimport {\n type ApduReceiverConstructorArgs,\n ApduReceiverService,\n} from \"@api/device-session/service/ApduReceiverService\";\nimport { FramerUtils } from \"@api/device-session/utils/FramerUtils\";\nimport { LoggerPublisherService } from \"@api/logger-publisher/service/LoggerPublisherService\";\nimport { APDU_RESPONSE_STATUS_CODE_LENGTH } from \"@internal/device-session/data/ApduResponseConst\";\nimport { ReceiverApduError } from \"@internal/device-session/model/Errors\";\nimport { Frame } from \"@internal/device-session/model/Frame\";\nimport { FrameHeader } from \"@internal/device-session/model/FrameHeader\";\nimport { loggerTypes } from \"@internal/logger-publisher/di/loggerTypes\";\n\n@injectable()\nexport class DefaultApduReceiverService implements ApduReceiverService {\n private readonly _channel: Maybe<Uint8Array>;\n private readonly _logger: LoggerPublisherService;\n private _pendingFrames: Frame[];\n\n constructor(\n { channel = Maybe.zero() }: ApduReceiverConstructorArgs,\n @inject(loggerTypes.LoggerPublisherServiceFactory)\n loggerModuleFactory: (tag: string) => LoggerPublisherService,\n ) {\n this._channel = channel;\n this._logger = loggerModuleFactory(\"ApduReceiverService\");\n this._pendingFrames = [];\n }\n\n /*\n * Return\n * - A complete ApduResponse\n * - Or a Nothing if not all the data has been received\n * - Or a ReceiverApduError if the apdu is not formatted correctly\n *\n * @param Uint8Array\n */\n public handleFrame(\n frameBytes: Uint8Array,\n ): Either<ReceiverApduError, Maybe<ApduResponse>> {\n const frame = this.getFrameFromBytes(frameBytes);\n\n return frame.map((value) => {\n this._pendingFrames.push(value);\n if (!this._pendingFrames[0]) {\n return Nothing;\n }\n const dataSize = this._pendingFrames[0].getHeader().getDataLength();\n return this.getCompleteFrame(dataSize);\n });\n }\n\n /*\n * Return\n * - A complete ApduResponse\n * - Or a Nothing if not all the data has been received\n *\n * @param Maybe<number>\n */\n private getCompleteFrame(dataSize: Maybe<number>): Maybe<ApduResponse> {\n return dataSize.chain((value) => {\n if (!this.isComplete(value)) {\n this._logger.debug(\"frame is not complete, waiting for more\");\n return Nothing;\n }\n\n const concatenatedFramesData = FramerUtils.getFirstBytesFrom(\n this.concatFrames(this._pendingFrames),\n value,\n );\n const data = FramerUtils.getFirstBytesFrom(\n concatenatedFramesData,\n concatenatedFramesData.length - APDU_RESPONSE_STATUS_CODE_LENGTH,\n );\n const statusCode = FramerUtils.getLastBytesFrom(\n concatenatedFramesData,\n APDU_RESPONSE_STATUS_CODE_LENGTH,\n );\n\n this._pendingFrames = [];\n\n return Just(\n new ApduResponse({\n data: data,\n statusCode,\n }),\n );\n });\n }\n\n /*\n * Parse an Uint8Array to a Frame\n * Return an error if the frame is not formatted correctly\n *\n * @param Uint8Array\n */\n private getFrameFromBytes(\n rawFrame: Uint8Array,\n ): Either<ReceiverApduError, Frame> {\n const channelSize = this._channel.caseOf({\n Just: () => CHANNEL_LENGTH,\n Nothing: () => 0,\n });\n\n const headTag = rawFrame.slice(channelSize, channelSize + HEAD_TAG_LENGTH);\n const index = rawFrame.slice(\n channelSize + HEAD_TAG_LENGTH,\n channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH,\n );\n\n const isFirstIndex = index.reduce((curr, val) => curr + val, 0) === 0;\n\n if (!isFirstIndex && this._pendingFrames.length === 0) {\n return Left(new ReceiverApduError());\n }\n\n const dataSizeIndex = channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH;\n const dataSizeLength = isFirstIndex ? APDU_DATA_LENGTH_LENGTH : 0;\n\n if (\n rawFrame.length <\n channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH + dataSizeLength\n ) {\n return Left(new ReceiverApduError(\"Unable to parse header from apdu\"));\n }\n\n const dataSize = isFirstIndex\n ? Just(rawFrame.slice(dataSizeIndex, dataSizeIndex + dataSizeLength))\n : Nothing;\n\n const dataIndex = dataSizeIndex + dataSizeLength;\n const data = rawFrame.slice(dataIndex);\n\n const frame = new Frame({\n header: new FrameHeader({\n uuid: v4(),\n channel: this._channel,\n dataSize,\n headTag,\n index,\n length: channelSize + HEAD_TAG_LENGTH + INDEX_LENGTH + dataSizeLength,\n }),\n data,\n });\n\n return Right(frame);\n }\n\n /*\n * Return true if all the datas has been received\n *\n * @param number\n */\n private isComplete(dataSize: number): boolean {\n const totalReceiveLength = this._pendingFrames.reduce(\n (prev, curr) => prev + curr.getData().length,\n 0,\n );\n\n return totalReceiveLength >= dataSize;\n }\n\n private concatFrames(frames: Frame[]): Uint8Array {\n return frames.reduce(\n (prev: Uint8Array, curr: Frame) =>\n Uint8Array.from([...prev, ...curr.getData()]),\n new Uint8Array(0),\n );\n }\n}\n"],
|
5
|
+
"mappings": "okBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAmC,qBACnCC,EAA0D,qBAC1DC,EAAmB,gBAEnBC,EAA6B,4CAC7BC,EAKO,gDAKPC,EAA4B,iDAE5BC,EAAiD,2DACjDC,EAAkC,iDAClCC,EAAsB,gDACtBC,EAA4B,sDAC5BC,EAA4B,qDAGrB,IAAMC,EAAN,KAAgE,CACpD,SACA,QACT,eAER,YACE,CAAE,QAAAC,EAAU,QAAM,KAAK,CAAE,EAEzBC,EACA,CACA,KAAK,SAAWD,EAChB,KAAK,QAAUC,EAAoB,qBAAqB,EACxD,KAAK,eAAiB,CAAC,CACzB,CAUO,YACLC,EACgD,CAGhD,OAFc,KAAK,kBAAkBA,CAAU,EAElC,IAAKC,GAAU,CAE1B,GADA,KAAK,eAAe,KAAKA,CAAK,EAC1B,CAAC,KAAK,eAAe,CAAC,EACxB,OAAO,UAET,MAAMC,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M,MAAG,EACT,QAAS,KAAK,SACd,SAAAd,EACA,QAAAM,EACA,MAAAC,EACA,OAAQF,EAAc,kBAAkB,eAAeO,CACzD,CAAC,EACD,KAAAV,CACF,CAAC,EAED,SAAO,SAAMY,CAAK,CACpB,CAOQ,WAAWd,EAA2B,CAM5C,OAL2B,KAAK,eAAe,OAC7C,CAACe,EAAMN,IAASM,EAAON,EAAK,QAAQ,EAAE,OACtC,CACF,GAE6BT,CAC/B,CAEQ,aAAagB,EAA6B,CAChD,OAAOA,EAAO,OACZ,CAACD,EAAkBN,IACjB,WAAW,KAAK,CAAC,GAAGM,EAAM,GAAGN,EAAK,QAAQ,CAAC,CAAC,EAC9C,IAAI,WAAW,CAAC,CAClB,CACF,CACF,EA3Jad,EAANsB,EAAA,IADN,cAAW,EAQPC,EAAA,eAAO,cAAY,6BAA6B,IAPxCvB",
|
6
6
|
"names": ["DefaultApduReceiverService_exports", "__export", "DefaultApduReceiverService", "__toCommonJS", "import_inversify", "import_purify_ts", "import_uuid", "import_ApduResponse", "import_FramerConst", "import_FramerUtils", "import_ApduResponseConst", "import_Errors", "import_Frame", "import_FrameHeader", "import_loggerTypes", "DefaultApduReceiverService", "channel", "loggerModuleFactory", "frameBytes", "value", "dataSize", "concatenatedFramesData", "data", "statusCode", "rawFrame", "channelSize", "headTag", "index", "isFirstIndex", "curr", "val", "dataSizeIndex", "dataSizeLength", "dataIndex", "frame", "prev", "frames", "__decorateClass", "__decorateParam"]
|
7
7
|
}
|
@@ -1,2 +1,2 @@
|
|
1
|
-
"use strict";var c=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var y=(a,e)=>{for(var t in e)c(a,t,{get:e[t],enumerable:!0})},E=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z(e))!v.call(a,i)&&i!==t&&c(a,i,{get:()=>e[i],enumerable:!(r=u(e,i))||r.enumerable});return a};var L=a=>E(c({},"__esModule",{value:!0}),a),f=(a,e,t,r)=>{for(var i=r>1?void 0:r?u(e,t):e,m=a.length-1,s;m>=0;m--)(s=a[m])&&(i=(r?s(e,t,i):s(i))||i);return r&&i&&c(e,t,i),i},F=(a,e)=>(t,r)=>e(t,r,a);var T={};y(T,{DefaultApduSenderService:()=>g});module.exports=L(T);var l=require("inversify"),o=require("purify-ts"),S=require("uuid"),n=require("../../../api/device-session/data/FramerConst"),d=require("../../../api/device-session/utils/FramerUtils"),h=require("../../device-session/model/Errors"),A=require("../../device-session/model/Frame"),_=require("../../device-session/model/FrameHeader"),b=require("../../logger-publisher/di/loggerTypes");let g=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:e,channel:t=o.Maybe.zero(),padding:r=!1},i){this._frameSize=e,this._channel=t,this._padding=r,this._logger=i("DefaultApduSenderService")}getFrames(e){const t=[];let r=0,i=this.getFrameAtIndex(e,r);for(;i.isRight();)t.push(i.extract()),r+=1,i=this.getFrameAtIndex(e,r).mapLeft(m=>(m instanceof h.FramerOverflowError
|
1
|
+
"use strict";var c=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var y=(a,e)=>{for(var t in e)c(a,t,{get:e[t],enumerable:!0})},E=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z(e))!v.call(a,i)&&i!==t&&c(a,i,{get:()=>e[i],enumerable:!(r=u(e,i))||r.enumerable});return a};var L=a=>E(c({},"__esModule",{value:!0}),a),f=(a,e,t,r)=>{for(var i=r>1?void 0:r?u(e,t):e,m=a.length-1,s;m>=0;m--)(s=a[m])&&(i=(r?s(e,t,i):s(i))||i);return r&&i&&c(e,t,i),i},F=(a,e)=>(t,r)=>e(t,r,a);var T={};y(T,{DefaultApduSenderService:()=>g});module.exports=L(T);var l=require("inversify"),o=require("purify-ts"),S=require("uuid"),n=require("../../../api/device-session/data/FramerConst"),d=require("../../../api/device-session/utils/FramerUtils"),h=require("../../device-session/model/Errors"),A=require("../../device-session/model/Frame"),_=require("../../device-session/model/FrameHeader"),b=require("../../logger-publisher/di/loggerTypes");let g=class{_frameSize;_channel;_padding;_logger;constructor({frameSize:e,channel:t=o.Maybe.zero(),padding:r=!1},i){this._frameSize=e,this._channel=t,this._padding=r,this._logger=i("DefaultApduSenderService")}getFrames(e){const t=[];let r=0,i=this.getFrameAtIndex(e,r);for(;i.isRight();)t.push(i.extract()),r+=1,i=this.getFrameAtIndex(e,r).mapLeft(m=>(m instanceof h.FramerOverflowError||this._logger.error("Error while parsing frame",{data:{error:m}}),m));return t}getFrameAtIndex(e,t){const r=this.getFrameHeaderFrom(t,e.length),i=t===0?0:t*this._frameSize-this.getHeaderSizeSumFrom(t);if(i>=e.length)return(0,o.Left)(new h.FramerOverflowError);if(r.getLength()>this._frameSize)return(0,o.Left)(new h.FramerApduError);const m=this._frameSize-r.getLength(),s=e.slice(i,i+this._frameSize-r.getLength()),p=this._padding?new Uint8Array(m).fill(0):new Uint8Array(s.length<m?s.length:m);p.set(s,0);const H=new A.Frame({header:r,data:p});return(0,o.Right)(H)}getFrameHeaderFrom(e,t){const r=new _.FrameHeader({uuid:(0,S.v4)(),channel:this._channel.map(i=>d.FramerUtils.getLastBytesFrom(i,n.CHANNEL_LENGTH)),headTag:new Uint8Array([n.HEAD_TAG]),index:d.FramerUtils.numberToByteArray(e,n.INDEX_LENGTH),length:this.getFrameHeaderSizeFromIndex(e),dataSize:o.Maybe.zero()});return e===0&&r.setDataSize(o.Maybe.of(d.FramerUtils.numberToByteArray(t,n.APDU_DATA_LENGTH_LENGTH))),r}getHeaderSizeSumFrom(e){let t=this.getFrameHeaderSizeFromIndex(0),r=1;for(;r<e;)t+=this.getFrameHeaderSizeFromIndex(r),r+=1;return t}getFrameHeaderSizeFromIndex(e){return this._channel.caseOf({Just:()=>n.CHANNEL_LENGTH,Nothing:()=>0})+n.INDEX_LENGTH+n.HEAD_TAG_LENGTH+(e===0?n.APDU_DATA_LENGTH_LENGTH:0)}};g=f([(0,l.injectable)(),F(1,(0,l.inject)(b.loggerTypes.LoggerPublisherServiceFactory))],g);0&&(module.exports={DefaultApduSenderService});
|
2
2
|
//# sourceMappingURL=DefaultApduSenderService.js.map
|