apacuana-sdk-core 0.12.0 → 0.14.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 (49) hide show
  1. package/README.md +131 -164
  2. package/coverage/clover.xml +386 -296
  3. package/coverage/coverage-final.json +7 -7
  4. package/coverage/lcov-report/index.html +38 -38
  5. package/coverage/lcov-report/src/api/certs.js.html +14 -8
  6. package/coverage/lcov-report/src/api/faceLiveness.js.html +1 -1
  7. package/coverage/lcov-report/src/api/index.html +31 -31
  8. package/coverage/lcov-report/src/api/revocations.js.html +2 -2
  9. package/coverage/lcov-report/src/api/signatures.js.html +17 -56
  10. package/coverage/lcov-report/src/api/users.js.html +160 -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 +1 -1
  15. package/coverage/lcov-report/src/index.html +21 -21
  16. package/coverage/lcov-report/src/index.js.html +267 -63
  17. package/coverage/lcov-report/src/success/index.html +1 -1
  18. package/coverage/lcov-report/src/success/index.js.html +1 -1
  19. package/coverage/lcov-report/src/utils/constant.js.html +115 -4
  20. package/coverage/lcov-report/src/utils/helpers.js.html +286 -22
  21. package/coverage/lcov-report/src/utils/httpClient.js.html +32 -20
  22. package/coverage/lcov-report/src/utils/index.html +24 -24
  23. package/coverage/lcov.info +776 -586
  24. package/dist/api/users.d.ts +27 -21
  25. package/dist/index.d.ts +19 -42
  26. package/dist/index.js +357 -251
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +357 -251
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/types/certs.d.ts +20 -34
  31. package/dist/types/signatures.d.ts +19 -4
  32. package/dist/utils/constant.d.ts +31 -0
  33. package/dist/utils/helpers.d.ts +5 -3
  34. package/package.json +1 -1
  35. package/src/api/certs.js +4 -2
  36. package/src/api/revocations.js +1 -1
  37. package/src/api/signatures.js +8 -21
  38. package/src/api/users.js +51 -2
  39. package/src/index.js +113 -45
  40. package/src/types/certs.js +36 -25
  41. package/src/types/signatures.js +6 -1
  42. package/src/utils/constant.js +37 -0
  43. package/src/utils/helpers.js +100 -12
  44. package/src/utils/httpClient.js +16 -12
  45. package/tests/api/certs.test.js +11 -3
  46. package/tests/api/revocations.test.js +1 -1
  47. package/tests/api/signatures.test.js +73 -16
  48. package/tests/api/users.test.js +1 -1
  49. package/tests/index.test.js +3 -2
package/dist/index.mjs CHANGED
@@ -277,8 +277,31 @@ var STATUS_CERTIFICATE = {
277
277
  generate: "GENERAR",
278
278
  current: "VIGENTE",
279
279
  revoque: "REVOCADO",
280
+ expire: "EXPIRADO",
280
281
  request_revoque: "SOLICITUD_DE_REVOCACION",
281
282
  certificate_another_device: "CERTIFICADO_EN_OTRO_DISPOSITIVO"};
283
+ var PARSE_STATUS = _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, STATUS_CERTIFICATE.certificate_another_device, {
284
+ text: "Verificado",
285
+ descriptionText: undefined
286
+ }), STATUS_CERTIFICATE.request_cert, {
287
+ text: "En revisión",
288
+ descriptionText: "La información y documentos enviados están siendo certificados por la Autoridad de Certificación para confirmar su validez."
289
+ }), STATUS_CERTIFICATE.request, {
290
+ text: "Por verificar",
291
+ descriptionText: "La información y documentos enviados están siendo revisados por la Autoridad de Registro."
292
+ }), STATUS_CERTIFICATE.generate, {
293
+ text: "Por generar",
294
+ descriptionText: "Tu solicitud fue aprobada. Solo falta que generes tu certificado para comenzar a usarlo."
295
+ }), STATUS_CERTIFICATE.current, {
296
+ text: " ",
297
+ descriptionText: undefined
298
+ }), STATUS_CERTIFICATE.expire, "Certificado expirado."), STATUS_CERTIFICATE.request_revoque, {
299
+ text: "Por revocar",
300
+ descriptionText: "Recibimos tu solicitud de revocación y estamos procesándola. El certificado dejará de ser válido una vez finalice el trámite."
301
+ }), STATUS_CERTIFICATE.revoque, {
302
+ text: "Revocado",
303
+ descriptionText: "Este certificado ha sido revocado. Debes solicitar uno nuevo."
304
+ });
282
305
  var VERIFICATION_STATUS = {
283
306
  APPROVED: 1
284
307
  };
@@ -371,7 +394,7 @@ var axiosInstance;
371
394
  */
