apacuana-sdk-core 0.10.0 → 0.11.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.
Files changed (56) hide show
  1. package/README.md +305 -286
  2. package/coverage/clover.xml +337 -243
  3. package/coverage/coverage-final.json +9 -7
  4. package/coverage/lcov-report/index.html +34 -19
  5. package/coverage/lcov-report/src/api/certs.js.html +162 -87
  6. package/coverage/lcov-report/src/api/faceLiveness.js.html +496 -0
  7. package/coverage/lcov-report/src/api/index.html +43 -28
  8. package/coverage/lcov-report/src/api/revocations.js.html +103 -106
  9. package/coverage/lcov-report/src/api/signatures.js.html +25 -253
  10. package/coverage/lcov-report/src/api/users.js.html +7 -13
  11. package/coverage/lcov-report/src/config/index.html +1 -1
  12. package/coverage/lcov-report/src/config/index.js.html +1 -1
  13. package/coverage/lcov-report/src/errors/index.html +1 -1
  14. package/coverage/lcov-report/src/errors/index.js.html +8 -8
  15. package/coverage/lcov-report/src/index.html +1 -1
  16. package/coverage/lcov-report/src/index.js.html +26 -2
  17. package/coverage/lcov-report/src/success/index.html +116 -0
  18. package/coverage/lcov-report/src/success/index.js.html +106 -0
  19. package/coverage/lcov-report/src/utils/constant.js.html +4 -4
  20. package/coverage/lcov-report/src/utils/helpers.js.html +1 -1
  21. package/coverage/lcov-report/src/utils/httpClient.js.html +1 -1
  22. package/coverage/lcov-report/src/utils/index.html +1 -1
  23. package/coverage/lcov.info +582 -406
  24. package/dist/api/certs.d.ts +9 -70
  25. package/dist/api/faceLiveness.d.ts +6 -0
  26. package/dist/api/revocations.d.ts +3 -42
  27. package/dist/api/signatures.d.ts +11 -153
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +463 -252
  30. package/dist/index.js.map +1 -1
  31. package/dist/index.mjs +463 -252
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/success/index.d.ts +7 -0
  34. package/dist/types/certs.d.ts +97 -0
  35. package/dist/types/faceLiveness.d.ts +10 -0
  36. package/dist/types/revocations.d.ts +40 -0
  37. package/dist/types/signatures.d.ts +152 -0
  38. package/dist/types/users.d.ts +260 -0
  39. package/package.json +1 -1
  40. package/src/api/certs.js +74 -49
  41. package/src/api/faceLiveness.js +137 -0
  42. package/src/api/revocations.js +66 -67
  43. package/src/api/signatures.js +21 -97
  44. package/src/api/users.js +4 -6
  45. package/src/index.js +8 -0
  46. package/src/success/index.js +8 -0
  47. package/src/types/certs.js +56 -0
  48. package/src/types/faceLiveness.js +7 -0
  49. package/src/types/revocations.js +25 -0
  50. package/src/types/signatures.js +77 -0
  51. package/src/types/users.js +73 -0
  52. package/tests/api/certs.test.js +99 -6
  53. package/tests/api/faceLiveness.test.js +172 -0
  54. package/tests/api/revocations.test.js +37 -37
  55. package/tests/api/signatures.test.js +11 -5
  56. package/tests/api/users.test.js +3 -2
package/src/index.js CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  getCertStatus,
8
8
  getCertTypes,
9
9
  getRequerimentsByTypeUser,
10
+ requestCertificate,
10
11
  } from "./api/certs";
