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