372
395
  var initHttpClient = function initHttpClient() {
373
396
  var config = getConfig();
374
- if (!config.apiUrl || !config.secretKey || !config.apiKey || !config.verificationId || !config.customerId) {
397
+ if (!config.apiUrl || !config.secretKey || !config.apiKey || !config.verificationId) {
375
398
  throw new Error("HttpClient: Configuración de inicialización incompleta. Llama a apacuana.init() primero.");
376
399
  }
377
400
  axiosInstance = axios.create({
@@ -466,17 +489,21 @@ var httpRequest = /*#__PURE__*/function () {
466
489
  throw new Error("Apacuana SDK: Cliente HTTP no inicializado. " + "Llama a apacuana.init() primero.");
467
490
  case 1:
468
491
  requestConfig = {};
469
- hasFile = Object.values(data).some(function (value) {
470
- return typeof File !== "undefined" && value instanceof File;
471
- });
472
- if (hasFile) {
473
- formData = new FormData();
474
- Object.keys(data).forEach(function (key) {
475
- formData.append(key, data[key]);
476
- });
477
- dataToSend = formData;
492
+ if (typeof FormData !== "undefined" && data instanceof FormData) {
493
+ dataToSend = data;
478
494
  } else {
479
- dataToSend = _objectSpread2({}, data);
495
+ hasFile = Object.values(data).some(function (value) {
496
+ return typeof File !== "undefined" && value instanceof File;
497
+ });
498
+ if (hasFile) {
499
+ formData = new FormData();
500
+ Object.keys(data).forEach(function (key) {
501
+ formData.append(key, data[key]);
502
+ });
503
+ dataToSend = formData;
504
+ } else {
505
+ dataToSend = _objectSpread2({}, data);
506
+ }
480
507
  }
481
508
  _context.p = 2;
482
509
  _t = method.toUpperCase();
@@ -538,79 +565,6 @@ var ApacuanaSuccess = /*#__PURE__*/_createClass(function ApacuanaSuccess(data) {
538
565
  this.data = data;
539
566
  });
540
567
 
541
- /**
542
- * @typedef {object} GetCustomerData
543
- * @property {string} token - El token de sesión del usuario.
544
- * @property {object} userData - Los datos del usuario obtenidos.
545
- */
546
-
547
- /**
548
- * @typedef {object} GetCustomerResponse
549
- * @property {true} success - Indica que la operación fue exitosa.
550
- * @property {GetCustomerData} data - El payload de la respuesta.
551
- */
552
-
553
- /**
554
- * Obtiene el token de un usuario a través de una petición POST.
555
- * Este método es útil para endpoints que requieren datos en el cuerpo de la petición
556
- * para buscar un usuario, como un ID de sesión o un token de acceso.
557
- *
558
- * @returns {Promise<GetCustomerResponse>} Una promesa que resuelve a un objeto con la respuesta exitosa.
559
- * @throws {Error} Si los parámetros de entrada son inválidos.
560
- * @throws {ApacuanaAPIError} Si ocurre un error en la API de Apacuana.
561
- */
562
- var getCustomer = /*#__PURE__*/function () {
563
- var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
564
- var _getConfig, verificationId, customerId, body, response, _t;
565
- return _regenerator().w(function (_context) {
566
- while (1) switch (_context.p = _context.n) {
567
- case 0:
568
- _getConfig = getConfig(), verificationId = _getConfig.verificationId, customerId = _getConfig.customerId;
569
- if (!(!verificationId || !customerId)) {
570
- _context.n = 1;
571
- break;
572
- }
573
- throw new ApacuanaAPIError("Both 'verificationId' and 'customerId' must be configured.", 400, "CONFIGURATION_ERROR");
574
- case 1:
575
- body = {
576
- verificationid: verificationId,
577
- customerid: customerId
578
- };
579
- _context.p = 2;
580
- _context.n = 3;
581
- return httpRequest("services/api/register/init", body, "POST");
582
- case 3:
583
- response = _context.v;
584
- if (!(!response.sessionid || !response.entry)) {
585
- _context.n = 4;
586
- break;
587
- }
588
- throw new ApacuanaAPIError("The API response does not contain the user.", 200, "INVALID_API_RESPONSE");
589
- case 4:
590
- return _context.a(2, new ApacuanaSuccess({
591
- token: response.sessionid,
592
- userData: response.entry
593
- }));
594
- case 5:
595
- _context.p = 5;
596
- _t = _context.v;
597
- if (!(_t instanceof ApacuanaAPIError)) {
598
- _context.n = 6;
599
- break;
600
- }
601
- throw _t;
602
- case 6:
603
- throw new ApacuanaAPIError("Unexpected failure getting token: ".concat(_t.message || "Unknown error"));
604
- case 7:
605
- return _context.a(2);
606
- }
607
- }, _callee, null, [[2, 5]]);
608
- }));
609
- return function getCustomer() {
610
- return _ref.apply(this, arguments);
611
- };
612
- }();
613
-
614
568
  /** @typedef {import("../types/revocations").RequestRevocationResponse} RequestRevocationResponse */
615
569
  /** @typedef {import("../types/revocations").GetRevocationReasonsResponse} GetRevocationReasonsResponse */
616
570
 
@@ -622,7 +576,9 @@ var requestRevocationOnBoarding = /*#__PURE__*/function () {
622
576
  case 0:
623
577
  _context.p = 0;
624
578
  _context.n = 1;
625
- return httpRequest("services/api/onboardingclient/requestcert", params, "POST");
579
+ return httpRequest("services/api/onboardingclient/requestcert", {
580
+ reason: params.reasonCode
581
+ }, "POST");
626
582
  case 1:
627
583
  response = _context.v;
628
584
  return _context.a(2, new ApacuanaSuccess(response));
@@ -32893,7 +32849,7 @@ initCryptoEngine();
32893
32849
 
32894
32850
  var KEY_HEX = "dRgUkXp2s5v8y/B?";
32895
32851
  var getCertificateStatus = function getCertificateStatus(userData, certificateInDevice) {
32896
- var _userData$verificatio, _userData$requestscer, _userData$requestscer2;
32852
+ var _userData$verificatio, _userData$requestscer, _userData$requestscer2, _userData$requestscer3;
32897
32853
  if (!userData) {
32898
32854
  throw new Error("El parámetro userData es requerido.");
32899
32855
  }
@@ -32901,10 +32857,10 @@ var getCertificateStatus = function getCertificateStatus(userData, certificateIn
32901
32857
  throw new Error("El parámetro certificateInDevice es requerido y debe ser un valor booleano.");
32902
32858
  }
32903
32859
  if ((userData === null || userData === void 0 || (_userData$verificatio = userData.verificationstatus) === null || _userData$verificatio === void 0 ? void 0 : _userData$verificatio.id) !== VERIFICATION_STATUS.APPROVED) return STATUS_CERTIFICATE.request;
32904
- if (userData !== null && userData !== void 0 && userData.certificationId && !(userData !== null && userData !== void 0 && userData.cangenerate) && !(userData !== null && userData !== void 0 && (_userData$requestscer = userData.requestscert) !== null && _userData$requestscer !== void 0 && _userData$requestscer.pending) && !certificateInDevice && (userData === null || userData === void 0 ? void 0 : userData.certificatestatus) !== STATUS_CERTIFICATE.revoque) return STATUS_CERTIFICATE.certificate_another_device;
32905
- if (userData !== null && userData !== void 0 && (_userData$requestscer2 = userData.requestscert) !== null && _userData$requestscer2 !== void 0 && _userData$requestscer2.pending && userData !== null && userData !== void 0 && userData.certificationId) return STATUS_CERTIFICATE.request_revoque;
32860
+ if (!(userData !== null && userData !== void 0 && userData.certificationId) && (userData === null || userData === void 0 || (_userData$requestscer = userData.requestscert) === null || _userData$requestscer === void 0 ? void 0 : _userData$requestscer.requests.length) === 0) return STATUS_CERTIFICATE.request_cert;
32861
+ if (userData !== null && userData !== void 0 && userData.certificationId && !(userData !== null && userData !== void 0 && userData.cangenerate) && !(userData !== null && userData !== void 0 && (_userData$requestscer2 = userData.requestscert) !== null && _userData$requestscer2 !== void 0 && _userData$requestscer2.pending) && !certificateInDevice && (userData === null || userData === void 0 ? void 0 : userData.certificatestatus) !== STATUS_CERTIFICATE.revoque) return STATUS_CERTIFICATE.certificate_another_device;
32862
+ if (userData !== null && userData !== void 0 && (_userData$requestscer3 = userData.requestscert) !== null && _userData$requestscer3 !== void 0 && _userData$requestscer3.pending && userData !== null && userData !== void 0 && userData.certificationId) return STATUS_CERTIFICATE.request_revoque;
32906
32863
  if (!(userData !== null && userData !== void 0 && userData.cangenerate) && (userData === null || userData === void 0 ? void 0 : userData.certificatestatus) === STATUS_CERTIFICATE.revoque) return STATUS_CERTIFICATE.revoque;
32907
- if (!(userData !== null && userData !== void 0 && userData.approvedUser)) return STATUS_CERTIFICATE.request;
32908
32864
  if (userData !== null && userData !== void 0 && userData.cangenerate) return STATUS_CERTIFICATE.generate;
32909
32865
  if (userData !== null && userData !== void 0 && userData.certificationId) return STATUS_CERTIFICATE.current;
32910
32866
  return STATUS_CERTIFICATE.revoque;
@@ -32946,24 +32902,57 @@ var encryptedCsr = function encryptedCsr(csr) {
32946
32902
  };
32947
32903
  return body;
32948
32904
  };
32905
+ var createPayloadGetDigest = function createPayloadGetDigest(signData) {
32906
+ var formData = new FormData();
32907
+
32908
+ // Iterate over the object's own properties
32909
+ Object.keys(signData).forEach(function (key) {
32910
+ // Conditionally handle the 'document' field
32911
+
32912
+ if (key === "document" && signData[key] instanceof File) {
32913
+ // Append the file directly
32914
+ formData.append(key, signData[key]);
32915
+ } else if (key === "cert") {
32916
+ formData.append("publickey", signData[key]);
32917
+ }
32918
+ });
32919
+ return formData;
32920
+ };
32949
32921
  var validateOnBoardingSignerData = function validateOnBoardingSignerData(signerData) {
32950
- if (!signerData.name || typeof signerData.name !== "string") {
32922
+ // Create a copy of the original object to avoid modifying the function parameter
32923
+ var validatedSignerData = _objectSpread2({}, signerData);
32924
+ if (!validatedSignerData.name || typeof validatedSignerData.name !== "string") {
32951
32925
  throw new ApacuanaAPIError('El campo "name" es requerido y debe ser una cadena de texto.', 400, "INVALID_PARAMETER_FORMAT");
32952
32926
  }
32953
- if (!signerData.reference || typeof signerData.reference !== "string") {
32954
- throw new ApacuanaAPIError('El campo "reference" es requerido y debe ser una cadena de texto.', 400, "INVALID_PARAMETER_FORMAT");
32927
+
32928
+ // Limpia 'reference' si es inválido o está vacío.
32929
+ if (!validatedSignerData.reference || typeof validatedSignerData.reference !== "string" || validatedSignerData.reference.trim() === "") {
32930
+ delete validatedSignerData.reference;
32931
+ }
32932
+
32933
+ // Limpia 'file' si no es una instancia de File.
32934
+ if (typeof File === "undefined" || !validatedSignerData.file || !(validatedSignerData.file instanceof File)) {
32935
+ delete validatedSignerData.file;
32936
+ }
32937
+
32938
+ // Valida que solo uno de los dos campos exista después de la limpieza.
32939
+ if (validatedSignerData.reference && validatedSignerData.file) {
32940
+ throw new ApacuanaAPIError("No se pueden proporcionar 'reference' y 'file' simultáneamente.", 400, "INVALID_PARAMETER_FORMAT");
32941
+ }
32942
+ if (!validatedSignerData.reference && !validatedSignerData.file) {
32943
+ throw new ApacuanaAPIError("Se debe proporcionar un campo 'reference' o 'file' válido.", 400, "INVALID_PARAMETER_FORMAT");
32955
32944
  }
32956
32945
  var validDocTypes = ["V", "P", "E"];
32957
- if (!signerData.typedoc || !validDocTypes.includes(signerData.typedoc)) {
32946
+ if (!validatedSignerData.typedoc || !validDocTypes.includes(validatedSignerData.typedoc)) {
32958
32947
  throw new ApacuanaAPIError('El campo "typedoc" es requerido y debe ser uno de los siguientes valores: V, P, E.', 400, "INVALID_PARAMETER_FORMAT");
32959
32948
  }
32960
- if (!signerData.doc || typeof signerData.doc !== "string") {
32949
+ if (!validatedSignerData.doc || typeof validatedSignerData.doc !== "string") {
32961
32950
  throw new ApacuanaAPIError('El campo "doc" es requerido y debe ser una cadena de texto.', 400, "INVALID_PARAMETER_FORMAT");
32962
32951
  }
32963
- if (!Array.isArray(signerData.signature) || signerData.signature.length === 0) {
32952
+ if (!Array.isArray(validatedSignerData.signature) || validatedSignerData.signature.length === 0) {
32964
32953
  throw new ApacuanaAPIError('El campo "signature" es requerido y debe ser un array no vacío.', 400, "INVALID_PARAMETER_FORMAT");
32965
32954
  }
32966
- signerData.signature.forEach(function (sig, index) {
32955
+ validatedSignerData.signature.forEach(function (sig, index) {
32967
32956
  if (!Number.isInteger(sig.page) || sig.page < 1) {
32968
32957
  throw new ApacuanaAPIError("La p\xE1gina de la firma ".concat(index + 1, " debe ser un n\xFAmero entero positivo."), 400, "INVALID_PARAMETER_FORMAT");
32969
32958
  }
@@ -32974,6 +32963,17 @@ var validateOnBoardingSignerData = function validateOnBoardingSignerData(signerD
32974
32963
  throw new ApacuanaAPIError("La coordenada Y de la firma ".concat(index + 1, " debe ser un n\xFAmero entre 0 y 1."), 400, "INVALID_PARAMETER_FORMAT");
32975
32964
  }
32976
32965
  });
32966
+ var formData = new FormData();
32967
+ Object.keys(validatedSignerData).forEach(function (key) {
32968
+ if (key === "signature") {
32969
+ formData.append(key, JSON.stringify(validatedSignerData[key]));
32970
+ } else if (key === "file") {
32971
+ formData.append("document", validatedSignerData[key]);
32972
+ } else if (validatedSignerData[key] !== undefined) {
32973
+ formData.append(key, validatedSignerData[key]);
32974
+ }
32975
+ });
32976
+ return formData;
32977
32977
  };
32978
32978
  var validateCsr = function validateCsr(encryptedCSR) {
32979
32979
  if (!encryptedCSR || _typeof(encryptedCSR) !== "object" || !encryptedCSR.csr || typeof encryptedCSR.csr !== "string" || encryptedCSR.csr.trim() === "") {
@@ -33014,6 +33014,21 @@ var validateOnBoardingSignDocumentData = function validateOnBoardingSignDocument
33014
33014
  if (!signedDigest || typeof signedDigest !== "string") {
33015
33015
  throw new ApacuanaAPIError("Signed digest 'signedDigest' is required and must be a string.", 400, "INVALID_PARAMETER");
33016
33016
  }
33017
+ var formData = new FormData();
33018
+ formData.append("positions", JSON.stringify(signature.positions.map(function (p) {
33019
+ return {
33020
+ x: p.x,
33021
+ y: p.y,
33022
+ page: p.page,
33023
+ status: 1
33024
+ };
33025
+ })));
33026
+ formData.append("publickey", cert);
33027
+ formData.append("signeddigest", signedDigest);
33028
+ if (signData.document && signData.document instanceof File) {
33029
+ formData.append("document", signData.document);
33030
+ }
33031
+ return formData;
33017
33032
  };
33018
33033
  var helpers = {
33019
33034
  getCertificateStatus: getCertificateStatus,
@@ -33024,7 +33039,8 @@ var helpers = {
33024
33039
  validateCsr: validateCsr,
33025
33040
  validateGetDocsData: validateGetDocsData,
33026
33041
  validateGetDigestData: validateGetDigestData,
33027
- validateOnBoardingSignDocumentData: validateOnBoardingSignDocumentData
33042
+ validateOnBoardingSignDocumentData: validateOnBoardingSignDocumentData,
33043
+ createPayloadGetDigest: createPayloadGetDigest
33028
33044
  };
33029
33045
 
33030
33046
  /**
@@ -33134,8 +33150,9 @@ var getCertStatus = function getCertStatus() {
33134
33150
  var isCertificateInDevice = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
33135
33151
  var config = getConfig();
33136
33152
  var status = helpers.getCertificateStatus(config.userData, isCertificateInDevice);
33153
+ var parseStatus = PARSE_STATUS[status];
33137
33154
  return new ApacuanaSuccess({
33138
- status: status
33155
+ status: parseStatus
33139
33156
  });
33140
33157
  };
33141
33158
  var getCertTypesOnBoarding = /*#__PURE__*/function () {
@@ -33311,95 +33328,6 @@ var getRequerimentsByTypeUser = /*#__PURE__*/function () {
33311
33328
  return _ref9.apply(this, arguments);
33312
33329
  };
33313
33330
  }();
33314
- var requestCertificateOnBoarding = /*#__PURE__*/function () {
33315
- var _ref0 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0(params) {
33316
- var response, _t4;
33317
- return _regenerator().w(function (_context0) {
33318
- while (1) switch (_context0.p = _context0.n) {
33319
- case 0:
33320
- _context0.p = 0;
33321
- _context0.n = 1;
33322
- return httpRequest("services/api/customer/request-certificate", params, "POST");
33323
- case 1:
33324
- response = _context0.v;
33325
- return _context0.a(2, new ApacuanaSuccess(response));
33326
- case 2:
33327
- _context0.p = 2;
33328
- _t4 = _context0.v;
33329
- if (!(_t4 instanceof ApacuanaAPIError)) {
33330
- _context0.n = 3;
33331
- break;
33332
- }
33333
- throw _t4;
33334
- case 3:
33335
- throw new Error("Failed to request certificate: ".concat(_t4.message));
33336
- case 4:
33337
- return _context0.a(2);
33338
- }
33339
- }, _callee0, null, [[0, 2]]);
33340
- }));
33341
- return function requestCertificateOnBoarding(_x5) {
33342
- return _ref0.apply(this, arguments);
33343
- };
33344
- }();
33345
- var requestCertificateOnPremise = /*#__PURE__*/function () {
33346
- var _ref1 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1() {
33347
- return _regenerator().w(function (_context1) {
33348
- while (1) switch (_context1.n) {
33349
- case 0:
33350
- throw new ApacuanaAPIError("Requesting a certificate is not supported for integration type: ONPREMISE", 501, "NOT_IMPLEMENTED");
33351
- case 1:
33352
- return _context1.a(2);
33353
- }
33354
- }, _callee1);
33355
- }));
33356
- return function requestCertificateOnPremise() {
33357
- return _ref1.apply(this, arguments);
33358
- };
33359
- }();
33360
-
33361
- /**
33362
- * Requests a certificate for the user.
33363
- * @param {CertificateRequestParams} params - The parameters for the certificate request.
33364
- * @returns {Promise<RequestCertificateResponse>} Object with a confirmation message and a success indicator.
33365
- * @throws {ApacuanaAPIError} If the API response is invalid or the integration type is not supported.
33366
- * @throws {Error} If the request fails for another reason or the params are invalid.
33367
- */
33368
- var requestCertificate = /*#__PURE__*/function () {
33369
- var _ref10 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10(params) {
33370
- var _getConfig4, integrationType;
33371
- return _regenerator().w(function (_context10) {
33372
- while (1) switch (_context10.n) {
33373
- case 0:
33374
- if (!(!params || typeof params.type !== "number" || !Array.isArray(params.documents))) {
33375
- _context10.n = 1;
33376
- break;
33377
- }
33378
- throw new Error('The "params" object with a numeric "type" property and a "documents" array is required.');
33379
- case 1:
33380
- _getConfig4 = getConfig(), integrationType = _getConfig4.integrationType;
33381
- if (!(integrationType === INTEGRATION_TYPE.ONBOARDING)) {
33382
- _context10.n = 2;
33383
- break;
33384
- }
33385
- return _context10.a(2, requestCertificateOnBoarding(params));
33386
- case 2:
33387
- if (!(integrationType === INTEGRATION_TYPE.ONPREMISE)) {
33388
- _context10.n = 3;
33389
- break;
33390
- }
33391
- return _context10.a(2, requestCertificateOnPremise());
33392
- case 3:
33393
- throw new ApacuanaAPIError("Unsupported integration type: ".concat(integrationType), 400, "UNSUPPORTED_INTEGRATION_TYPE");
33394
- case 4:
33395
- return _context10.a(2);
33396
- }
33397
- }, _callee10);
33398
- }));
33399
- return function requestCertificate(_x6) {
33400
- return _ref10.apply(this, arguments);
33401
- };
33402
- }();
33403
33331
 
33404
33332
  /** @typedef {import("../types/signatures").Signer} Signer */
33405
33333
  /** @typedef {import("../types/signatures").SignerData} SignerData */
@@ -33418,27 +33346,15 @@ var requestCertificate = /*#__PURE__*/function () {
33418
33346
 
33419
33347
  var signDocumentOnBoarding = /*#__PURE__*/function () {
33420
33348
  var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(signData) {
33421
- var signature, cert, signedDigest, signBody, response, _t;
33349
+ var payload, signature, response, _t;
33422
33350
  return _regenerator().w(function (_context) {
33423
33351
  while (1) switch (_context.p = _context.n) {
33424
33352
  case 0:
33425
- helpers.validateOnBoardingSignDocumentData(signData);
33426
- signature = signData.signature, cert = signData.cert, signedDigest = signData.signedDigest;
33353
+ payload = helpers.validateOnBoardingSignDocumentData(signData);
33354
+ signature = signData.signature;
33427
33355
  _context.p = 1;
33428
- signBody = {
33429
- positions: JSON.stringify(signature.positions.map(function (p) {
33430
- return {
33431
- x: p.x,
33432
- y: p.y,
33433
- page: p.page,
33434
- status: 1
33435
- };
33436
- })),
33437
- publickey: cert,
33438
- signeddigest: signedDigest
33439
- };
33440
33356
  _context.n = 2;
33441
- return httpRequest("services/api/documents/sign/".concat(signature.id), signBody, "PUT");
33357
+ return httpRequest("services/api/documents/sign/".concat(signature.id), payload, "PUT");
33442
33358
  case 2:
33443
33359
  response = _context.v;
33444
33360
  return _context.a(2, new ApacuanaSuccess(response));
@@ -33478,15 +33394,14 @@ var signDocumentOnPremise = /*#__PURE__*/function () {
33478
33394
  }();
33479
33395
  var getDigestToSignOnBoarding = /*#__PURE__*/function () {
33480
33396
  var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(signData) {
33481
- var _response$data, response, digest, _t2;
33397
+ var _response$data, formData, response, digest, _t2;
33482
33398
  return _regenerator().w(function (_context3) {
33483
33399
  while (1) switch (_context3.p = _context3.n) {
33484
33400
  case 0:
33485
33401
  _context3.p = 0;
33402
+ formData = helpers.createPayloadGetDigest(signData);
33486
33403
  _context3.n = 1;
33487
- return httpRequest("services/api/documents/getdigest/".concat(signData.signatureId), {
33488
- publickey: signData.cert
33489
- }, "POST");
33404
+ return httpRequest("services/api/documents/getdigest/".concat(signData.signatureId), formData, "POST");
33490
33405
  case 1:
33491
33406
  response = _context3.v;
33492
33407
  digest = ((_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.digest) || response.digest;
@@ -33535,14 +33450,14 @@ var getDigestToSignOnPremise = /*#__PURE__*/function () {
33535
33450
  }();
33536
33451
  var addSignerOnBoarding = /*#__PURE__*/function () {
33537
33452
  var _ref5 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(signerData) {
33538
- var _t3;
33453
+ var payload, _t3;
33539
33454
  return _regenerator().w(function (_context5) {
33540
33455
  while (1) switch (_context5.p = _context5.n) {
33541
33456
  case 0:
33542
- helpers.validateOnBoardingSignerData(signerData);
33457
+ payload = helpers.validateOnBoardingSignerData(signerData);
33543
33458
  _context5.p = 1;
33544
33459
  _context5.n = 2;
33545
- return httpRequest("services/api/documents/signing", signerData, "POST");
33460
+ return httpRequest("services/api/documents/signingsdk", payload, "POST");
33546
33461
  case 2:
33547
33462
  return _context5.a(2, new ApacuanaSuccess({
33548
33463
  signer: signerData.typedoc + signerData.doc
@@ -34281,18 +34196,158 @@ var validateFaceLiveness = /*#__PURE__*/function () {
34281
34196
  };
34282
34197
  }();
34283
34198
 
34199
+ /**
34200
+ * @typedef {object} GetCustomerData
34201
+ * @property {string} token - El token de sesión del usuario.
34202
+ * @property {object} userData - Los datos del usuario obtenidos.
34203
+ */
34204
+
34205
+ /**
34206
+ * @typedef {object} GetCustomerResponse
34207
+ * @property {true} success - Indica que la operación fue exitosa.
34208
+ * @property {GetCustomerData} data - El payload de la respuesta.
34209
+ */
34210
+
34211
+ /**
34212
+ * Obtiene el token de un usuario a través de una petición POST.
34213
+ * Este método es útil para endpoints que requieren datos en el cuerpo de la petición
34214
+ * para buscar un usuario, como un ID de sesión o un token de acceso.
34215
+ *
34216
+ * @returns {Promise<GetCustomerResponse>} Una promesa que resuelve a un objeto con la respuesta exitosa.
34217
+ * @throws {Error} Si los parámetros de entrada son inválidos.
34218
+ * @throws {ApacuanaAPIError} Si ocurre un error en la API de Apacuana.
34219
+ */
34220
+ var getCustomer = /*#__PURE__*/function () {
34221
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
34222
+ var _getConfig, verificationId, customerId, body, response, _t;
34223
+ return _regenerator().w(function (_context) {
34224
+ while (1) switch (_context.p = _context.n) {
34225
+ case 0:
34226
+ _getConfig = getConfig(), verificationId = _getConfig.verificationId, customerId = _getConfig.customerId;
34227
+ if (!(!verificationId || !customerId)) {
34228
+ _context.n = 1;
34229
+ break;
34230
+ }
34231
+ throw new ApacuanaAPIError("Both 'verificationId' and 'customerId' must be configured.", 400, "CONFIGURATION_ERROR");
34232
+ case 1:
34233
+ body = {
34234
+ verificationid: verificationId,
34235
+ customerid: customerId
34236
+ };
34237
+ _context.p = 2;
34238
+ _context.n = 3;
34239
+ return httpRequest("services/api/register/init", body, "POST");
34240
+ case 3:
34241
+ response = _context.v;
34242
+ if (!(!response.sessionid || !response.entry)) {
34243
+ _context.n = 4;
34244
+ break;
34245
+ }
34246
+ throw new ApacuanaAPIError("The API response does not contain the user.", 200, "INVALID_API_RESPONSE");
34247
+ case 4:
34248
+ return _context.a(2, new ApacuanaSuccess({
34249
+ token: response.sessionid,
34250
+ userData: response.entry
34251
+ }));
34252
+ case 5:
34253
+ _context.p = 5;
34254
+ _t = _context.v;
34255
+ if (!(_t instanceof ApacuanaAPIError)) {
34256
+ _context.n = 6;
34257
+ break;
34258
+ }
34259
+ throw _t;
34260
+ case 6:
34261
+ throw new ApacuanaAPIError("Unexpected failure getting token: ".concat(_t.message || "Unknown error"));
34262
+ case 7:
34263
+ return _context.a(2);
34264
+ }
34265
+ }, _callee, null, [[2, 5]]);
34266
+ }));
34267
+ return function getCustomer() {
34268
+ return _ref.apply(this, arguments);
34269
+ };
34270
+ }();
34271
+
34272
+ /**
34273
+ * @typedef {object} CreateUserPayload
34274
+ * @property {string} usr - Correo electrónico del usuario.
34275
+ * @property {string} pwd - Contraseña del usuario.
34276
+ * @property {string} kinddoc - Tipo de documento de identidad (ej. 'V', 'P', 'E').
34277
+ * @property {string} doc - Número de documento de identidad.
34278
+ */
34279
+
34280
+ /**
34281
+ * @typedef {object} CreateUserResponse
34282
+ * @property {string} message - Mensaje de confirmación de la creación del usuario.
34283
+ */
34284
+
34285
+ /**
34286
+ * Crea un nuevo usuario en la plataforma de Apacuana.
34287
+ * @param {CreateUserPayload} userData - Objeto con los datos del usuario a crear.
34288
+ * @returns {Promise<ApacuanaSuccess>} Una promesa que resuelve a un objeto con la respuesta exitosa.
34289
+ * @throws {ApacuanaAPIError} Si los datos de entrada son inválidos o si ocurre un error en la API.
34290
+ */
34291
+
34292
+ var createApacuanaUser = /*#__PURE__*/function () {
34293
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(userData) {
34294
+ var formData, response, _t2;
34295
+ return _regenerator().w(function (_context2) {
34296
+ while (1) switch (_context2.p = _context2.n) {
34297
+ case 0:
34298
+ _context2.p = 0;
34299
+ formData = new FormData();
34300
+ Object.keys(userData).forEach(function (key) {
34301
+ var value = userData[key];
34302
+ if (value instanceof File) {
34303
+ formData.append(key, value);
34304
+ } else if (value !== null && value !== undefined) {
34305
+ formData.append(key, String(value));
34306
+ }
34307
+ });
34308
+ _context2.n = 1;
34309
+ return httpRequest("services/api/register/initial", formData, "POST");
34310
+ case 1:
34311
+ response = _context2.v;
34312
+ return _context2.a(2, new ApacuanaSuccess(_objectSpread2({}, response)));
34313
+ case 2:
34314
+ _context2.p = 2;
34315
+ _t2 = _context2.v;
34316
+ if (!(_t2 instanceof ApacuanaAPIError)) {
34317
+ _context2.n = 3;
34318
+ break;
34319
+ }
34320
+ throw _t2;
34321
+ case 3:
34322
+ throw new ApacuanaAPIError("Unexpected failure creating user: ".concat(_t2.message || "Unknown error"));
34323
+ case 4:
34324
+ return _context2.a(2);
34325
+ }
34326
+ }, _callee2, null, [[0, 2]]);
34327
+ }));
34328
+ return function createApacuanaUser(_x) {
34329
+ return _ref2.apply(this, arguments);
34330
+ };
34331
+ }();
34332
+
34333
+ /**
34334
+ * Valida si el SDK está inicializado y si se dispone de un customerId.
34335
+ * @param {boolean} requiresCustomerId - Indica si la operación necesita un customerId.
34336
+ * @throws {ApacuanaAPIError} Si el SDK no está inicializado o el customerId es requerido y no está presente.
34337
+ */
34338
+ var checkSdk = function checkSdk() {
34339
+ var requiresCustomerId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
34340
+ var config = getConfig();
34341
+ if (!config || !config.apiUrl) {
34342
+ throw new ApacuanaAPIError("El SDK no está inicializado. Llama a apacuana.init() primero.", 400, "NOT_INITIALIZED_ERROR");
34343
+ }
34344
+ if (requiresCustomerId && !config.customerId) {
34345
+ throw new ApacuanaAPIError("Se requiere un CustomerId para esta operación. Por favor, inicia sesión.", 403, "CUSTOMER_ID_REQUIRED");
34346
+ }
34347
+ };
34284
34348
  var apacuana = {
34285
34349
  /**
34286
- * Inicializa el Apacuana SDK con la configuración necesaria y obtiene
34287
- * los detalles del usuario.
34288
- * @param {object} config - Objeto de configuración.
34289
- * @param {string} config.apiUrl - La URL base de la API de Apacuana.
34290
- * @param {string} config.secretKey - La clave secreta para la autenticación.
34291
- * @param {string} config.apiKey - La clave de API para la autenticación.
34292
- * @param {string} config.verificationId - El ID de verificación del usuario.
34293
- * @param {string} config.customerId - El ID del cliente.
34294
- * @param {string} config.integrationType - El tipo de integración ('onpremise' o 'onboarding').
34295
- * @returns {Promise<object>} retorna los detalles del usuario si la inicialización es exitosa.
34350
+ * Inicializa el Apacuana SDK con la configuración necesaria.
34296
34351
  */
34297
34352
  init: function () {
34298
34353
  var _init = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(config) {
@@ -34304,17 +34359,13 @@ var apacuana = {
34304
34359
  setConfig(config);
34305
34360
  initHttpClient();
34306
34361
  currentConfig = getConfig();
34307
- if (currentConfig.customerId) {
34308
- _context.n = 1;
34362
+ if (!currentConfig.customerId) {
34363
+ _context.n = 2;
34309
34364
  break;
34310
34365
  }
34311
- throw new ApacuanaAPIError("Apacuana SDK: La configuración de CustomerId no se ha guardado" + " correctamente.", 400, {
34312
- code: "CONFIG_ERROR"
34313
- });
34314
- case 1:
34315
- _context.n = 2;
34366
+ _context.n = 1;
34316
34367
  return getCustomer();
34317
- case 2:
34368
+ case 1:
34318
34369
  customer = _context.v;
34319
34370
  _customer$data = customer.data, token = _customer$data.token, userData = _customer$data.userData;
34320
34371
  setConfig(_objectSpread2(_objectSpread2({}, currentConfig), {}, {
@@ -34324,12 +34375,16 @@ var apacuana = {
34324
34375
  setAuthToken(token);
34325
34376
  return _context.a(2, new ApacuanaSuccess({
34326
34377
  initialized: true,
34327
- message: "SDK inicializado correctamente."
34378
+ message: "SDK inicializado con sesión de usuario."
34379
+ }));
34380
+ case 2:
34381
+ return _context.a(2, new ApacuanaSuccess({
34382
+ initialized: true,
34383
+ message: "SDK inicializado para operaciones públicas (sin customerId)."
34328
34384
  }));
34329
34385
  case 3:
34330
34386
  _context.p = 3;
34331
34387
  _t = _context.v;
34332
- // eslint-disable-next-line no-console
34333
34388
  console.error("Error durante la inicialización del SDK:", _t);
34334
34389
  if (!(_t instanceof ApacuanaAPIError)) {
34335
34390
  _context.n = 4;
@@ -34348,30 +34403,81 @@ var apacuana = {
34348
34403
  }
34349
34404
  return init;
34350
34405
  }(),
34351
- /**
34352
- * Permite obtener la configuración actual del SDK.
34353
- */
34406
+ // --- Métodos de Revocación ---
34407
+ requestRevocation: function requestRevocation$1(data) {
34408
+ checkSdk(true);
34409
+ return requestRevocation(data);
34410
+ },
34411
+ getRevocationReasons: function getRevocationReasons$1() {
34412
+ checkSdk(true);
34413
+ return getRevocationReasons();
34414
+ },
34415
+ // --- Métodos de Certificados ---
34416
+ generateCert: function generateCert$1(data) {
34417
+ checkSdk(true);
34418
+ return generateCert(data);
34419
+ },
34420
+ getCertStatus: function getCertStatus$1(isCertificateInDevice) {
34421
+ checkSdk(true);
34422
+ return getCertStatus(isCertificateInDevice);
34423
+ },
34424
+ getCertTypes: function getCertTypes$1() {
34425
+ checkSdk(false);
34426
+ return getCertTypes();
34427
+ },
34428
+ getRequerimentsByTypeUser: function getRequerimentsByTypeUser$1(data) {
34429
+ checkSdk(false);
34430
+ return getRequerimentsByTypeUser(data);
34431
+ },
34432
+ // --- Métodos de Firmas y Documentos ---
34433
+ addSigner: function addSigner$1(data) {
34434
+ checkSdk(true);
34435
+ return addSigner(data);
34436
+ },
34437
+ deleteSignatureVariant: function deleteSignatureVariant$1() {
34438
+ checkSdk(true);
34439
+ return deleteSignatureVariant();
34440
+ },
34441
+ getDigest: function getDigest$1(data) {
34442
+ checkSdk(true);
34443
+ return getDigest(data);
34444
+ },
34445
+ getDocs: function getDocs$1(data) {
34446
+ checkSdk(true);
34447
+ return getDocs(data);
34448
+ },
34449
+ getSignatureVariant: function getSignatureVariant$1() {
34450
+ checkSdk(true);
34451
+ return getSignatureVariant();
34452
+ },
34453
+ signDocument: function signDocument$1(data) {
34454
+ checkSdk(true);
34455
+ return signDocument(data);
34456
+ },
34457
+ uploadSignatureVariant: function uploadSignatureVariant$1(data) {
34458
+ checkSdk(true);
34459
+ return uploadSignatureVariant(data);
34460
+ },
34461
+ getCustomer: function getCustomer$1() {
34462
+ checkSdk(true);
34463
+ return getCustomer();
34464
+ },
34465
+ createFaceLivenessSession: function createFaceLivenessSession$1() {
34466
+ checkSdk(true);
34467
+ return createFaceLivenessSession();
34468
+ },
34469
+ createApacuanaUser: function createApacuanaUser$1(data) {
34470
+ checkSdk(false);
34471
+ return createApacuanaUser(data);
34472
+ },
34473
+ validateFaceLiveness: function validateFaceLiveness$1(data) {
34474
+ checkSdk(true);
34475
+ return validateFaceLiveness(data);
34476
+ },
34354
34477
  close: function close$1() {
34355
34478
  return close();
34356
34479
  },
34357
- getConfig: getConfig,
34358
- requestRevocation: requestRevocation,
34359
- getCertStatus: getCertStatus,
34360
- getCustomer: getCustomer,
34361
- addSigner: addSigner,
34362
- getDocs: getDocs,
34363
- generateCert: generateCert,
34364
- signDocument: signDocument,
34365
- getDigest: getDigest,
34366
- getRevocationReasons: getRevocationReasons,
34367
- uploadSignatureVariant: uploadSignatureVariant,
34368
- getSignatureVariant: getSignatureVariant,
34369
- deleteSignatureVariant: deleteSignatureVariant,
34370
- getCertTypes: getCertTypes,
34371
- getRequerimentsByTypeUser: getRequerimentsByTypeUser,
34372
- createFaceLivenessSession: createFaceLivenessSession,
34373
- validateFaceLiveness: validateFaceLiveness,
34374
- requestCertificate: requestCertificate
34480
+ getConfig: getConfig
34375
34481
  };
34376
34482
 
34377
34483
  export { apacuana as default };