11
12
  import {
12
13
  addSigner,
@@ -17,6 +18,10 @@ import {
17
18
  signDocument,
18
19
  uploadSignatureVariant,
19
20
  } from "./api/signatures";
21
+ import {
22
+ createFaceLivenessSession,
23
+ validateFaceLiveness,
24
+ } from "./api/faceLiveness";
20
25
 
21
26
  const apacuana = {
22
27
  /**
@@ -68,6 +73,9 @@ const apacuana = {
68
73
  deleteSignatureVariant,
69
74
  getCertTypes,
70
75
  getRequerimentsByTypeUser,
76
+ createFaceLivenessSession,
77
+ validateFaceLiveness,
78
+ requestCertificate,
71
79
  };
72
80
 
73
81
  export default apacuana;
@@ -0,0 +1,8 @@
1
+ export default class ApacuanaSuccess {
2
+ constructor(data, statusCode = 200) {
3
+ this.success = true;
4
+ this.statusCode = statusCode;
5
+ this.name = "ApacuanaSuccess";
6
+ this.data = data;
7
+ }
8
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @typedef {object} GenerateCertResponse
3
+ * @property {string} cert - El certificado generado en formato string.
4
+ * @property {string} certifiedid - El ID del certificado generado.
5
+ * @property {boolean} success - Indica si la operación fue exitosa.
6
+ */
7
+
8
+ /**
9
+ * @typedef {object} GetCertStatusResponse
10
+ * @property {string} status - El estado actual del certificado del usuario.
11
+ * @property {boolean} success - Indica si la operación fue exitosa.
12
+ */
13
+
14
+ /**
15
+ * @typedef {object} EncryptedCSRObject
16
+ * @property {string} csr - The encrypted Certificate Signing Request.
17
+ */
18
+
19
+ /**
20
+ * @typedef {object} CertType
21
+ * @property {string} id - The ID of the certificate type.
22
+ * @property {string} name - The name of the certificate type.
23
+ */
24
+
25
+ /**
26
+ * @typedef {object} GetCertTypesResponse
27
+ * @property {Array<CertType>} types - A list of available certificate types.
28
+ * @property {boolean} success - Indicates if the operation was successful.
29
+ */
30
+
31
+ /**
32
+ * @typedef {object} Requirement
33
+ * @property {string} id - The ID of the requirement.
34
+ * @property {string} description - The description of the requirement.
35
+ */
36
+
37
+ /**
38
+ * @typedef {object} GetRequirementsResponse
39
+ * @property {Array<Requirement>} requirements - A list of requirements for the user type.
40
+ * @property {boolean} success - Indicates if the operation was successful.
41
+ */
42
+
43
+ /**
44
+ * @typedef {object} CertificateRequestParams
45
+ * @property {number} type - The user type to get requirements for.
46
+ * @property {string} [observation] - An optional observation for the certificate request.
47
+ * @property {Array<{id: string, file: string}>} documents - The documents required for the certificate.
48
+ */
49
+
50
+ /**
51
+ * @typedef {object} RequestCertificateResponse
52
+ * @property {string} message - A message confirming the request.
53
+ * @property {boolean} success - Indicates if the operation was successful.
54
+ */
55
+
56
+ export {};
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @typedef {object} CreateFaceLivenessSessionResponse
3
+ * @property {string} sessionId - The session ID for the face liveness check.
4
+ * @property {boolean} success - Indicates if the operation was successful.
5
+ */
6
+
7
+ export {};
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @typedef {object} RequestRevocationResponse
3
+ * @property {string} revocationStatus - El estado de la solicitud de revocación (e.g., "pending").
4
+ * @property {string|number} requestId - El ID de la solicitud de revocación.
5
+ */
6
+
7
+ /**
8
+ * @typedef {object} RevocationResponse
9
+ * @property {boolean} success - Indicates if the revocation request was successful.
10
+ * @property {string} [message] - A message providing details about the outcome.
11
+ */
12
+
13
+ /**
14
+ * @typedef {object} RevocationReason
15
+ * @property {string} code - The code for the revocation reason.
16
+ * @property {string} description - The description of the revocation reason.
17
+ */
18
+
19
+ /**
20
+ * @typedef {object} RevocationReasonsResponse
21
+ * @property {boolean} success - Indicates if the request was successful.
22
+ * @property {RevocationReason[]} reasons - A list of revocation reasons.
23
+ */
24
+
25
+ export {};
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Define la estructura de un objeto Firmante.
3
+ * @typedef {object} Signer
4
+ * @property {string} name - Nombre completo del firmante.
5
+ * @property {string} email - Correo electrónico del firmante.
6
+ * @property {string} document - Documento de identidad del firmante.
7
+ */
8
+
9
+ /**
10
+ * Define la estructura de datos para añadir un firmante.
11
+ * @typedef {object} SignerData
12
+ * @property {string} docId - Identificador único del documento.
13
+ */
14
+
15
+ /**
16
+ * Define la estructura de la respuesta al añadir un firmante.
17
+ * @typedef {object} AddSignerResponse
18
+ * @property {string} signer - Identificador de confirmación del firmante añadido.
19
+ * @property {boolean} success - Indica si la operación fue exitosa.
20
+ */
21
+
22
+ /**
23
+ * Define la estructura de datos para obtener el digest de un documento.
24
+ * @typedef {object} GetDigestData
25
+ * @property {string} cert - Certificado del firmante en formato base64.
26
+ * @property {string} signatureId - Identificador único del proceso de firma.
27
+ */
28
+
29
+ /**
30
+ * Define la estructura de la respuesta al obtener el digest.
31
+ * @typedef {object} GetDigestResponse
32
+ * @property {string} digest - El digest del documento que se va a firmar.
33
+ * @property {boolean} success - Indica si la operación fue exitosa.
34
+ */
35
+
36
+ /**
37
+ * Define la estructura de los parámetros para obtener documentos.
38
+ * @typedef {object} GetDocsParams
39
+ * @property {number} page - Número de página para la paginación.
40
+ * @property {number} size - Cantidad de registros por página.
41
+ * @property {string} [status] - (Opcional) Estado para filtrar los documentos.
42
+ */
43
+
44
+ /**
45
+ * Define la estructura de la respuesta al obtener documentos.
46
+ * @typedef {object} GetDocsResponse
47
+ * @property {number} totalRecords - El número total de registros encontrados.
48
+ * @property {Array<object>} records - Un arreglo con los registros de los documentos.
49
+ * @property {boolean} success - Indica si la operación fue exitosa.
50
+ */
51
+
52
+ /**
53
+ * @typedef {object} SignDocumentData
54
+ * @property {object} signature - Objeto con información de la firma.
55
+ * @property {string} signature.id - ID de la firma.
56
+ * @property {Array<object>} signature.positions - Posiciones de la firma.
57
+ * @property {string} cert - Certificado en base64.
58
+ * @property {string} signedDigest - Digest firmado.
59
+ */
60
+
61
+ /**
62
+ * @typedef {object} SignaturePosition
63
+ * @property {number} page - The page number for the signature.
64
+ * @property {number} x - The x-coordinate for the signature's position (from 0 to 1).
65
+ * @property {number} y - The y-coordinate for the signature's position (from 0 to 1).
66
+ */
67
+
68
+ /**
69
+ * @typedef {object} OnboardingSignerData
70
+ * @property {string} name - The name of the document.
71
+ * @property {string} reference - An external reference for the document.
72
+ * @property {string} typedoc - The type of document of the signer (e.g., "V", "E", "J").
73
+ * @property {string} doc - The document number of the signer.
74
+ * @property {SignaturePosition[]} signature - An array of signature positions.
75
+ */
76
+
77
+ export {};
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @typedef {object} UserData
3
+ * @property {string} email - Correo electrónico. No puede contener espacios y tiene un máximo de 128 caracteres.
4
+ * @property {number} typeuser - Tipo de usuario. Debe ser un ID valido.
5
+ * @property {string} name - Nombre de la persona.
6
+ * @property {string} lastname - Apellido de la persona.
7
+ * @property {'V' | 'P' | 'E'} kinddoc - Tipo de documento de identidad. Puede ser 'V' (Venezolano), 'P' (Pasaporte) o 'E' (Extranjero).
8
+ * @property {number} doc - Número de documento de identidad. Debe ser un número entero.
9
+ * @property {string} birthdate - Fecha de nacimiento. Debe ser una fecha válida en formato ISO y no puede ser una fecha futura.
10
+ * @property {'J' | 'G' | 'V' | 'P' | 'E'} kindrif - Tipo de RIF (Registro de Información Fiscal). Puede ser 'J', 'G', 'V', 'P' o 'E'.
11
+ * @property {'M' | 'F' | 'Sin especificar'} gender - Género. Puede ser 'M' (Masculino), 'F' (Femenino) o 'Sin especificar'.
12
+ * @property {number} rif - Número de RIF. Debe ser un número entero.
13
+ * @property {number} phone - Número de teléfono. Debe ser un número entero.
14
+ * @property {string} kindphone - Código de área del teléfono. Ej. 0424.
15
+ * @property {string} state - Nombre del estado.
16
+ * @property {string} municipality - Nombre del municipio.
17
+ * @property {string} parish - Nombre de la parroquia.
18
+ * @property {string} postalcode - Código postal.
19
+ * @property {string} address - Dirección.
20
+ * @property {string} fiscaladdress - Dirección fiscal.
21
+ * @property {string} fiscalkindphone - Código de área del teléfono fiscal. Ej. 0424.
22
+ * @property {number} fiscalphone - Número de teléfono fiscal. Debe ser un número entero.
23
+ * @property {string} occupation - Ocupacion de la persona.
24
+ * @property {string} degree - Título universitario.
25
+ * @property {string} university - Universidad.
26
+ * @property {string} graduationyear - Año de graduación.
27
+ * @property {string} collegiatenumber - Número de colegiado.
28
+ * @property {string} collegiateyear - Año de colegiatura.
29
+ * @property {string} companyname - Nombre de la empresa.
30
+ * @property {'J' | 'G' | 'V' | 'P' | 'E'} companykindrif - Tipo de RIF de la empresa. Puede ser 'J', 'G', 'V', 'P' o 'E'.
31
+ * @property {string} companyrif - Número de RIF de la empresa.
32
+ * @property {string} companystate - Estado de la empresa.
33
+ * @property {string} companymunicipality - Municipio de la empresa.
34
+ * @property {string} companyparish - Parroquia de la empresa.
35
+ * @property {string} companyaddress - Dirección de la empresa.
36
+ * @property {string} companykindphone - Código de área del teléfono de la empresa. Ej. 0212.
37
+ * @property {string} companyphone - Número de teléfono de la empresa.
38
+ * @property {string} companypostalcode - Código postal de la empresa.
39
+ * @property {string} companywebpage - Página web de la empresa.
40
+ * @property {string} companycommercialregister - Registro comercial de la empresa.
41
+ * @property {string} companyregisterdate - Fecha de registro de la empresa en formato ISO.
42
+ * @property {string} companyregisternumber - Número de registro de la empresa.
43
+ * @property {string} companyconstitutiondate - Fecha de constitución de la empresa en formato ISO.
44
+ * @property {string} companypublishdate - Fecha de publicación del decreto de constitución. Debe ser una fecha válida en formato ISO y no puede ser una fecha futura.
45
+ * @property {string} companyconstitutiondecree - Decreto de constitución de la empresa. Máximo 32 caracteres.
46
+ * @property {string} companynumberdecree - Número de decreto de la empresa. Máximo 16 caracteres.
47
+ * @property {string} positionprivate - Cargo empleado empresa privada.
48
+ * @property {string} departmentprivate - Departamento empleado empresa privada.
49
+ * @property {string} authorizedprivate - Autorizado de por empleado empresa privada.
50
+ * @property {string} functionsprivate - Funciones empleado empresa privada.
51
+ * @property {string} publishprivate - Fecha de publicación de la gaceta de la empresa privada.
52
+ * @property {string} issuedateprivate - Fecha de registro de la empresa privada. Debe ser una fecha válida en formato ISO.
53
+ * @property {string} kindphoneprivate - Código de área del teléfono de la empresa privada. ej. 0424.
54
+ * @property {number} phoneprivate - Número de teléfono privado. Debe ser un número entero.
55
+ * @property {string} positionpublic - Cargo empleado empresa publica.
56
+ * @property {string} departmentpublic - Departamento empleado empresa publica.
57
+ * @property {string} authorizedpublic - Autorizado empleado empresa publica.
58
+ * @property {string} functionspublic - Funciones de empleado empresa publica.
59
+ * @property {string} publishpublic - Fecha de publicación de la gaceta de la empresa pública.
60
+ * @property {string} issuedatepublic - Fecha de registro de la empresa pública. Debe ser una fecha válida en formato ISO.
61
+ * @property {string} kindphonepublic - Código de área del teléfono de la empresa publica. ej 0424.
62
+ * @property {number} phonepublic - Número de teléfono público. Debe ser un número entero.
63
+ * @property {string} companyid - ID de la empresa. Debe ser un UUID para la creacion de empleados.
64
+ */
65
+
66
+ /**
67
+ * @typedef {object} GetCustomerResponse
68
+ * @property {string} token - El token de sesión del usuario.
69
+ * @property {UserData} userData - Los datos del usuario obtenidos.
70
+ * @property {boolean} success - Indica si la operación fue exitosa.
71
+ */
72
+
73
+ export {};
@@ -2,11 +2,13 @@ import { getConfig } from "../../src/config/index";
2
2
  import { httpRequest } from "../../src/utils/httpClient";
3
3
  import helpers from "../../src/utils/helpers";
4
4
  import { ApacuanaAPIError } from "../../src/errors";
5
+ import ApacuanaSuccess from "../../src/success";
5
6
  import {
6
7
  generateCert,
7
8
  getCertStatus,
8
9
  getCertTypes,
9
10
  getRequerimentsByTypeUser,
11
+ requestCertificate,
10
12
  } from "../../src/api/certs";
11
13
  import { INTEGRATION_TYPE } from "../../src/utils/constant";
12
14
 
@@ -43,10 +45,10 @@ describe("Certificate API - certs.js", () => {
43
45
  mockEncryptedCsr,
44
46
  "POST"
45
47
  );
46
- expect(result).toEqual({
48
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
49
+ expect(result.data).toEqual({
47
50
  cert: "onboarding-cert",
48
51
  certifiedid: "onboarding-certified-id",
49
- success: true,
50
52
  });
51
53
  });
52
54
 
@@ -93,7 +95,8 @@ describe("Certificate API - certs.js", () => {
93
95
  mockUserData,
94
96
  true
95
97
  );
96
- expect(result).toEqual({ status: "VALID", success: true });
98
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
99
+ expect(result.data).toEqual({ status: "VALID" });
97
100
  });
98
101
  });
