@mp-front/common 0.0.2-next.0 → 0.0.2-next.2

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.
@@ -1,80 +1,151 @@
1
- var E = Object.defineProperty;
2
- var p = (u, e, t) => e in u ? E(u, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : u[e] = t;
3
- var g = (u, e, t) => p(u, typeof e != "symbol" ? e + "" : e, t);
4
- import { R as c, a as f } from "./default-errors-DsKmUZbG.js";
5
- import { E as J, c as M } from "./default-errors-DsKmUZbG.js";
6
- import { t as U } from "./i18n-CEBemBIX.js";
7
- import { a as L, b as F, H as P } from "./client-DKI6Ntcl.js";
8
- import { firstValueFrom as D, of as a, switchMap as l, forkJoin as h } from "rxjs";
9
- import { L as R } from "./logger-DtlFWyFO.js";
1
+ var f = Object.defineProperty;
2
+ var E = (u, r, t) => r in u ? f(u, r, { enumerable: !0, configurable: !0, writable: !0, value: t }) : u[r] = t;
3
+ var m = (u, r, t) => E(u, typeof r != "symbol" ? r + "" : r, t);
4
+ import { R, a as c } from "./default-errors-DsKmUZbG.js";
5
+ import { E as U, c as T } from "./default-errors-DsKmUZbG.js";
6
+ import { t as L } from "./i18n-CEBemBIX.js";
7
+ import { R as S } from "./client-DuXI9Ldu.js";
8
+ import { a as Q, b as k, H as B } from "./client-DuXI9Ldu.js";
9
+ import { firstValueFrom as d, of as a, switchMap as D, forkJoin as l } from "rxjs";
10
+ import { L as b } from "./logger-DtlFWyFO.js";
10
11
  import { E as I } from "./encoder-CXAlLf5T.js";
11
12
  import "node-jose";
12
13
  import "crypto";
13
- class N {
14
+ class J {
14
15
  constructor() {
15
- g(this, "encoder", new I());
16
- g(this, "logger", new R());
17
- g(this, "requestID", "");
18
- g(this, "session", null);
16
+ m(this, "encoder", new I());
17
+ m(this, "logger", new b());
18
+ m(this, "requestID", "");
19
+ m(this, "session", null);
19
20
  }
20
- setSession(e) {
21
- this.session = e;
21
+ /**
22
+ * Establece la sesión de usuario para el middleware.
23
+ *
24
+ * @param {Session} session - Sesión de NextAuth
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * const middleware = new ApiMiddleware()
29
+ * middleware.setSession(session)
30
+ * ```
31
+ */
32
+ setSession(r) {
33
+ this.session = r;
22
34
  }
35
+ /**
36
+ * Obtiene la sesión de usuario actual.
37
+ *
38
+ * @returns {Session} La sesión de usuario activa
39
+ * @throws {RuntimeError} Si no hay sesión establecida
40
+ *
41
+ * @example
42
+ * ```typescript
43
+ * const session = this.getSession()
44
+ * console.log('Usuario:', session.user.email)
45
+ * ```
46
+ */
23
47
  getSession() {
24
48
  if (!this.session)
25
- throw new c(
26
- f.AUTHENTICATION_ERROR,
49
+ throw new R(
50
+ c.AUTHENTICATION_ERROR,
27
51
  this.requestID
28
52
  );
29
53
  return this.session;
30
54
  }
31
- returnData(e, t) {
32
- const r = this.encoder.encode(e, t);
33
- return new Response(r, { status: 200 });
55
+ /**
56
+ * Retorna una respuesta HTTP exitosa con datos codificados.
57
+ *
58
+ * @template ApiMiddlewareResponse - Tipo de la respuesta
59
+ * @param {ApiMiddlewareResponse} response - Datos de respuesta
60
+ * @param {string} requestID - ID de la petición (opcional)
61
+ * @returns {Response} Respuesta HTTP con status 200
62
+ */
63
+ returnData(r, t) {
64
+ const e = this.encoder.encode(r, t);
65
+ return new Response(e, { status: 200 });
34
66
  }
35
- returnError(e) {
36
- return new Response(JSON.stringify(e), { status: 520 });
67
+ /**
68
+ * Retorna una respuesta HTTP de error.
69
+ *
70
+ * @param {RuntimeError} error - Error a retornar
71
+ * @returns {Response} Respuesta HTTP con status 520
72
+ */
73
+ returnError(r) {
74
+ return new Response(JSON.stringify(r), { status: 520 });
37
75
  }
38
- async getBody(e) {
39
- if (e.method === "GET") {
40
- const { searchParams: o } = new URL(e.url);
41
- if (o != null && o.entries()) {
42
- const s = [...o.entries()].reduce(
43
- (n, [d, m]) => (n[d] = m, n),
76
+ async getBody(r) {
77
+ if (r.method === "GET") {
78
+ const { searchParams: i } = new URL(r.url);
79
+ if (i != null && i.entries()) {
80
+ const s = [...i.entries()].reduce(
81
+ (n, [g, h]) => (n[g] = h, n),
44
82
  {}
45
- ), i = s.requestID ?? "";
46
- return { data: s, requestID: i };
83
+ ), o = s.requestID ?? "";
84
+ return { data: s, requestID: o };
47
85
  }
48
86
  return { data: {}, requestID: "" };
49
87
  }
50
- const t = await e.json(), r = (t == null ? void 0 : t.requestID) ?? "";
51
- return { data: t, requestID: r };
88
+ const t = await r.json(), e = (t == null ? void 0 : t.requestID) ?? "";
89
+ return { data: t, requestID: e };
52
90
  }
53
- get(e) {
91
+ transformFormData(r) {
92
+ return r.entries().reduce(
93
+ (t, e) => {
94
+ const [i, s] = e;
95
+ return S === i ? t : s instanceof File ? (t.files = [...t.files, s], t) : (t.params[i] = s, t);
96
+ },
97
+ { params: {}, files: [] }
98
+ );
99
+ }
100
+ /**
101
+ * Crea un manejador de peticiones HTTP con codificación/decodificación automática.
102
+ *
103
+ * @template ApiMiddlewareRequest - Tipo de los parámetros de entrada
104
+ * @template ApiMiddlewareResponse - Tipo de la respuesta (por defecto igual a ApiMiddlewareRequest)
105
+ * @param {function} handle - Función que procesa la petición
106
+ * @returns {function} Manejador de peticiones para Next.js API routes
107
+ *
108
+ * @example
109
+ * ```typescript
110
+ * const createUser = this.get<CreateUserRequest, CreateUserResponse>(
111
+ * (params, { requestID, headers }) => {
112
+ * // Validación
113
+ * if (!params.email) {
114
+ * throw new RuntimeError('VALIDATION_ERROR', requestID)
115
+ * }
116
+ *
117
+ * // Lógica de negocio
118
+ * return of({ id: generateId(), ...params })
119
+ * }
120
+ * )
121
+ * ```
122
+ */
123
+ get(r) {
54
124
  return this.logger.logDebug("get ApiMiddleware"), async (t) => {
55
- const { data: r, requestID: o } = await this.getBody(t);
56
- this.logger.logDebug("return ApiMiddleware", JSON.stringify(r)), this.requestID = o;
125
+ const { data: e, requestID: i } = await this.getBody(t);
126
+ this.logger.logDebug("return ApiMiddleware", JSON.stringify(e)), this.requestID = i;
57
127
  try {
58
- const s = await D(
128
+ const s = await d(
59
129
  a(t).pipe(
60
- l(
61
- (i) => h({
62
- params: a(this.encoder.decode(r)),
63
- headers: a(i.headers)
130
+ D(
131
+ (o) => l({
132
+ params: a(this.encoder.decode(e)),
133
+ headers: a(o.headers)
64
134
  })
65
135
  ),
66
- l(
67
- ({ params: i, headers: n }) => h({
68
- response: e(i, {
136
+ D(
137
+ ({ params: o, headers: n }) => l({
138
+ response: r({
139
+ params: o,
69
140
  requestID: this.requestID,
70
141
  headers: n
71
142
  }),
72
143
  headers: a(n),
73
- params: a(i)
144
+ params: a(o)
74
145
  })
75
146
  ),
76
- l(({ params: i, response: n, headers: d }) => (this.logger.logDebug(
77
- `ApiMiddleware \x1B[37m <URL>: \x1B[33m ${t.url} \x1B[37m <HEADERS>: \x1B[33m ${JSON.stringify(d)} \x1B[37m <REQUEST ID> \x1B[33m ${this.requestID} \x1B[37m <PARAMS> \x1B[33m ${JSON.stringify(i)} \x1B[37m <RESPONSE>: \x1B[33m ${JSON.stringify(n)}`
147
+ D(({ params: o, response: n, headers: g }) => (this.logger.logDebug(
148
+ `ApiMiddleware \\x1b[37m <URL>: \\x1b[33m ${t.url} \\x1b[37m <HEADERS>: \\x1b[33m ${JSON.stringify(g)} \\x1b[37m <REQUEST ID> \\x1b[33m ${this.requestID} \\x1b[37m <PARAMS> \\x1b[33m ${JSON.stringify(o)} \\x1b[37m <RESPONSE>: \\x1b[33m ${JSON.stringify(n)}`
78
149
  ), a(n)))
79
150
  )
80
151
  );
@@ -89,38 +160,58 @@ class N {
89
160
  }
90
161
  };
91
162
  }
92
- getFile(e) {
93
- return this.logger.logDebug("get File ApiMiddleware"), async (t) => {
163
+ /**
164
+ * Crea un manejador de peticiones para datos de formulario con archivos.
165
+ *
166
+ * @template ApiMiddlewareResponse - Tipo de la respuesta
167
+ * @template ApiMiddlewareRequest - Tipo de los parámetros (por defecto object)
168
+ * @param {function} handle - Función que procesa la petición con archivos
169
+ * @returns {function} Manejador de peticiones para Next.js API routes
170
+ *
171
+ * @example
172
+ * ```typescript
173
+ * const uploadFiles = this.getFormData<UploadResponse>(
174
+ * (params, files) => {
175
+ * console.log('Archivos recibidos:', files.length)
176
+ * return of({
177
+ * uploadedFiles: files.map(f => ({
178
+ * name: f.name,
179
+ * size: f.size
180
+ * }))
181
+ * })
182
+ * }
183
+ * )
184
+ * ```
185
+ */
186
+ getFormData(r) {
187
+ return this.logger.logDebug("get FormData ApiMiddleware"), async (t) => {
94
188
  try {
95
- const r = await t.formData(), o = r.get("file");
96
- this.requestID = r.get("requestID");
97
- const s = await D(
98
- e(o).pipe(
99
- l((i) => (this.logger.logDebug(
100
- `ApiMiddleware \x1B[37m <URL>: \x1B[33m ${t.url} \x1B[37m <REQUEST ID> \x1B[33m ${this.requestID} \x1B[37m <RESPONSE>: \x1B[33m ${JSON.stringify(i)}`
101
- ), a(i)))
189
+ const e = await t.formData(), { params: i, files: s } = this.transformFormData(e);
190
+ this.requestID = e.get("requestID");
191
+ const o = t.headers, n = await d(
192
+ r({ params: i, headers: o, files: s, requestID: this.requestID }).pipe(
193
+ D((g) => (this.logger.logDebug(
194
+ `ApiMiddleware FormData \\x1b[37m <URL>: \\x1b[33m ${t.url} \\x1b[37m <HEADERS>: \\x1b[33m ${JSON.stringify(o)} \\x1b[37m <REQUEST ID> \\x1b[33m ${this.requestID} \\x1b[37m <PARAMS> \\x1b[33m ${JSON.stringify(i)} \\x1b[37m <RESPONSE>: \\x1b[33m ${JSON.stringify(g)}`
195
+ ), a(g)))
102
196
  )
103
197
  );
104
- return this.logger.logDebug(
105
- "ApiMiddleware File subscribe next",
106
- JSON.stringify(s)
107
- ), this.returnData(s, this.requestID);
108
- } catch (r) {
198
+ return this.returnData(n, this.requestID);
199
+ } catch (e) {
109
200
  return this.logger.logError(
110
- `ApiMiddleware <URL>: ${t == null ? void 0 : t.url} <HEADERS>: ${JSON.stringify(t == null ? void 0 : t.headers)} <REQUEST ID> ${this.requestID} <PARAMS> ${JSON.stringify(t == null ? void 0 : t.body)} <ERROR>: ${JSON.stringify(r)}`
111
- ), this.returnError({ ...r, requestID: this.requestID });
201
+ `ApiMiddleware FormData <URL>: ${t == null ? void 0 : t.url} <HEADERS>: ${JSON.stringify(t == null ? void 0 : t.headers)} <REQUEST ID> ${this.requestID} <PARAMS> ${JSON.stringify(t == null ? void 0 : t.body)} <ERROR>: ${JSON.stringify(e)}`
202
+ ), this.returnError({ ...e, requestID: this.requestID });
112
203
  }
113
204
  };
114
205
  }
115
206
  }
116
207
  export {
117
- N as ApiMiddleware,
118
- J as ErrorHandler,
119
- L as HttpBackend,
120
- F as HttpClient,
121
- P as HttpHeaders,
122
- c as RuntimeError,
123
- f as RuntimeErrorCode,
124
- M as commonErrors,
125
- U as errorTranslations
208
+ J as ApiMiddleware,
209
+ U as ErrorHandler,
210
+ Q as HttpBackend,
211
+ k as HttpClient,
212
+ B as HttpHeaders,
213
+ R as RuntimeError,
214
+ c as RuntimeErrorCode,
215
+ T as commonErrors,
216
+ L as errorTranslations
126
217
  };
@@ -1 +1 @@
1
- "use strict";var T=Object.defineProperty;var C=(i,e,s)=>e in i?T(i,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[e]=s;var n=(i,e,s)=>C(i,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("./redis-cache-D9CzfYgO.cjs"),_=require("./logger-BMbeDoGU.cjs");require("./lodash-DNCgFYS7.cjs");require("node-jose");require("crypto");const G=require("./v5-BTqP79vV.cjs"),A=process.env.TIMEOUT_SESSION_MINUTES,N=process.env.PREFIX_TERMINAL||"PF:TERMINAL:",$="619abad7-0dea-46c5-aa49-fc1ec872a684",u="TERMINAL";class w{constructor(){n(this,"logger",new _.Logger);n(this,"redisCache",new S.RedisCache)}getIdApi(e){const s=G.v5(e,$);return`${N}${s}`}async set(e,s){return this.redisCache.set({prefix:this.getIdApi(e),idData:u,body:s,expire:A})}async get(e){return this.redisCache.get(this.getIdApi(e),u).then(({data:s})=>(this.logger.logDebug("getTerminal",JSON.stringify(s)),s)).catch(s=>(this.logger.logError("Error getTerminal",JSON.stringify(s)),null))}async delete(e){return this.redisCache.delete(this.getIdApi(e),u)}}const{TIMEOUT_SESSION_MINUTES:R}=process.env,{PREFIX_LOGIN:r}=process.env,O=process.env.REDIS_GET_USER_DATA_SESSION??"",U=`${r}:${O}`;`${process.env.APP_LOGS_NAME}${process.env.REDIS_GET_USER_APPS_PERMISSIONS}`;class M{constructor(e){n(this,"redisCache",new S.RedisCache);n(this,"userId","");n(this,"accountId","");this.userId=e}async updateSessionTimeout(e,s,a){if(!e)return;const t=new Date,c=R*6e4,o=new Date(t.getTime()+c);this.redisCache.simpleHSet(s,a,o.toISOString())}async getBasicSession(){const e="expires",s=await this.redisCache.simpleGet(`${r}:session:user:${this.userId}`)??"",a=await this.redisCache.simpleHGet(s,"sessionToken"),h=await this.redisCache.simpleHGet(`${r}:user:${this.userId}`,"email")??"",t=await this.redisCache.simpleGet(`${r}:account:user:${this.userId}`)??"",c=await this.redisCache.simpleHGet(t,"providerAccountId")??"",o=await this.redisCache.simpleHGet(s,e);if(this.updateSessionTimeout(o,s,e),this.accountId=c,a&&h&&t&&c){const d=await this.redisCache.simpleHGet(`${r}:user:${this.userId}`,"name"),I=await this.redisCache.simpleHGet(`${r}:user:${this.userId}`,"email")??"",p=await this.redisCache.simpleHGet(`${r}:user:${this.userId}`,"image"),m=await this.redisCache.simpleHGet(`${t}`,"cveUsuario"),l=await this.redisCache.simpleHGet(`${t}`,"appGroups"),E=await this.redisCache.simpleHGet(`${t}`,"rol"),g=l?JSON.parse(l):[];return{user:{name:d,email:I,image:p,cveUsuario:m,rol:E,appGroups:g}}}return{user:{name:null,email:null,image:null},expires:null}}async getUserAndShoppingStore(){var a;const e=await this.getBasicSession();if(e.user.image===null)return e;const s=await this.redisCache.get(U,this.accountId);return s.data.data?{user:{...e.user,...(a=s==null?void 0:s.data)==null?void 0:a.data}}:{user:{name:null,email:null,image:null},expires:null}}}exports.SessionCache=M;exports.Terminal=w;
1
+ "use strict";var T=Object.defineProperty;var C=(i,e,s)=>e in i?T(i,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):i[e]=s;var n=(i,e,s)=>C(i,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S=require("./redis-cache-BstIlgPR.cjs"),_=require("./logger-BMbeDoGU.cjs");require("./lodash-DNCgFYS7.cjs");require("node-jose");require("crypto");const G=require("./v5-BTqP79vV.cjs"),A=process.env.TIMEOUT_SESSION_MINUTES,N=process.env.PREFIX_TERMINAL||"PF:TERMINAL:",$="619abad7-0dea-46c5-aa49-fc1ec872a684",u="TERMINAL";class w{constructor(){n(this,"logger",new _.Logger);n(this,"redisCache",new S.RedisCache)}getIdApi(e){const s=G.v5(e,$);return`${N}${s}`}async set(e,s){return this.redisCache.set({prefix:this.getIdApi(e),idData:u,body:s,expire:A})}async get(e){return this.redisCache.get(this.getIdApi(e),u).then(({data:s})=>(this.logger.logDebug("getTerminal",JSON.stringify(s)),s)).catch(s=>(this.logger.logError("Error getTerminal",JSON.stringify(s)),null))}async delete(e){return this.redisCache.delete(this.getIdApi(e),u)}}const{TIMEOUT_SESSION_MINUTES:R}=process.env,{PREFIX_LOGIN:r}=process.env,O=process.env.REDIS_GET_USER_DATA_SESSION??"",U=`${r}:${O}`;`${process.env.APP_LOGS_NAME}${process.env.REDIS_GET_USER_APPS_PERMISSIONS}`;class M{constructor(e){n(this,"redisCache",new S.RedisCache);n(this,"userId","");n(this,"accountId","");this.userId=e}async updateSessionTimeout(e,s,a){if(!e)return;const t=new Date,c=R*6e4,o=new Date(t.getTime()+c);this.redisCache.simpleHSet(s,a,o.toISOString())}async getBasicSession(){const e="expires",s=await this.redisCache.simpleGet(`${r}:session:user:${this.userId}`)??"",a=await this.redisCache.simpleHGet(s,"sessionToken"),h=await this.redisCache.simpleHGet(`${r}:user:${this.userId}`,"email")??"",t=await this.redisCache.simpleGet(`${r}:account:user:${this.userId}`)??"",c=await this.redisCache.simpleHGet(t,"providerAccountId")??"",o=await this.redisCache.simpleHGet(s,e);if(this.updateSessionTimeout(o,s,e),this.accountId=c,a&&h&&t&&c){const d=await this.redisCache.simpleHGet(`${r}:user:${this.userId}`,"name"),I=await this.redisCache.simpleHGet(`${r}:user:${this.userId}`,"email")??"",p=await this.redisCache.simpleHGet(`${r}:user:${this.userId}`,"image"),m=await this.redisCache.simpleHGet(`${t}`,"cveUsuario"),l=await this.redisCache.simpleHGet(`${t}`,"appGroups"),E=await this.redisCache.simpleHGet(`${t}`,"rol"),g=l?JSON.parse(l):[];return{user:{name:d,email:I,image:p,cveUsuario:m,rol:E,appGroups:g}}}return{user:{name:null,email:null,image:null},expires:null}}async getUserAndShoppingStore(){var a;const e=await this.getBasicSession();if(e.user.image===null)return e;const s=await this.redisCache.get(U,this.accountId);return s.data.data?{user:{...e.user,...(a=s==null?void 0:s.data)==null?void 0:a.data}}:{user:{name:null,email:null,image:null},expires:null}}}exports.SessionCache=M;exports.Terminal=w;
@@ -1,7 +1,7 @@
1
1
  var T = Object.defineProperty;
2
2
  var _ = (t, e, s) => e in t ? T(t, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : t[e] = s;
3
3
  var n = (t, e, s) => _(t, typeof e != "symbol" ? e + "" : e, s);
4
- import { R as S } from "./redis-cache-B_SyXbUI.js";
4
+ import { R as S } from "./redis-cache-HiNx0Kbv.js";
5
5
  import { L as C } from "./logger-DtlFWyFO.js";
6
6
  import "./lodash-QjAkD17S.js";
7
7
  import "node-jose";
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./redis-cache-D9CzfYgO.cjs");exports.RedisCache=e.RedisCache;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./redis-cache-BstIlgPR.cjs");exports.RedisCache=e.RedisCache;
@@ -1,4 +1,4 @@
1
- import { R as o } from "./redis-cache-B_SyXbUI.js";
1
+ import { R as o } from "./redis-cache-HiNx0Kbv.js";
2
2
  export {
3
3
  o as RedisCache
4
4
  };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./client-BVAQF7Tb.cjs");exports.HttpBackend=t.HttpBackend;exports.HttpClient=t.HttpClient;exports.HttpHeaders=t.HttpHeaders;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./client-AVep4jK5.cjs");exports.HttpBackend=t.HttpBackend;exports.HttpClient=t.HttpClient;exports.HttpHeaders=t.HttpHeaders;
@@ -1,4 +1,4 @@
1
- import { a as e, b as H, H as p } from "./client-DKI6Ntcl.js";
1
+ import { a as e, b as H, H as p } from "./client-DuXI9Ldu.js";
2
2
  export {
3
3
  e as HttpBackend,
4
4
  H as HttpClient,
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var S=(n,t,e)=>t in n?p(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var o=(n,t,e)=>S(n,typeof t!="symbol"?t+"":t,e);const u=require("./ioredis-instance-PenLE7vi.cjs"),d=require("./encrypter-CgZLhLnj.cjs");var h=(n=>(n.NOT_REFRESH="NOT_REFRESH",n.REFRESH="REFRESH",n))(h||{});const E=process.env.TIMEOUT_SESSION_MINUTES;class R{constructor(){o(this,"encrypter",new d.Encrypter);o(this,"initClient",u.ioredisInstance)}getRootNode(t){return this.initClient.get(t)}async getEntryPoint(t){try{return await this.getRootNode(t)}catch{throw new Error("Not found entry point")}}setEntryPoint(t,e,i){const s=typeof e=="string"?e:JSON.stringify(e);this.initClient.set(t,s,"EX",60*i)}async get(t,e){const i=`${t}:${this.encrypter.generateSHA(e)}`,s=await this.getEntryPoint(i),c=await this.encrypter.isEncrypted(s)?await this.encrypter.decrypt(s??""):JSON.parse(s),r=Number(c==null?void 0:c.expires_in);return r&&this.ttl(i,r*60),{sha:i,data:c}}async delete(t,e){const i=`${t}:${this.encrypter.generateSHA(e)}`;this.initClient.del(i)}async set({prefix:t,idData:e,body:i,expire:s,encrypted:l=!1,refresh:c=h.REFRESH}){const r=`${t}:${this.encrypter.generateSHA(e)}`,y={expires_in:c===h.REFRESH?s:0,...i};if(l){const a=await this.encrypter.encrypt(y);return this.setEntryPoint(r,a,s),r}return this.setEntryPoint(r,y,s),r}async statusHost(){return new Promise((t,e)=>{this.initClient.on("error",i=>{this.killRedis(),e(i)}),this.initClient.on("connect",()=>{t("success")})})}killRedis(){this.initClient.disconnect()}deleteKey(t){this.initClient.del(t)}ttl(t,e){this.initClient.expire(t,e)}simpleGet(t){return this.ttl(t,E*60),this.initClient.get(t)}simpleHGet(t,e){return this.ttl(t,E*60),this.initClient.hget(t,e)}simpleHSet(t,e,i){return this.initClient.hset(t,e,i)}simpleHGetAll(t){return this.initClient.hgetall(t)}}exports.RedisCache=R;
1
+ "use strict";var a=Object.defineProperty;var u=(n,t,e)=>t in n?a(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var o=(n,t,e)=>u(n,typeof t!="symbol"?t+"":t,e);const S=require("./ioredis-instance-PenLE7vi.cjs"),d=require("./encrypter-CgZLhLnj.cjs");var l=(n=>(n.NOT_REFRESH="NOT_REFRESH",n.REFRESH="REFRESH",n))(l||{});const h=process.env.TIMEOUT_SESSION_MINUTES;class R{constructor(){o(this,"encrypter",new d.Encrypter);o(this,"initClient",S.ioredisInstance)}getRootNode(t){return this.initClient.get(t)}async getEntryPoint(t){try{return await this.getRootNode(t)}catch{throw new Error("Not found entry point")}}setEntryPoint(t,e,i){const s=typeof e=="string"?e:JSON.stringify(e);this.initClient.set(t,s,"EX",60*i)}async get(t,e){const i=`${t}:${this.encrypter.generateSHA(e)}`,s=await this.getEntryPoint(i),c=await this.encrypter.isEncrypted(s)?await this.encrypter.decrypt(s??""):JSON.parse(s),r=Number(c==null?void 0:c.expires_in);return r&&this.ttl(i,r*60),{sha:i,data:c}}async delete(t,e){const i=`${t}:${this.encrypter.generateSHA(e)}`;this.initClient.del(i)}async set({prefix:t,idData:e,body:i,expire:s,encrypted:y=!1,refresh:c=l.REFRESH}){const r=`${t}:${this.encrypter.generateSHA(e)}`,E={expires_in:c===l.REFRESH?s:0,...i};if(y){const p=await this.encrypter.encrypt(E);return this.setEntryPoint(r,p,s),r}return this.setEntryPoint(r,E,s),r}async statusHost(){return new Promise((t,e)=>{this.initClient.on("error",i=>{this.killRedis(),e(i)}),this.initClient.on("connect",()=>{t("success")})})}killRedis(){this.initClient.disconnect()}deleteKey(t){this.initClient.del(t)}ttl(t,e){this.initClient.expire(t,e)}simpleGet(t){return this.ttl(t,h*60),this.initClient.get(t)}simpleHGet(t,e){return this.ttl(t,h*60),this.initClient.hget(t,e)}simpleHGetBuffer(t,e){return this.ttl(t,h*60),this.initClient.hgetBuffer(t,e)}simpleHSet(t,e,i){return this.initClient.hset(t,e,i)}simpleHGetAll(t){return this.initClient.hgetall(t)}}exports.RedisCache=R;
@@ -1,14 +1,14 @@
1
1
  var a = Object.defineProperty;
2
2
  var S = (n, t, e) => t in n ? a(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
3
  var c = (n, t, e) => S(n, typeof t != "symbol" ? t + "" : t, e);
4
- import { i as R } from "./ioredis-instance-BaXfqmqC.js";
5
- import { E as u } from "./encrypter-ZTjrp3uD.js";
6
- var l = /* @__PURE__ */ ((n) => (n.NOT_REFRESH = "NOT_REFRESH", n.REFRESH = "REFRESH", n))(l || {});
7
- const E = process.env.TIMEOUT_SESSION_MINUTES;
4
+ import { i as u } from "./ioredis-instance-BaXfqmqC.js";
5
+ import { E as R } from "./encrypter-ZTjrp3uD.js";
6
+ var h = /* @__PURE__ */ ((n) => (n.NOT_REFRESH = "NOT_REFRESH", n.REFRESH = "REFRESH", n))(h || {});
7
+ const l = process.env.TIMEOUT_SESSION_MINUTES;
8
8
  class m {
9
9
  constructor() {
10
- c(this, "encrypter", new u());
11
- c(this, "initClient", R);
10
+ c(this, "encrypter", new R());
11
+ c(this, "initClient", u);
12
12
  }
13
13
  getRootNode(t) {
14
14
  return this.initClient.get(t);
@@ -37,15 +37,15 @@ class m {
37
37
  idData: e,
38
38
  body: i,
39
39
  expire: s,
40
- encrypted: h = !1,
41
- refresh: o = l.REFRESH
40
+ encrypted: y = !1,
41
+ refresh: o = h.REFRESH
42
42
  }) {
43
- const r = `${t}:${this.encrypter.generateSHA(e)}`, y = { expires_in: o === l.REFRESH ? s : 0, ...i };
44
- if (h) {
45
- const p = await this.encrypter.encrypt(y);
43
+ const r = `${t}:${this.encrypter.generateSHA(e)}`, E = { expires_in: o === h.REFRESH ? s : 0, ...i };
44
+ if (y) {
45
+ const p = await this.encrypter.encrypt(E);
46
46
  return this.setEntryPoint(r, p, s), r;
47
47
  }
48
- return this.setEntryPoint(r, y, s), r;
48
+ return this.setEntryPoint(r, E, s), r;
49
49
  }
50
50
  async statusHost() {
51
51
  return new Promise((t, e) => {
@@ -66,10 +66,13 @@ class m {
66
66
  this.initClient.expire(t, e);
67
67
  }
68
68
  simpleGet(t) {
69
- return this.ttl(t, E * 60), this.initClient.get(t);
69
+ return this.ttl(t, l * 60), this.initClient.get(t);
70
70
  }
71
71
  simpleHGet(t, e) {
72
- return this.ttl(t, E * 60), this.initClient.hget(t, e);
72
+ return this.ttl(t, l * 60), this.initClient.hget(t, e);
73
+ }
74
+ simpleHGetBuffer(t, e) {
75
+ return this.ttl(t, l * 60), this.initClient.hgetBuffer(t, e);
73
76
  }
74
77
  simpleHSet(t, e, i) {
75
78
  return this.initClient.hset(t, e, i);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mp-front/common",
3
- "version": "0.0.2-next.0",
3
+ "version": "0.0.2-next.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/mp-front-common-all.cjs",
@@ -1 +0,0 @@
1
- "use strict";var w=Object.defineProperty;var N=(c,e,t)=>e in c?w(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var o=(c,e,t)=>N(c,typeof e!="symbol"?e+"":e,t);const i=require("rxjs"),S=require("./logger-BMbeDoGU.cjs");require("./lodash-DNCgFYS7.cjs");require("node-jose");require("crypto");const l=require("./default-errors-DiEIEEE2.cjs"),y=require("./fetch-BZP9DZLg.cjs"),x=require("./authorization-service-DkLS18Us.cjs"),D=require("./encoder-BEp9qfLf.cjs"),p=require("./loading-handler-BrN0O37N.cjs"),b=require("./v5-BTqP79vV.cjs");class O{constructor(e={}){o(this,"logger",new S.Logger);o(this,"headers");this.headers={Accept:"application/json","Content-Type":"application/vnd.api+json",...e}}addTokenBackend(e){return this.logger.logDebug("addTokenBackend HttpHeaders",JSON.stringify(e)),new x.AuthorizationService().get().pipe(i.switchMap(t=>i.of({...e,Authorization:`Bearer ${t}`})))}get(e){this.logger.logDebug("get HttpHeaders");const t=i.of({...this.headers});return e?t.pipe(i.switchMap(s=>this.addTokenBackend(s))):t}}const L=process.env.ID_FRONT??"NOT_AVAILABLE";class ${constructor(){o(this,"httpHeaders",new O);o(this,"logger",new S.Logger)}errorCatcher(e,t){var s,r,n;if(e!=null&&e.errors)throw new l.RuntimeError(((n=(r=(s=e.errors).at)==null?void 0:r.call(s,0))==null?void 0:n.code)??l.RuntimeErrorCode.DEFAULT,t??"");return!(e!=null&&e.errors)}get(e,t={}){const s=this.buildRequest("GET",e,null,t);return this.request(s)}post(e,t,s={}){const r=this.buildRequest("POST",e,t,s);return this.request(r)}put(e,t,s={}){const r=this.buildRequest("PUT",e,t,s);return this.request(r)}delete(e,t={}){const s=this.buildRequest("DELETE",e,null,t);return this.request(s)}formatParams(e,t){return JSON.stringify(t==="JSON:API"?{data:{type:L,attributes:e}}:e)}buildRequest(e,t,s,r){const n=r.format??"JSON:API",a={requestID:r==null?void 0:r.requestID,withCredentials:(r==null?void 0:r.withCredentials)??!0,url:t,headers:r.headers,method:e,selector:u=>u.json()};if(e==="GET"){const u=new URL(t);if(r.params)for(const m of Object.keys(r.params))u.searchParams.append(m,`${r.params[m]}`);return{...a,url:u.toString()}}return{...a,body:this.formatParams(s,n)}}request({url:e,requestID:t,withCredentials:s=!1,...r}){return this.httpHeaders.get(s).pipe(i.switchMap(n=>y.fromFetch(e,{...r,headers:{...r.headers,...n}}).pipe(i.catchError(a=>{throw this.logger.logError(JSON.stringify(a)),this.logger.logError(`HttpBackend \x1B[37m <URL>: \x1B[33m ${e} \x1B[37m <RequestID>: \x1B[33m ${t} \x1B[37m <HEADERS>: \x1B[33m ${JSON.stringify(n)} \x1B[37m <BODY>: \x1B[33m ${JSON.stringify(this.formatParams(r.body,r.format))} \x1B[37m <RESPONSE>: \x1B[33m ${JSON.stringify(a)} \x1B[33m`),new l.RuntimeError(l.RuntimeErrorCode.DEFAULT,t)}),i.switchMap(a=>(this.logger.logDebug(`HttpBackend \x1B[37m <URL>: \x1B[33m ${e} \x1B[37m <RequestID>: \x1B[33m ${t} \x1B[37m <HEADERS>: \x1B[33m ${JSON.stringify(n)} \x1B[37m <BODY>: \x1B[33m ${JSON.stringify(this.formatParams(r.body,r.format))} \x1B[37m <RESPONSE>: \x1B[33m ${JSON.stringify(a)} \x1B[33m`),i.of(a))))),i.filter(n=>this.errorCatcher(n,t)))}}class J{constructor(){o(this,"httpHeaders",new O);o(this,"logger",new S.Logger);o(this,"encoder",new D.Encoder);o(this,"isLoadingEnabled",!0)}setIsLoadingEnabled(e){this.isLoadingEnabled=e}get(e,t={}){const s=this.buildRequest("GET",e,null,t);return this.request(s)}post(e,t,s={}){const r=this.buildRequest("POST",e,t,s);return this.request(r)}put(e,t,s={}){const r=this.buildRequest("PUT",e,t,s);return this.request(r)}patch(e,t,s={}){const r=this.buildRequest("PATCH",e,t,s);return this.request(r)}delete(e,t={}){const s=this.buildRequest("DELETE",e,null,t);return this.request(s)}buildRequest(e,t,s,r){const n={url:t,headers:r.headers,method:e,selector:d=>d.json()},a=new Date().toISOString(),u=b.v5(a,b.v5.URL);if(e==="GET"){const d=new URL(t,location.origin),f=r.params??{},B=Object.entries(f).reduce((h,H)=>{const[g,T]=H;if(h[g]=`${T}`,Object.hasOwn(f,g)){const E=f[g];E!=null&&(h[g]=E)}return h},{}),R=this.encoder.encode(B,u),q=JSON.parse(R);for(const h of Object.keys(q))d.searchParams.append(h,`${q[h]}`);return{...n,url:d.toString()}}if(new Headers(r.headers).get("Content-Type")==="multipart/form-data"){const d=s;return d.append("requestID",u),{...n,body:d}}return{...n,body:this.encoder.encode(s??{},u)}}request({url:e,...t}){return p.LoadingHandler.getInstance().setSubject(this.isLoadingEnabled),this.httpHeaders.get(!1).pipe(i.switchMap(s=>{const r={...s,...t.headers};return"Content-Type"in r&&r["Content-Type"]==="multipart/form-data"&&delete r["Content-Type"],y.fromFetch(e,{...t,headers:r}).pipe(i.switchMap(n=>i.of(this.encoder.decode(n))),i.switchMap(n=>{if("code"in n)throw n;return p.LoadingHandler.getInstance().setSubject(!1),this.logger.logDebug(`HttpClient <URL>: ${e} <HEADERS>: ${JSON.stringify(t.headers)} <BODY> ${JSON.stringify(t.body)} <RESPONSE>: ${JSON.stringify(n)}`),i.of(n)}),i.catchError(n=>(this.logger.logError(`HttpClient <URL>: ${e} <HEADERS>: ${JSON.stringify(t.headers)} <BODY> ${JSON.stringify(t.body)} <ERROR>: ${JSON.stringify(n)}`),p.LoadingHandler.getInstance().setSubject(!1),l.ErrorHandler.getInstance().setSubject(n),i.EMPTY)))}))}}exports.HttpBackend=$;exports.HttpClient=J;exports.HttpHeaders=O;
@@ -1,234 +0,0 @@
1
- var $ = Object.defineProperty;
2
- var L = (o, e, t) => e in o ? $(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
- var i = (o, e, t) => L(o, typeof e != "symbol" ? e + "" : e, t);
4
- import { switchMap as d, of as m, catchError as R, filter as w, EMPTY as J } from "rxjs";
5
- import { L as S } from "./logger-DtlFWyFO.js";
6
- import "./lodash-QjAkD17S.js";
7
- import "node-jose";
8
- import "crypto";
9
- import { R as b, a as y, E as P } from "./default-errors-DsKmUZbG.js";
10
- import { f as T } from "./fetch-CUIb9XhZ.js";
11
- import { A } from "./authorization-service-DE-hoYji.js";
12
- import { E as I } from "./encoder-CXAlLf5T.js";
13
- import { L as E } from "./loading-handler-ivYFmS_V.js";
14
- import { v as B } from "./v5-Cu1sjPlx.js";
15
- class q {
16
- constructor(e = {}) {
17
- i(this, "logger", new S());
18
- i(this, "headers");
19
- this.headers = {
20
- Accept: "application/json",
21
- "Content-Type": "application/vnd.api+json",
22
- ...e
23
- };
24
- }
25
- addTokenBackend(e) {
26
- return this.logger.logDebug("addTokenBackend HttpHeaders", JSON.stringify(e)), new A().get().pipe(
27
- d((t) => m({ ...e, Authorization: `Bearer ${t}` }))
28
- );
29
- }
30
- get(e) {
31
- this.logger.logDebug("get HttpHeaders");
32
- const t = m({ ...this.headers });
33
- return e ? t.pipe(
34
- d((s) => this.addTokenBackend(s))
35
- ) : t;
36
- }
37
- }
38
- const k = process.env.ID_FRONT ?? "NOT_AVAILABLE";
39
- class Q {
40
- constructor() {
41
- i(this, "httpHeaders", new q());
42
- i(this, "logger", new S());
43
- }
44
- errorCatcher(e, t) {
45
- var s, r, n;
46
- if (e != null && e.errors)
47
- throw new b(
48
- ((n = (r = (s = e.errors).at) == null ? void 0 : r.call(s, 0)) == null ? void 0 : n.code) ?? y.DEFAULT,
49
- t ?? ""
50
- );
51
- return !(e != null && e.errors);
52
- }
53
- get(e, t = {}) {
54
- const s = this.buildRequest("GET", e, null, t);
55
- return this.request(s);
56
- }
57
- post(e, t, s = {}) {
58
- const r = this.buildRequest("POST", e, t, s);
59
- return this.request(r);
60
- }
61
- put(e, t, s = {}) {
62
- const r = this.buildRequest("PUT", e, t, s);
63
- return this.request(r);
64
- }
65
- delete(e, t = {}) {
66
- const s = this.buildRequest("DELETE", e, null, t);
67
- return this.request(s);
68
- }
69
- formatParams(e, t) {
70
- return JSON.stringify(t === "JSON:API" ? {
71
- data: {
72
- type: k,
73
- attributes: e
74
- }
75
- } : e);
76
- }
77
- /**
78
- * Building configuration object request
79
- */
80
- buildRequest(e, t, s, r) {
81
- const n = r.format ?? "JSON:API", a = {
82
- requestID: r == null ? void 0 : r.requestID,
83
- withCredentials: (r == null ? void 0 : r.withCredentials) ?? !0,
84
- url: t,
85
- headers: r.headers,
86
- method: e,
87
- selector: (u) => u.json()
88
- };
89
- if (e === "GET") {
90
- const u = new URL(t);
91
- if (r.params)
92
- for (const g of Object.keys(r.params))
93
- u.searchParams.append(g, `${r.params[g]}`);
94
- return { ...a, url: u.toString() };
95
- }
96
- return { ...a, body: this.formatParams(s, n) };
97
- }
98
- request({
99
- url: e,
100
- requestID: t,
101
- withCredentials: s = !1,
102
- ...r
103
- }) {
104
- return this.httpHeaders.get(s).pipe(
105
- d(
106
- (n) => T(e, {
107
- ...r,
108
- headers: {
109
- ...r.headers,
110
- ...n
111
- }
112
- }).pipe(
113
- R((a) => {
114
- throw this.logger.logError(JSON.stringify(a)), this.logger.logError(
115
- `HttpBackend \x1B[37m <URL>: \x1B[33m ${e} \x1B[37m <RequestID>: \x1B[33m ${t} \x1B[37m <HEADERS>: \x1B[33m ${JSON.stringify(
116
- n
117
- )} \x1B[37m <BODY>: \x1B[33m ${JSON.stringify(
118
- this.formatParams(r.body, r.format)
119
- )} \x1B[37m <RESPONSE>: \x1B[33m ${JSON.stringify(a)} \x1B[33m`
120
- ), new b(y.DEFAULT, t);
121
- }),
122
- d((a) => (this.logger.logDebug(
123
- `HttpBackend \x1B[37m <URL>: \x1B[33m ${e} \x1B[37m <RequestID>: \x1B[33m ${t} \x1B[37m <HEADERS>: \x1B[33m ${JSON.stringify(
124
- n
125
- )} \x1B[37m <BODY>: \x1B[33m ${JSON.stringify(
126
- this.formatParams(r.body, r.format)
127
- )} \x1B[37m <RESPONSE>: \x1B[33m ${JSON.stringify(a)} \x1B[33m`
128
- ), m(a)))
129
- )
130
- ),
131
- w((n) => this.errorCatcher(n, t))
132
- );
133
- }
134
- }
135
- class X {
136
- constructor() {
137
- i(this, "httpHeaders", new q());
138
- i(this, "logger", new S());
139
- i(this, "encoder", new I());
140
- i(this, "isLoadingEnabled", !0);
141
- }
142
- setIsLoadingEnabled(e) {
143
- this.isLoadingEnabled = e;
144
- }
145
- get(e, t = {}) {
146
- const s = this.buildRequest("GET", e, null, t);
147
- return this.request(s);
148
- }
149
- post(e, t, s = {}) {
150
- const r = this.buildRequest("POST", e, t, s);
151
- return this.request(r);
152
- }
153
- put(e, t, s = {}) {
154
- const r = this.buildRequest("PUT", e, t, s);
155
- return this.request(r);
156
- }
157
- patch(e, t, s = {}) {
158
- const r = this.buildRequest("PATCH", e, t, s);
159
- return this.request(r);
160
- }
161
- delete(e, t = {}) {
162
- const s = this.buildRequest("DELETE", e, null, t);
163
- return this.request(s);
164
- }
165
- /**
166
- * Building configuration object request
167
- */
168
- buildRequest(e, t, s, r) {
169
- const n = {
170
- url: t,
171
- headers: r.headers,
172
- method: e,
173
- selector: (c) => c.json()
174
- }, a = (/* @__PURE__ */ new Date()).toISOString(), u = B(a, B.URL);
175
- if (e === "GET") {
176
- const c = new URL(t, location.origin), f = r.params ?? {}, H = Object.entries(f).reduce((h, x) => {
177
- const [l, D] = x;
178
- if (h[l] = `${D}`, Object.hasOwn(f, l)) {
179
- const p = f[l];
180
- p != null && (h[l] = p);
181
- }
182
- return h;
183
- }, {}), N = this.encoder.encode(H, u), O = JSON.parse(N);
184
- for (const h of Object.keys(O))
185
- c.searchParams.append(h, `${O[h]}`);
186
- return { ...n, url: c.toString() };
187
- }
188
- if (new Headers(r.headers).get("Content-Type") === "multipart/form-data") {
189
- const c = s;
190
- return c.append("requestID", u), {
191
- ...n,
192
- body: c
193
- };
194
- }
195
- return {
196
- ...n,
197
- body: this.encoder.encode(s ?? {}, u)
198
- };
199
- }
200
- request({
201
- url: e,
202
- ...t
203
- }) {
204
- return E.getInstance().setSubject(this.isLoadingEnabled), this.httpHeaders.get(!1).pipe(
205
- d((s) => {
206
- const r = {
207
- ...s,
208
- ...t.headers
209
- };
210
- return "Content-Type" in r && r["Content-Type"] === "multipart/form-data" && delete r["Content-Type"], T(e, {
211
- ...t,
212
- headers: r
213
- }).pipe(
214
- d((n) => m(this.encoder.decode(n))),
215
- d((n) => {
216
- if ("code" in n)
217
- throw n;
218
- return E.getInstance().setSubject(!1), this.logger.logDebug(
219
- `HttpClient <URL>: ${e} <HEADERS>: ${JSON.stringify(t.headers)} <BODY> ${JSON.stringify(t.body)} <RESPONSE>: ${JSON.stringify(n)}`
220
- ), m(n);
221
- }),
222
- R((n) => (this.logger.logError(
223
- `HttpClient <URL>: ${e} <HEADERS>: ${JSON.stringify(t.headers)} <BODY> ${JSON.stringify(t.body)} <ERROR>: ${JSON.stringify(n)}`
224
- ), E.getInstance().setSubject(!1), P.getInstance().setSubject(n), J))
225
- );
226
- })
227
- );
228
- }
229
- }
230
- export {
231
- q as H,
232
- Q as a,
233
- X as b
234
- };