99
102
 
@@ -112,7 +115,8 @@ describe("Certificate API - certs.js", () => {
112
115
  {},
113
116
  "GET"
114
117
  );
115
- expect(result).toEqual({ types: mockApiResponse.types, success: true });
118
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
119
+ expect(result.data).toEqual({ types: mockApiResponse.types });
116
120
  });
117
121
 
118
122
  it("should throw an error for ONPREMISE integration", async () => {
@@ -159,9 +163,9 @@ describe("Certificate API - certs.js", () => {
159
163
  {},
160
164
  "GET"
161
165
  );
162
- expect(result).toEqual({
166
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
167
+ expect(result.data).toEqual({
163
168
  requirements: mockApiResponse.requirements,
164
- success: true,
165
169
  });
166
170
  });
167
171
 
@@ -202,5 +206,94 @@ describe("Certificate API - certs.js", () => {
202
206
  'The "params" object with a numeric "type" property is required.'
203
207
  );
204
208
  });
209
+ it("should throw a generic error for other failures", async () => {
210
+ getConfig.mockReturnValue({
211
+ integrationType: INTEGRATION_TYPE.ONBOARDING,
212
+ });
213
+ const genericError = new Error("Network failure");
214
+ httpRequest.mockRejectedValue(genericError);
215
+
216
+ await expect(getRequerimentsByTypeUser({ type: 1 })).rejects.toThrow(
217
+ `Failed to get requirements: ${genericError.message}`
218
+ );
219
+ });
220
+ });
221
+ });
222
+
223
+ describe("requestCertificate", () => {
224
+ const validParams = { type: 1, documents: [] };
225
+
226
+ afterEach(() => {
227
+ jest.clearAllMocks();
228
+ });
229
+
230
+ it("should throw an error if params are invalid", async () => {
231
+ await expect(requestCertificate()).rejects.toThrow(
232
+ 'The "params" object with a numeric "type" property and a "documents" array is required.'
233
+ );
234
+ await expect(requestCertificate({ type: 1 })).rejects.toThrow(
235
+ 'The "params" object with a numeric "type" property and a "documents" array is required.'
236
+ );
237
+ await expect(requestCertificate({ documents: [] })).rejects.toThrow(
238
+ 'The "params" object with a numeric "type" property and a "documents" array is required.'
239
+ );
240
+ });
241
+
242
+ it("should request a certificate for ONBOARDING integration", async () => {
243
+ getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONBOARDING });
244
+ const mockResponse = { message: "Certificate requested" };
245
+ httpRequest.mockResolvedValue(mockResponse);
246
+
247
+ const result = await requestCertificate(validParams);
248
+
249
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
250
+ expect(result.data).toEqual(mockResponse);
251
+ expect(httpRequest).toHaveBeenCalledWith(
252
+ "services/api/customer/request-certificate",
253
+ validParams,
254
+ "POST"
255
+ );
256
+ });
257
+
258
+ it("should throw a NOT_IMPLEMENTED error for ONPREMISE integration", async () => {
259
+ getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONPREMISE });
260
+
261
+ await expect(requestCertificate(validParams)).rejects.toThrow(
262
+ new ApacuanaAPIError(
263
+ "Requesting a certificate is not supported for integration type: ONPREMISE",
264
+ 501,
265
+ "NOT_IMPLEMENTED"
266
+ )
267
+ );
268
+ });
269
+
270
+ it("should throw an UNSUPPORTED_INTEGRATION_TYPE error for unsupported integration types", async () => {
271
+ getConfig.mockReturnValue({ integrationType: "unsupported-type" });
272
+
273
+ await expect(requestCertificate(validParams)).rejects.toThrow(
274
+ new ApacuanaAPIError(
275
+ "Unsupported integration type: unsupported-type",
276
+ 400,
277
+ "UNSUPPORTED_INTEGRATION_TYPE"
278
+ )
279
+ );
280
+ });
281
+
282
+ it("should re-throw ApacuanaAPIError if caught", async () => {
283
+ getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONBOARDING });
284
+ const apiError = new ApacuanaAPIError("API Error", 500, "API_ERROR");
285
+ httpRequest.mockRejectedValue(apiError);
286
+
287
+ await expect(requestCertificate(validParams)).rejects.toThrow(apiError);
288
+ });
289
+
290
+ it("should throw a generic error for other failures", async () => {
291
+ getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONBOARDING });
292
+ const genericError = new Error("Network failure");
293
+ httpRequest.mockRejectedValue(genericError);
294
+
295
+ await expect(requestCertificate(validParams)).rejects.toThrow(
296
+ `Failed to request certificate: ${genericError.message}`
297
+ );
205
298
  });
206
299
  });
@@ -0,0 +1,172 @@
1
+ import * as faceLiveness from "../../src/api/faceLiveness";
2
+ import { httpRequest } from "../../src/utils/httpClient";
3
+ import { getConfig } from "../../src/config";
4
+ import { ApacuanaAPIError } from "../../src/errors";
5
+ import ApacuanaSuccess from "../../src/success";
6
+ import { INTEGRATION_TYPE } from "../../src/utils/constant";
7
+
8
+ jest.mock("../../src/utils/httpClient", () => ({
9
+ httpRequest: jest.fn(),
10
+ }));
11
+
12
+ jest.mock("../../src/config", () => ({
13
+ getConfig: jest.fn(),
14
+ }));
15
+
16
+ describe("FaceLiveness API", () => {
17
+ beforeEach(() => {
18
+ jest.clearAllMocks();
19
+ getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONBOARDING });
20
+ });
21
+
22
+ describe("createFaceLivenessSession", () => {
23
+ it("should create a session for ONBOARDING integration", async () => {
24
+ httpRequest.mockResolvedValue({ sessionId: "test-session-id" });
25
+
26
+ const result = await faceLiveness.createFaceLivenessSession();
27
+
28
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
29
+ expect(result.data).toEqual({ sessionId: "test-session-id" });
30
+ expect(httpRequest).toHaveBeenCalledWith(
31
+ "services/api/faceliveness/create",
32
+ {},
33
+ "POST"
34
+ );
35
+ });
36
+
37
+ it("should throw an error if API response does not contain sessionId for ONBOARDING", async () => {
38
+ httpRequest.mockResolvedValue({}); // No sessionId
39
+
40
+ await expect(faceLiveness.createFaceLivenessSession()).rejects.toThrow(
41
+ new ApacuanaAPIError(
42
+ "The API response does not contain the session ID.",
43
+ undefined,
44
+ "INVALID_API_RESPONSE"
45
+ )
46
+ );
47
+ });
48
+
49
+ it("should throw a NOT_IMPLEMENTED error for ONPREMISE integration", async () => {
50
+ getConfig.mockReturnValue({
51
+ integrationType: INTEGRATION_TYPE.ONPREMISE,
52
+ });
53
+
54
+ await expect(faceLiveness.createFaceLivenessSession()).rejects.toThrow(
55
+ new ApacuanaAPIError(
56
+ "Creating a Face Liveness session is not supported for integration type: ONPREMISE",
57
+ 501,
58
+ "NOT_IMPLEMENTED"
59
+ )
60
+ );
61
+ });
62
+
63
+ it("should throw an UNSUPPORTED_INTEGRATION_TYPE error for unsupported integration types", async () => {
64
+ getConfig.mockReturnValue({ integrationType: "unsupported-type" });
65
+
66
+ await expect(faceLiveness.createFaceLivenessSession()).rejects.toThrow(
67
+ new ApacuanaAPIError(
68
+ "Unsupported integration type: unsupported-type",
69
+ 400,
70
+ "UNSUPPORTED_INTEGRATION_TYPE"
71
+ )
72
+ );
73
+ });
74
+
75
+ it("should re-throw ApacuanaAPIError if caught during session creation", async () => {
76
+ const apiError = new ApacuanaAPIError("API Error", 500, "API_ERROR");
77
+ httpRequest.mockRejectedValue(apiError);
78
+
79
+ await expect(faceLiveness.createFaceLivenessSession()).rejects.toThrow(
80
+ apiError
81
+ );
82
+ });
83
+
84
+ it("should throw a generic error for other failures during session creation", async () => {
85
+ const genericError = new Error("Network Error");
86
+ httpRequest.mockRejectedValue(genericError);
87
+
88
+ await expect(faceLiveness.createFaceLivenessSession()).rejects.toThrow(
89
+ `Failed to create Face Liveness session: ${genericError.message}`
90
+ );
91
+ });
92
+ });
93
+
94
+ describe("validateFaceLiveness", () => {
95
+ const sessionId = "test-session-id";
96
+
97
+ it("should throw an error if sessionId is not provided", async () => {
98
+ await expect(faceLiveness.validateFaceLiveness({})).rejects.toThrow(
99
+ new ApacuanaAPIError(
100
+ "sessionId is a required parameter.",
101
+ 400,
102
+ "INVALID_PARAMETER"
103
+ )
104
+ );
105
+ });
106
+
107
+ it("should return 'verified' on status 200", async () => {
108
+ httpRequest.mockResolvedValue({ someData: "data" });
109
+
110
+ const result = await faceLiveness.validateFaceLiveness({ sessionId });
111
+
112
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
113
+ expect(result.data).toEqual({ status: "verified", someData: "data" });
114
+ expect(httpRequest).toHaveBeenCalledWith(
115
+ "services/api/faceliveness/validate",
116
+ { sessionid: sessionId },
117
+ "POST"
118
+ );
119
+ });
120
+
121
+ it.each([
122
+ [402, "waitingForScan"],
123
+ [403, "rejected"],
124
+ [406, "processing"],
125
+ [408, "expired"],
126
+ ])(
127
+ "should return status '%s' for statusCode %i",
128
+ async (statusCode, status) => {
129
+ const apiError = new ApacuanaAPIError(
130
+ "Error",
131
+ statusCode,
132
+ "API_ERROR"
133
+ );
134
+ httpRequest.mockRejectedValue(apiError);
135
+
136
+ const result = await faceLiveness.validateFaceLiveness({ sessionId });
137
+
138
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
139
+ expect(result.data).toEqual({ status });
140
+ }
141
+ );
142
+
143
+ it("should throw an error for unhandled status codes", async () => {
144
+ const apiError = new ApacuanaAPIError(
145
+ "Unhandled Error",
146
+ 500,
147
+ "API_ERROR"
148
+ );
149
+ httpRequest.mockRejectedValue(apiError);
150
+
151
+ await expect(
152
+ faceLiveness.validateFaceLiveness({ sessionId })
153
+ ).rejects.toThrow(apiError);
154
+ });
155
+
156
+ it("should throw a NOT_IMPLEMENTED error for ONPREMISE integration", async () => {
157
+ getConfig.mockReturnValue({
158
+ integrationType: INTEGRATION_TYPE.ONPREMISE,
159
+ });
160
+
161
+ await expect(
162
+ faceLiveness.validateFaceLiveness({ sessionId })
163
+ ).rejects.toThrow(
164
+ new ApacuanaAPIError(
165
+ "Validating a Face Liveness session is not supported for integration type: ONPREMISE",
166
+ 501,
167
+ "NOT_IMPLEMENTED"
168
+ )
169
+ );
170
+ });
171
+ });
172
+ });