@c-rex/core 0.0.8 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -9,22 +9,19 @@ interface CallParams {
9
9
  params?: any;
10
10
  }
11
11
  declare class CrexApi {
12
- private config;
12
+ private customerConfig;
13
13
  private apiClient;
14
- private logger;
15
- constructor(config: ConfigInterface, logger: any);
16
14
  private manageToken;
17
15
  private getToken;
16
+ private initAPI;
18
17
  execute<T>({ url, method, params, body, headers, }: CallParams): Promise<T>;
19
18
  }
20
19
 
21
20
  declare class CrexSDK {
22
- api: CrexApi;
23
- logger: any;
24
21
  userAuthConfig: any;
25
22
  customerConfig: ConfigInterface;
26
- constructor();
27
- static setConfig(config: ConfigInterface): void;
23
+ private getConfig;
24
+ getUserAuthConfig(): Promise<any>;
28
25
  }
29
26
 
30
27
  export { CrexApi, CrexSDK };
package/dist/index.d.ts CHANGED
@@ -9,22 +9,19 @@ interface CallParams {
9
9
  params?: any;
10
10
  }
11
11
  declare class CrexApi {
12
- private config;
12
+ private customerConfig;
13
13
  private apiClient;
14
- private logger;
15
- constructor(config: ConfigInterface, logger: any);
16
14
  private manageToken;
17
15
  private getToken;
16
+ private initAPI;
18
17
  execute<T>({ url, method, params, body, headers, }: CallParams): Promise<T>;
19
18
  }
20
19
 
21
20
  declare class CrexSDK {
22
- api: CrexApi;
23
- logger: any;
24
21
  userAuthConfig: any;
25
22
  customerConfig: ConfigInterface;
26
- constructor();
27
- static setConfig(config: ConfigInterface): void;
23
+ private getConfig;
24
+ getUserAuthConfig(): Promise<any>;
28
25
  }
29
26
 
30
27
  export { CrexApi, CrexSDK };
package/dist/index.js CHANGED
@@ -1,35 +1,117 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _class;// src/requests.ts
2
- var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);
3
- var _constants = require('@c-rex/constants');
4
- var _openidclient = require('openid-client');
5
- var _utils = require('@c-rex/utils');
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ CrexApi: () => CrexApi,
34
+ CrexSDK: () => CrexSDK
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/requests.ts
39
+ var import_axios = __toESM(require("axios"));
40
+
41
+ // ../constants/src/index.ts
42
+ var API = {
43
+ MAX_RETRY: 3,
44
+ API_TIMEOUT: 1e4,
45
+ API_HEADERS: {
46
+ "content-Type": "application/json"
47
+ }
48
+ };
49
+ var SDK_CONFIG_KEY = "crex-sdk-config";
50
+
51
+ // src/requests.ts
52
+ var import_openid_client = require("openid-client");
53
+
54
+ // ../utils/src/utils.ts
55
+ var call = async (method, params) => {
56
+ try {
57
+ const res = await fetch(`/api/rpc`, {
58
+ method: "POST",
59
+ headers: { "Content-Type": "application/json" },
60
+ body: JSON.stringify({ method, params })
61
+ });
62
+ const json = await res.json();
63
+ if (!res.ok) throw new Error(json.error || "Unknown error");
64
+ return json.data;
65
+ } catch (error) {
66
+ console.error(error);
67
+ return null;
68
+ }
69
+ };
70
+
71
+ // ../utils/src/memory.ts
72
+ function isBrowser() {
73
+ return typeof window !== "undefined" && typeof document !== "undefined";
74
+ }
75
+ function saveInMemory(value, key) {
76
+ if (isBrowser()) throw new Error("saveInMemory is not supported in browser");
77
+ if (typeof global !== "undefined" && !(key in global)) {
78
+ global[key] = null;
79
+ }
80
+ const globalConfig = global[key];
81
+ if (globalConfig === null) {
82
+ global[key] = value;
83
+ }
84
+ }
85
+ function getFromMemory(key) {
86
+ if (isBrowser()) throw new Error("getFromMemory is not supported in browser");
87
+ return global[key];
88
+ }
89
+
90
+ // ../utils/src/classMerge.ts
91
+ var import_clsx = require("clsx");
92
+ var import_tailwind_merge = require("tailwind-merge");
93
+
94
+ // ../utils/src/treeOfContent.ts
95
+ var import_services = require("@c-rex/services");
96
+
97
+ // src/requests.ts
98
+ var import_next_cookies = require("@c-rex/utils/next-cookies");
6
99
  var CREX_TOKEN_HEADER_KEY = "crex-token";
7
100
  var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
8
101
  var CrexApi = class {
9
-
10
-
11
-
12
- constructor(config, logger) {
13
- this.apiClient = _axios2.default.create({
14
- baseURL: config.baseUrl,
15
- headers: {
16
- "content-Type": "application/json"
17
- }
18
- });
19
- this.config = config;
20
- this.logger = logger;
21
- }
102
+ customerConfig;
103
+ apiClient;
22
104
  async manageToken() {
23
105
  const headersAux = {};
24
- if (this.config.OIDC.client.enabled) {
25
- let token = _utils.getFromMemory.call(void 0, CREX_TOKEN_HEADER_KEY);
26
- let tokenExpiry = _utils.getFromMemory.call(void 0, CREX_TOKEN_EXPIRY_HEADER_KEY);
106
+ if (this.customerConfig.OIDC.client.enabled) {
107
+ let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
108
+ let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);
27
109
  const now = Math.floor(Date.now() / 1e3);
28
110
  if (!(token && tokenExpiry > now + 60)) {
29
111
  const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
30
112
  token = tokenAux;
31
- _utils.saveInMemory.call(void 0, token, CREX_TOKEN_HEADER_KEY);
32
- _utils.saveInMemory.call(void 0, tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
113
+ saveInMemory(token, CREX_TOKEN_HEADER_KEY);
114
+ saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);
33
115
  }
34
116
  headersAux["Authorization"] = `Bearer ${token}`;
35
117
  }
@@ -40,21 +122,39 @@ var CrexApi = class {
40
122
  let tokenExpiry = 0;
41
123
  try {
42
124
  const now = Math.floor(Date.now() / 1e3);
43
- const issuer = await _openidclient.Issuer.discover(this.config.OIDC.client.issuer);
125
+ const issuer = await import_openid_client.Issuer.discover(this.customerConfig.OIDC.client.issuer);
44
126
  const client = new issuer.Client({
45
- client_id: this.config.OIDC.client.id,
46
- client_secret: this.config.OIDC.client.secret
127
+ client_id: this.customerConfig.OIDC.client.id,
128
+ client_secret: this.customerConfig.OIDC.client.secret
47
129
  });
48
130
  const tokenSet = await client.grant({ grant_type: "client_credentials" });
49
- token = tokenSet.access_token, tokenExpiry = now + tokenSet.expires_at;
131
+ token = tokenSet.access_token;
132
+ tokenExpiry = now + tokenSet.expires_at;
50
133
  } catch (error) {
51
- console.log("error", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);
134
+ call("CrexLogger.log", {
135
+ level: "error",
136
+ message: `API.getToken error when request ${this.customerConfig.OIDC.client.issuer}. Error: ${error}`
137
+ });
52
138
  }
53
139
  return {
54
140
  token,
55
141
  tokenExpiry
56
142
  };
57
143
  }
144
+ async initAPI() {
145
+ if (!this.customerConfig) {
146
+ const jsonConfigs = await (0, import_next_cookies.getCookie)(SDK_CONFIG_KEY);
147
+ if (!jsonConfigs) {
148
+ throw new Error("SDK not initialized");
149
+ }
150
+ this.customerConfig = JSON.parse(jsonConfigs);
151
+ }
152
+ if (!this.apiClient) {
153
+ this.apiClient = import_axios.default.create({
154
+ baseURL: this.customerConfig.baseUrl
155
+ });
156
+ }
157
+ }
58
158
  async execute({
59
159
  url,
60
160
  method,
@@ -62,12 +162,13 @@ var CrexApi = class {
62
162
  body,
63
163
  headers = {}
64
164
  }) {
165
+ await this.initAPI();
65
166
  let response = void 0;
66
167
  headers = {
67
168
  ...headers,
68
169
  ...await this.manageToken()
69
170
  };
70
- for (let retry = 0; retry < _constants.API.MAX_RETRY; retry++) {
171
+ for (let retry = 0; retry < API.MAX_RETRY; retry++) {
71
172
  try {
72
173
  response = await this.apiClient.request({
73
174
  url,
@@ -82,7 +183,7 @@ var CrexApi = class {
82
183
  "error",
83
184
  `API.execute ${retry + 1}\xBA error when request ${url}. Error: ${error}`
84
185
  );
85
- if (retry === _constants.API.MAX_RETRY - 1) {
186
+ if (retry === API.MAX_RETRY - 1) {
86
187
  throw error;
87
188
  }
88
189
  }
@@ -95,17 +196,24 @@ var CrexApi = class {
95
196
  };
96
197
 
97
198
  // src/sdk.ts
98
-
99
- var SDK_CONFIG_KEY = "crex-sdk-config";
100
- var CrexSDK = (_class = class {
101
-
102
-
103
- __init() {this.userAuthConfig = {}}
104
-
105
- constructor() {;_class.prototype.__init.call(this);
106
- const config = _utils.getFromMemory.call(void 0, SDK_CONFIG_KEY);
107
- this.customerConfig = config;
108
- this.api = new CrexApi(this.customerConfig, null);
199
+ var import_next_cookies2 = require("@c-rex/utils/next-cookies");
200
+ var CrexSDK = class {
201
+ userAuthConfig;
202
+ customerConfig;
203
+ async getConfig() {
204
+ if (!this.customerConfig) {
205
+ const jsonConfigs = await (0, import_next_cookies2.getCookie)(SDK_CONFIG_KEY);
206
+ if (!jsonConfigs) {
207
+ throw new Error("SDK not initialized");
208
+ }
209
+ this.customerConfig = JSON.parse(jsonConfigs);
210
+ }
211
+ }
212
+ async getUserAuthConfig() {
213
+ if (this.userAuthConfig) {
214
+ return this.userAuthConfig;
215
+ }
216
+ await this.getConfig();
109
217
  const user = this.customerConfig.OIDC.user;
110
218
  this.userAuthConfig = {
111
219
  providers: [
@@ -128,13 +236,12 @@ var CrexSDK = (_class = class {
128
236
  }
129
237
  ]
130
238
  };
239
+ return this.userAuthConfig;
131
240
  }
132
- static setConfig(config) {
133
- _utils.saveInMemory.call(void 0, config, SDK_CONFIG_KEY);
134
- }
135
- }, _class);
136
-
137
-
138
-
139
- exports.CrexApi = CrexApi; exports.CrexSDK = CrexSDK;
241
+ };
242
+ // Annotate the CommonJS export names for ESM import in node:
243
+ 0 && (module.exports = {
244
+ CrexApi,
245
+ CrexSDK
246
+ });
140
247
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/periotto/Desktop/workspace/c-rex.net-web-client-foundation/packages/core/dist/index.js","../src/requests.ts","../src/sdk.ts"],"names":[],"mappings":"AAAA;ACAA,4EAA4D;AAC5D,6CAAoB;AACpB,6CAAuB;AAEvB,qCAA4C;AAE5C,IAAM,sBAAA,EAAwB,YAAA;AAC9B,IAAM,6BAAA,EAA+B,mBAAA;AAe9B,IAAM,QAAA,EAAN,MAAc;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EAED,WAAA,CAAY,MAAA,EAAyB,MAAA,EAAa;AACrD,IAAA,IAAA,CAAK,UAAA,EAAY,eAAA,CAAM,MAAA,CAAO;AAAA,MAC1B,OAAA,EAAS,MAAA,CAAO,OAAA;AAAA,MAChB,OAAA,EAAS;AAAA,QACL,cAAA,EAAgB;A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A;AACA,IAAA;AACW,IAAA;AACY,EAAA;AAC2B,IAAA;AAExC,IAAA;AACH,MAAA;AACuB,MAAA;AAC9B,IAAA;AAE2C,IAAA;AACnC,MAAA;AACwC,QAAA;AACpC,UAAA;AACA,UAAA;AACM,UAAA;AACN,UAAA;AACA,UAAA;AACH,QAAA;AAED,QAAA;AACY,MAAA;AACJ,QAAA;AACJ,UAAA;AACwB,UAAA;AAC5B,QAAA;AAEiC,QAAA;AACvB,UAAA;AACV,QAAA;AACJ,MAAA;AACJ,IAAA;AAEc,IAAA;AACM,MAAA;AACpB,IAAA;AAEgB,IAAA;AACpB,EAAA;AACJ;ADvCoD;AACA;AE9F5B;AAED;AAEF;AACV,EAAA;AACA,EAAA;AACuB,iBAAA;AACvB,EAAA;AAEc,EAAA;AAC0B,IAAA;AAErB,IAAA;AAC0B,IAAA;AAEV,IAAA;AAChB,IAAA;AACP,MAAA;AACP,QAAA;AACQ,UAAA;AACE,UAAA;AACA,UAAA;AACS,UAAA;AACC,UAAA;AACG,UAAA;AACoB,UAAA;AACjB,UAAA;AACX,YAAA;AACe,cAAA;AACI,cAAA;AACE,cAAA;AACA,cAAA;AAC5B,YAAA;AACJ,UAAA;AACJ,QAAA;AACJ,MAAA;AACJ,IAAA;AACJ,EAAA;AAEiD,EAAA;AACV,IAAA;AACvC,EAAA;AACJ;AF0FoD;AACA;AACA;AACA","file":"/Users/periotto/Desktop/workspace/c-rex.net-web-client-foundation/packages/core/dist/index.js","sourcesContent":[null,"import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API } from \"@c-rex/constants\";\nimport { Issuer } from \"openid-client\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\nconst CREX_TOKEN_HEADER_KEY = \"crex-token\";\nconst CREX_TOKEN_EXPIRY_HEADER_KEY = \"crex-token-expiry\";\n\ninterface APIGenericResponse<T> extends AxiosResponse {\n data: T;\n statusCode: number;\n}\n\ninterface CallParams {\n url: string;\n method: Method;\n body?: any;\n headers?: any;\n params?: any;\n}\n\nexport class CrexApi {\n private config: ConfigInterface;\n private apiClient: AxiosInstance;\n private logger: any;\n\n public constructor(config: ConfigInterface, logger: any) {\n this.apiClient = axios.create({\n baseURL: config.baseUrl,\n headers: {\n \"content-Type\": \"application/json\",\n },\n });\n\n this.config = config;\n this.logger = logger;\n }\n\n private async manageToken() {\n const headersAux: Record<string, string> = {};\n\n if (this.config.OIDC.client.enabled) {\n let token = getFromMemory(CREX_TOKEN_HEADER_KEY);\n let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);\n\n const now = Math.floor(Date.now() / 1000);\n\n if (!(token && tokenExpiry > now + 60)) {\n const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();\n\n token = tokenAux;\n\n saveInMemory(token, CREX_TOKEN_HEADER_KEY);\n saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);\n }\n\n headersAux['Authorization'] = `Bearer ${token}`;\n }\n\n return headersAux;\n }\n\n private async getToken(): Promise<{\n token: string;\n tokenExpiry: number;\n }> {\n let token = \"\";\n let tokenExpiry = 0;\n\n try {\n const now = Math.floor(Date.now() / 1000);\n const issuer = await Issuer.discover(this.config.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: this.config.OIDC.client.id,\n client_secret: this.config.OIDC.client.secret,\n });\n const tokenSet = await client.grant({ grant_type: 'client_credentials' });\n\n token = tokenSet.access_token!,\n tokenExpiry = now + tokenSet.expires_at!\n } catch (error) {\n console.log(\"error\", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);\n }\n\n return {\n token,\n tokenExpiry\n };\n }\n\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\n let response: APIGenericResponse<T> | undefined = undefined;\n\n headers = {\n ...headers,\n ...await this.manageToken(),\n };\n\n for (let retry = 0; retry < API.MAX_RETRY; retry++) {\n try {\n response = await this.apiClient.request({\n url,\n method,\n data: body,\n params,\n headers,\n });\n\n break;\n } catch (error) {\n console.log(\n \"error\",\n `API.execute ${retry + 1}º error when request ${url}. Error: ${error}`\n );\n\n if (retry === API.MAX_RETRY - 1) {\n throw error;\n }\n }\n }\n\n if (response) {\n return response.data;\n }\n\n throw new Error(\"API.execute error: Failed to retrieve a valid response\");\n }\n}","import { CrexApi } from \"./requests\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\nconst SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport class CrexSDK {\n public api!: CrexApi;\n public logger!: any;\n public userAuthConfig: any = {};\n public customerConfig!: ConfigInterface;\n\n public constructor() {\n const config = getFromMemory(SDK_CONFIG_KEY);\n\n this.customerConfig = config as ConfigInterface;\n this.api = new CrexApi(this.customerConfig, null);\n\n const user = this.customerConfig.OIDC.user;\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: { params: { scope: user.scope } },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\n }\n },\n },\n ]\n }\n }\n\n public static setConfig(config: ConfigInterface) {\n saveInMemory(config, SDK_CONFIG_KEY);\n }\n}"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/requests.ts","../../constants/src/index.ts","../../utils/src/utils.ts","../../utils/src/memory.ts","../../utils/src/classMerge.ts","../../utils/src/treeOfContent.ts","../src/sdk.ts"],"sourcesContent":["//Do not export logger.ts. Logger must be exported as an another entrypoint on package.json\nexport * from \"./requests\";\nexport * from \"./sdk\";","import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API, SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { Issuer } from \"openid-client\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { call, getFromMemory, saveInMemory } from \"@c-rex/utils\";\nimport { getCookie } from \"@c-rex/utils/next-cookies\";\n\nconst CREX_TOKEN_HEADER_KEY = \"crex-token\";\nconst CREX_TOKEN_EXPIRY_HEADER_KEY = \"crex-token-expiry\";\n\ninterface APIGenericResponse<T> extends AxiosResponse {\n data: T;\n statusCode: number;\n}\n\ninterface CallParams {\n url: string;\n method: Method;\n body?: any;\n headers?: any;\n params?: any;\n}\n\nexport class CrexApi {\n private customerConfig!: ConfigInterface;\n private apiClient!: AxiosInstance;\n\n private async manageToken() {\n const headersAux: Record<string, string> = {};\n\n if (this.customerConfig.OIDC.client.enabled) {\n let token = getFromMemory(CREX_TOKEN_HEADER_KEY);\n let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);\n\n const now = Math.floor(Date.now() / 1000);\n\n if (!(token && tokenExpiry > now + 60)) {\n const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();\n\n token = tokenAux;\n\n saveInMemory(token, CREX_TOKEN_HEADER_KEY);\n saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);\n }\n\n headersAux['Authorization'] = `Bearer ${token}`;\n }\n\n return headersAux;\n }\n\n private async getToken(): Promise<{\n token: string;\n tokenExpiry: number;\n }> {\n let token = \"\";\n let tokenExpiry = 0;\n\n try {\n const now = Math.floor(Date.now() / 1000);\n const issuer = await Issuer.discover(this.customerConfig.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: this.customerConfig.OIDC.client.id,\n client_secret: this.customerConfig.OIDC.client.secret,\n });\n const tokenSet = await client.grant({ grant_type: 'client_credentials' });\n\n token = tokenSet.access_token!;\n tokenExpiry = now + tokenSet.expires_at!;\n } catch (error) {\n call(\"CrexLogger.log\", {\n level: \"error\",\n message: `API.getToken error when request ${this.customerConfig.OIDC.client.issuer}. Error: ${error}`\n });\n }\n\n return {\n token,\n tokenExpiry\n };\n }\n\n private async initAPI() {\n if (!this.customerConfig) {\n const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\n }\n if (!this.apiClient) {\n this.apiClient = axios.create({\n baseURL: this.customerConfig.baseUrl,\n })\n }\n }\n\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\n\n await this.initAPI();\n\n let response: APIGenericResponse<T> | undefined = undefined;\n\n headers = {\n ...headers,\n ...await this.manageToken(),\n };\n\n for (let retry = 0; retry < API.MAX_RETRY; retry++) {\n try {\n response = await this.apiClient.request({\n url,\n method,\n data: body,\n params,\n headers,\n });\n\n break;\n } catch (error) {\n //TODO: add logger\n console.log(\n \"error\",\n `API.execute ${retry + 1}º error when request ${url}. Error: ${error}`\n );\n\n if (retry === API.MAX_RETRY - 1) {\n throw error;\n }\n }\n }\n\n if (response) {\n return response.data;\n }\n\n throw new Error(\"API.execute error: Failed to retrieve a valid response\");\n }\n}","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_UI_LANG = \"en\";\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];","import { FLAGS_BY_LANG } from \"@c-rex/constants\";\n\nexport const call = async<T = unknown>(method: string, params?: any): Promise<T> => {\n try {\n const res = await fetch(`/api/rpc`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ method, params }),\n });\n\n const json = await res.json();\n\n if (!res.ok) throw new Error(json.error || 'Unknown error');\n\n return json.data;\n } catch (error) {\n console.error(error);\n return null as any;\n }\n}\n\nexport const getCountryCodeByLang = (lang: string): string => {\n const mappedKeys = Object.keys(FLAGS_BY_LANG);\n\n if (!mappedKeys.includes(lang)) {\n return lang\n }\n\n type LangKey = keyof typeof FLAGS_BY_LANG;\n const country = FLAGS_BY_LANG[lang as LangKey]\n\n return country\n}","export function isBrowser() {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nexport function saveInMemory(value: any, key: string) {\n if (isBrowser()) throw new Error(\"saveInMemory is not supported in browser\");\n\n if (typeof global !== 'undefined' && !(key in global)) {\n (global as any)[key] = null;\n }\n\n const globalConfig = (global as any)[key] as any;\n\n if (globalConfig === null) {\n (global as any)[key] = value;\n }\n}\n\nexport function getFromMemory(key: string): any {\n if (isBrowser()) throw new Error(\"getFromMemory is not supported in browser\");\n\n return (global as any)[key];\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n","import { DirectoryNodesService } from \"@c-rex/services\";\nimport { DirectoryNodes, informationUnitsDirectories, TreeOfContent } from \"@c-rex/interfaces\";\n\nexport const generateTreeOfContent = async (\n directoryNodes: DirectoryNodes[],\n): Promise<TreeOfContent[]> => {\n\n const service = new DirectoryNodesService();\n\n if (directoryNodes.length == 0) return [];\n if (directoryNodes[0] == undefined) return [];\n\n let id = directoryNodes[0].shortId;\n let response = await service.getItem(id);\n const childList = await getChildrenInfo(response.childNodes);\n let result: TreeOfContent[] = childList;\n\n while (response.parents != undefined) {\n if (response.informationUnits[0] == undefined) return result;\n if (response.labels[0] == undefined) return result;\n if (response.parents[0] == undefined) return result;\n\n const infoId = response.informationUnits[0].shortId;\n const aux = {\n active: true,\n label: response.labels[0].value,\n id: response.shortId,\n link: `/info/${infoId}`,\n children: [...result],\n };\n id = response.parents[0].shortId;\n response = await service.getItem(id);\n\n const tree = await getChildrenInfo(response.childNodes, aux);\n\n result = [...tree];\n }\n\n return result;\n};\n\nconst getChildrenInfo = async (\n childNodes: informationUnitsDirectories[],\n childItem?: TreeOfContent,\n): Promise<TreeOfContent[]> => {\n const result: TreeOfContent[] = [];\n if (childNodes == undefined) return result;\n\n for (const item of childNodes) {\n if (item.labels[0] == undefined) break;\n\n const infoId = await getLink(item.shortId);\n let resultItem: TreeOfContent = {\n active: false,\n label: item.labels[0].value,\n link: `/info/${infoId}`,\n id: item.shortId,\n children: [],\n };\n\n if (childItem?.id == item.shortId) {\n resultItem = childItem;\n }\n result.push(resultItem);\n }\n\n return result;\n};\n\nconst getLink = async (id: string): Promise<string> => {\n const service = new DirectoryNodesService();\n const response = await service.getItem(id);\n\n if (response.informationUnits == undefined) return \"\";\n if (response.informationUnits[0] == undefined) return \"\";\n\n return response.informationUnits[0].shortId;\n};","import { SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getCookie } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexSDK {\n public userAuthConfig!: any;\n public customerConfig!: ConfigInterface;\n\n private async getConfig() {\n if (!this.customerConfig) {\n const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\n }\n }\n\n public async getUserAuthConfig() {\n if (this.userAuthConfig) {\n return this.userAuthConfig;\n }\n\n await this.getConfig();\n\n const user = this.customerConfig.OIDC.user;\n\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: { params: { scope: user.scope } },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\n }\n },\n },\n ]\n };\n\n return this.userAuthConfig;\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,mBAA4D;;;ACuBrD,IAAM,MAAM;AAAA,EACf,WAAW;AAAA,EACX,aAAa;AAAA,EACb,aAAa;AAAA,IACT,gBAAgB;AAAA,EACpB;AACJ;AAEO,IAAM,iBAAiB;;;AD7B9B,2BAAuB;;;AEAhB,IAAM,OAAO,OAAmB,QAAgB,WAA6B;AAChF,MAAI;AACA,UAAM,MAAM,MAAM,MAAM,YAAY;AAAA,MAChC,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU,EAAE,QAAQ,OAAO,CAAC;AAAA,IAC3C,CAAC;AAED,UAAM,OAAO,MAAM,IAAI,KAAK;AAE5B,QAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,KAAK,SAAS,eAAe;AAE1D,WAAO,KAAK;AAAA,EAChB,SAAS,OAAO;AACZ,YAAQ,MAAM,KAAK;AACnB,WAAO;AAAA,EACX;AACJ;;;ACnBO,SAAS,YAAY;AACxB,SAAO,OAAO,WAAW,eAAe,OAAO,aAAa;AAChE;AAEO,SAAS,aAAa,OAAY,KAAa;AAClD,MAAI,UAAU,EAAG,OAAM,IAAI,MAAM,0CAA0C;AAE3E,MAAI,OAAO,WAAW,eAAe,EAAE,OAAO,SAAS;AACnD,IAAC,OAAe,GAAG,IAAI;AAAA,EAC3B;AAEA,QAAM,eAAgB,OAAe,GAAG;AAExC,MAAI,iBAAiB,MAAM;AACvB,IAAC,OAAe,GAAG,IAAI;AAAA,EAC3B;AACJ;AAEO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;AACJ;;;AM9IA,IAAAC,uBAA0B;AAEnB,IAAM,UAAN,MAAc;AAAA,EACV;AAAA,EACA;AAAA,EAEP,MAAc,YAAY;AACtB,QAAI,CAAC,KAAK,gBAAgB;AACtB,YAAM,cAAc,UAAM,gCAAU,cAAc;AAClD,UAAI,CAAC,aAAa;AACd,cAAM,IAAI,MAAM,qBAAqB;AAAA,MACzC;AACA,WAAK,iBAAiB,KAAK,MAAM,WAAW;AAAA,IAChD;AAAA,EACJ;AAAA,EAEA,MAAa,oBAAoB;AAC7B,QAAI,KAAK,gBAAgB;AACrB,aAAO,KAAK;AAAA,IAChB;AAEA,UAAM,KAAK,UAAU;AAErB,UAAM,OAAO,KAAK,eAAe,KAAK;AAEtC,SAAK,iBAAiB;AAAA,MAClB,WAAW;AAAA,QACP;AAAA,UACI,IAAI;AAAA,UACJ,MAAM;AAAA,UACN,MAAM;AAAA,UACN,UAAU,KAAK;AAAA,UACf,WAAW,KAAK;AAAA,UAChB,cAAc,KAAK;AAAA,UACnB,eAAe,EAAE,QAAQ,EAAE,OAAO,KAAK,MAAM,EAAE;AAAA,UAC/C,QAAQ,SAAc;AAClB,mBAAO;AAAA,cACH,IAAI,QAAQ,MAAM;AAAA,cAClB,MAAM,QAAQ,QAAQ;AAAA,cACtB,OAAO,QAAQ,SAAS;AAAA,cACxB,OAAO,QAAQ,SAAS;AAAA,YAC5B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAEA,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["axios","import_next_cookies"]}
package/dist/index.mjs CHANGED
@@ -1,27 +1,72 @@
1
1
  // src/requests.ts
2
2
  import axios from "axios";
3
- import { API } from "@c-rex/constants";
3
+
4
+ // ../constants/src/index.ts
5
+ var API = {
6
+ MAX_RETRY: 3,
7
+ API_TIMEOUT: 1e4,
8
+ API_HEADERS: {
9
+ "content-Type": "application/json"
10
+ }
11
+ };
12
+ var SDK_CONFIG_KEY = "crex-sdk-config";
13
+
14
+ // src/requests.ts
4
15
  import { Issuer } from "openid-client";
5
- import { getFromMemory, saveInMemory } from "@c-rex/utils";
16
+
17
+ // ../utils/src/utils.ts
18
+ var call = async (method, params) => {
19
+ try {
20
+ const res = await fetch(`/api/rpc`, {
21
+ method: "POST",
22
+ headers: { "Content-Type": "application/json" },
23
+ body: JSON.stringify({ method, params })
24
+ });
25
+ const json = await res.json();
26
+ if (!res.ok) throw new Error(json.error || "Unknown error");
27
+ return json.data;
28
+ } catch (error) {
29
+ console.error(error);
30
+ return null;
31
+ }
32
+ };
33
+
34
+ // ../utils/src/memory.ts
35
+ function isBrowser() {
36
+ return typeof window !== "undefined" && typeof document !== "undefined";
37
+ }
38
+ function saveInMemory(value, key) {
39
+ if (isBrowser()) throw new Error("saveInMemory is not supported in browser");
40
+ if (typeof global !== "undefined" && !(key in global)) {
41
+ global[key] = null;
42
+ }
43
+ const globalConfig = global[key];
44
+ if (globalConfig === null) {
45
+ global[key] = value;
46
+ }
47
+ }
48
+ function getFromMemory(key) {
49
+ if (isBrowser()) throw new Error("getFromMemory is not supported in browser");
50
+ return global[key];
51
+ }
52
+
53
+ // ../utils/src/classMerge.ts
54
+ import { clsx } from "clsx";
55
+ import { twMerge } from "tailwind-merge";
56
+
57
+ // ../utils/src/treeOfContent.ts
58
+ import { DirectoryNodesService } from "@c-rex/services";
59
+
60
+ // src/requests.ts
61
+ import { getCookie } from "@c-rex/utils/next-cookies";
6
62
  var CREX_TOKEN_HEADER_KEY = "crex-token";
7
63
  var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
8
64
  var CrexApi = class {
9
- config;
65
+ customerConfig;
10
66
  apiClient;
11
- logger;
12
- constructor(config, logger) {
13
- this.apiClient = axios.create({
14
- baseURL: config.baseUrl,
15
- headers: {
16
- "content-Type": "application/json"
17
- }
18
- });
19
- this.config = config;
20
- this.logger = logger;
21
- }
22
67
  async manageToken() {
23
68
  const headersAux = {};
24
- if (this.config.OIDC.client.enabled) {
69
+ if (this.customerConfig.OIDC.client.enabled) {
25
70
  let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
26
71
  let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);
27
72
  const now = Math.floor(Date.now() / 1e3);
@@ -40,21 +85,39 @@ var CrexApi = class {
40
85
  let tokenExpiry = 0;
41
86
  try {
42
87
  const now = Math.floor(Date.now() / 1e3);
43
- const issuer = await Issuer.discover(this.config.OIDC.client.issuer);
88
+ const issuer = await Issuer.discover(this.customerConfig.OIDC.client.issuer);
44
89
  const client = new issuer.Client({
45
- client_id: this.config.OIDC.client.id,
46
- client_secret: this.config.OIDC.client.secret
90
+ client_id: this.customerConfig.OIDC.client.id,
91
+ client_secret: this.customerConfig.OIDC.client.secret
47
92
  });
48
93
  const tokenSet = await client.grant({ grant_type: "client_credentials" });
49
- token = tokenSet.access_token, tokenExpiry = now + tokenSet.expires_at;
94
+ token = tokenSet.access_token;
95
+ tokenExpiry = now + tokenSet.expires_at;
50
96
  } catch (error) {
51
- console.log("error", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);
97
+ call("CrexLogger.log", {
98
+ level: "error",
99
+ message: `API.getToken error when request ${this.customerConfig.OIDC.client.issuer}. Error: ${error}`
100
+ });
52
101
  }
53
102
  return {
54
103
  token,
55
104
  tokenExpiry
56
105
  };
57
106
  }
107
+ async initAPI() {
108
+ if (!this.customerConfig) {
109
+ const jsonConfigs = await getCookie(SDK_CONFIG_KEY);
110
+ if (!jsonConfigs) {
111
+ throw new Error("SDK not initialized");
112
+ }
113
+ this.customerConfig = JSON.parse(jsonConfigs);
114
+ }
115
+ if (!this.apiClient) {
116
+ this.apiClient = axios.create({
117
+ baseURL: this.customerConfig.baseUrl
118
+ });
119
+ }
120
+ }
58
121
  async execute({
59
122
  url,
60
123
  method,
@@ -62,6 +125,7 @@ var CrexApi = class {
62
125
  body,
63
126
  headers = {}
64
127
  }) {
128
+ await this.initAPI();
65
129
  let response = void 0;
66
130
  headers = {
67
131
  ...headers,
@@ -95,17 +159,24 @@ var CrexApi = class {
95
159
  };
96
160
 
97
161
  // src/sdk.ts
98
- import { getFromMemory as getFromMemory2, saveInMemory as saveInMemory2 } from "@c-rex/utils";
99
- var SDK_CONFIG_KEY = "crex-sdk-config";
162
+ import { getCookie as getCookie2 } from "@c-rex/utils/next-cookies";
100
163
  var CrexSDK = class {
101
- api;
102
- logger;
103
- userAuthConfig = {};
164
+ userAuthConfig;
104
165
  customerConfig;
105
- constructor() {
106
- const config = getFromMemory2(SDK_CONFIG_KEY);
107
- this.customerConfig = config;
108
- this.api = new CrexApi(this.customerConfig, null);
166
+ async getConfig() {
167
+ if (!this.customerConfig) {
168
+ const jsonConfigs = await getCookie2(SDK_CONFIG_KEY);
169
+ if (!jsonConfigs) {
170
+ throw new Error("SDK not initialized");
171
+ }
172
+ this.customerConfig = JSON.parse(jsonConfigs);
173
+ }
174
+ }
175
+ async getUserAuthConfig() {
176
+ if (this.userAuthConfig) {
177
+ return this.userAuthConfig;
178
+ }
179
+ await this.getConfig();
109
180
  const user = this.customerConfig.OIDC.user;
110
181
  this.userAuthConfig = {
111
182
  providers: [
@@ -128,9 +199,7 @@ var CrexSDK = class {
128
199
  }
129
200
  ]
130
201
  };
131
- }
132
- static setConfig(config) {
133
- saveInMemory2(config, SDK_CONFIG_KEY);
202
+ return this.userAuthConfig;
134
203
  }
135
204
  };
136
205
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/requests.ts","../src/sdk.ts"],"sourcesContent":["import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API } from \"@c-rex/constants\";\nimport { Issuer } from \"openid-client\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\nconst CREX_TOKEN_HEADER_KEY = \"crex-token\";\nconst CREX_TOKEN_EXPIRY_HEADER_KEY = \"crex-token-expiry\";\n\ninterface APIGenericResponse<T> extends AxiosResponse {\n data: T;\n statusCode: number;\n}\n\ninterface CallParams {\n url: string;\n method: Method;\n body?: any;\n headers?: any;\n params?: any;\n}\n\nexport class CrexApi {\n private config: ConfigInterface;\n private apiClient: AxiosInstance;\n private logger: any;\n\n public constructor(config: ConfigInterface, logger: any) {\n this.apiClient = axios.create({\n baseURL: config.baseUrl,\n headers: {\n \"content-Type\": \"application/json\",\n },\n });\n\n this.config = config;\n this.logger = logger;\n }\n\n private async manageToken() {\n const headersAux: Record<string, string> = {};\n\n if (this.config.OIDC.client.enabled) {\n let token = getFromMemory(CREX_TOKEN_HEADER_KEY);\n let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);\n\n const now = Math.floor(Date.now() / 1000);\n\n if (!(token && tokenExpiry > now + 60)) {\n const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();\n\n token = tokenAux;\n\n saveInMemory(token, CREX_TOKEN_HEADER_KEY);\n saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);\n }\n\n headersAux['Authorization'] = `Bearer ${token}`;\n }\n\n return headersAux;\n }\n\n private async getToken(): Promise<{\n token: string;\n tokenExpiry: number;\n }> {\n let token = \"\";\n let tokenExpiry = 0;\n\n try {\n const now = Math.floor(Date.now() / 1000);\n const issuer = await Issuer.discover(this.config.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: this.config.OIDC.client.id,\n client_secret: this.config.OIDC.client.secret,\n });\n const tokenSet = await client.grant({ grant_type: 'client_credentials' });\n\n token = tokenSet.access_token!,\n tokenExpiry = now + tokenSet.expires_at!\n } catch (error) {\n console.log(\"error\", `API.getToken error when request ${this.config.OIDC.client.issuer}. Error: ${error}`);\n }\n\n return {\n token,\n tokenExpiry\n };\n }\n\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\n let response: APIGenericResponse<T> | undefined = undefined;\n\n headers = {\n ...headers,\n ...await this.manageToken(),\n };\n\n for (let retry = 0; retry < API.MAX_RETRY; retry++) {\n try {\n response = await this.apiClient.request({\n url,\n method,\n data: body,\n params,\n headers,\n });\n\n break;\n } catch (error) {\n console.log(\n \"error\",\n `API.execute ${retry + 1}º error when request ${url}. Error: ${error}`\n );\n\n if (retry === API.MAX_RETRY - 1) {\n throw error;\n }\n }\n }\n\n if (response) {\n return response.data;\n }\n\n throw new Error(\"API.execute error: Failed to retrieve a valid response\");\n }\n}","import { CrexApi } from \"./requests\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getFromMemory, saveInMemory } from \"@c-rex/utils\";\n\nconst SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport class CrexSDK {\n public api!: CrexApi;\n public logger!: any;\n public userAuthConfig: any = {};\n public customerConfig!: ConfigInterface;\n\n public constructor() {\n const config = getFromMemory(SDK_CONFIG_KEY);\n\n this.customerConfig = config as ConfigInterface;\n this.api = new CrexApi(this.customerConfig, null);\n\n const user = this.customerConfig.OIDC.user;\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: { params: { scope: user.scope } },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\n }\n },\n },\n ]\n }\n }\n\n public static setConfig(config: ConfigInterface) {\n saveInMemory(config, SDK_CONFIG_KEY);\n }\n}"],"mappings":";AAAA,OAAO,WAAqD;AAC5D,SAAS,WAAW;AACpB,SAAS,cAAc;AAEvB,SAAS,eAAe,oBAAoB;AAE5C,IAAM,wBAAwB;AAC9B,IAAM,+BAA+B;AAe9B,IAAM,UAAN,MAAc;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EAED,YAAY,QAAyB,QAAa;AACrD,SAAK,YAAY,MAAM,OAAO;AAAA,MAC1B,SAAS,OAAO;AAAA,MAChB,SAAS;AAAA,QACL,gBAAgB;AAA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,MAAM;AAAA,cAClB,MAAM,QAAQ,QAAQ;AAAA,cACtB,OAAO,QAAQ,SAAS;AAAA,cACxB,OAAO,QAAQ,SAAS;AAAA,YAC5B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AAAA,EAEA,OAAc,UAAU,QAAyB;AAC7C,IAAAC,cAAa,QAAQ,cAAc;AAAA,EACvC;AACJ;","names":["getFromMemory","saveInMemory"]}
1
+ {"version":3,"sources":["../src/requests.ts","../../constants/src/index.ts","../../utils/src/utils.ts","../../utils/src/memory.ts","../../utils/src/classMerge.ts","../../utils/src/treeOfContent.ts","../src/sdk.ts"],"sourcesContent":["import axios, { AxiosResponse, Method, AxiosInstance } from \"axios\";\nimport { API, SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { Issuer } from \"openid-client\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { call, getFromMemory, saveInMemory } from \"@c-rex/utils\";\nimport { getCookie } from \"@c-rex/utils/next-cookies\";\n\nconst CREX_TOKEN_HEADER_KEY = \"crex-token\";\nconst CREX_TOKEN_EXPIRY_HEADER_KEY = \"crex-token-expiry\";\n\ninterface APIGenericResponse<T> extends AxiosResponse {\n data: T;\n statusCode: number;\n}\n\ninterface CallParams {\n url: string;\n method: Method;\n body?: any;\n headers?: any;\n params?: any;\n}\n\nexport class CrexApi {\n private customerConfig!: ConfigInterface;\n private apiClient!: AxiosInstance;\n\n private async manageToken() {\n const headersAux: Record<string, string> = {};\n\n if (this.customerConfig.OIDC.client.enabled) {\n let token = getFromMemory(CREX_TOKEN_HEADER_KEY);\n let tokenExpiry = getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY);\n\n const now = Math.floor(Date.now() / 1000);\n\n if (!(token && tokenExpiry > now + 60)) {\n const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();\n\n token = tokenAux;\n\n saveInMemory(token, CREX_TOKEN_HEADER_KEY);\n saveInMemory(tokenExpiryAux, CREX_TOKEN_EXPIRY_HEADER_KEY);\n }\n\n headersAux['Authorization'] = `Bearer ${token}`;\n }\n\n return headersAux;\n }\n\n private async getToken(): Promise<{\n token: string;\n tokenExpiry: number;\n }> {\n let token = \"\";\n let tokenExpiry = 0;\n\n try {\n const now = Math.floor(Date.now() / 1000);\n const issuer = await Issuer.discover(this.customerConfig.OIDC.client.issuer);\n const client = new issuer.Client({\n client_id: this.customerConfig.OIDC.client.id,\n client_secret: this.customerConfig.OIDC.client.secret,\n });\n const tokenSet = await client.grant({ grant_type: 'client_credentials' });\n\n token = tokenSet.access_token!;\n tokenExpiry = now + tokenSet.expires_at!;\n } catch (error) {\n call(\"CrexLogger.log\", {\n level: \"error\",\n message: `API.getToken error when request ${this.customerConfig.OIDC.client.issuer}. Error: ${error}`\n });\n }\n\n return {\n token,\n tokenExpiry\n };\n }\n\n private async initAPI() {\n if (!this.customerConfig) {\n const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\n }\n if (!this.apiClient) {\n this.apiClient = axios.create({\n baseURL: this.customerConfig.baseUrl,\n })\n }\n }\n\n async execute<T>({\n url,\n method,\n params,\n body,\n headers = {},\n }: CallParams): Promise<T> {\n\n await this.initAPI();\n\n let response: APIGenericResponse<T> | undefined = undefined;\n\n headers = {\n ...headers,\n ...await this.manageToken(),\n };\n\n for (let retry = 0; retry < API.MAX_RETRY; retry++) {\n try {\n response = await this.apiClient.request({\n url,\n method,\n data: body,\n params,\n headers,\n });\n\n break;\n } catch (error) {\n //TODO: add logger\n console.log(\n \"error\",\n `API.execute ${retry + 1}º error when request ${url}. Error: ${error}`\n );\n\n if (retry === API.MAX_RETRY - 1) {\n throw error;\n }\n }\n }\n\n if (response) {\n return response.data;\n }\n\n throw new Error(\"API.execute error: Failed to retrieve a valid response\");\n }\n}","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_UI_LANG = \"en\";\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];","import { FLAGS_BY_LANG } from \"@c-rex/constants\";\n\nexport const call = async<T = unknown>(method: string, params?: any): Promise<T> => {\n try {\n const res = await fetch(`/api/rpc`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ method, params }),\n });\n\n const json = await res.json();\n\n if (!res.ok) throw new Error(json.error || 'Unknown error');\n\n return json.data;\n } catch (error) {\n console.error(error);\n return null as any;\n }\n}\n\nexport const getCountryCodeByLang = (lang: string): string => {\n const mappedKeys = Object.keys(FLAGS_BY_LANG);\n\n if (!mappedKeys.includes(lang)) {\n return lang\n }\n\n type LangKey = keyof typeof FLAGS_BY_LANG;\n const country = FLAGS_BY_LANG[lang as LangKey]\n\n return country\n}","export function isBrowser() {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nexport function saveInMemory(value: any, key: string) {\n if (isBrowser()) throw new Error(\"saveInMemory is not supported in browser\");\n\n if (typeof global !== 'undefined' && !(key in global)) {\n (global as any)[key] = null;\n }\n\n const globalConfig = (global as any)[key] as any;\n\n if (globalConfig === null) {\n (global as any)[key] = value;\n }\n}\n\nexport function getFromMemory(key: string): any {\n if (isBrowser()) throw new Error(\"getFromMemory is not supported in browser\");\n\n return (global as any)[key];\n}\n","import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n","import { DirectoryNodesService } from \"@c-rex/services\";\nimport { DirectoryNodes, informationUnitsDirectories, TreeOfContent } from \"@c-rex/interfaces\";\n\nexport const generateTreeOfContent = async (\n directoryNodes: DirectoryNodes[],\n): Promise<TreeOfContent[]> => {\n\n const service = new DirectoryNodesService();\n\n if (directoryNodes.length == 0) return [];\n if (directoryNodes[0] == undefined) return [];\n\n let id = directoryNodes[0].shortId;\n let response = await service.getItem(id);\n const childList = await getChildrenInfo(response.childNodes);\n let result: TreeOfContent[] = childList;\n\n while (response.parents != undefined) {\n if (response.informationUnits[0] == undefined) return result;\n if (response.labels[0] == undefined) return result;\n if (response.parents[0] == undefined) return result;\n\n const infoId = response.informationUnits[0].shortId;\n const aux = {\n active: true,\n label: response.labels[0].value,\n id: response.shortId,\n link: `/info/${infoId}`,\n children: [...result],\n };\n id = response.parents[0].shortId;\n response = await service.getItem(id);\n\n const tree = await getChildrenInfo(response.childNodes, aux);\n\n result = [...tree];\n }\n\n return result;\n};\n\nconst getChildrenInfo = async (\n childNodes: informationUnitsDirectories[],\n childItem?: TreeOfContent,\n): Promise<TreeOfContent[]> => {\n const result: TreeOfContent[] = [];\n if (childNodes == undefined) return result;\n\n for (const item of childNodes) {\n if (item.labels[0] == undefined) break;\n\n const infoId = await getLink(item.shortId);\n let resultItem: TreeOfContent = {\n active: false,\n label: item.labels[0].value,\n link: `/info/${infoId}`,\n id: item.shortId,\n children: [],\n };\n\n if (childItem?.id == item.shortId) {\n resultItem = childItem;\n }\n result.push(resultItem);\n }\n\n return result;\n};\n\nconst getLink = async (id: string): Promise<string> => {\n const service = new DirectoryNodesService();\n const response = await service.getItem(id);\n\n if (response.informationUnits == undefined) return \"\";\n if (response.informationUnits[0] == undefined) return \"\";\n\n return response.informationUnits[0].shortId;\n};","import { SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getCookie } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexSDK {\n public userAuthConfig!: any;\n public customerConfig!: ConfigInterface;\n\n private async getConfig() {\n if (!this.customerConfig) {\n const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\n }\n }\n\n public async getUserAuthConfig() {\n if (this.userAuthConfig) {\n return this.userAuthConfig;\n }\n\n await this.getConfig();\n\n const user = this.customerConfig.OIDC.user;\n\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: { params: { scope: user.scope } },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\n }\n },\n },\n ]\n };\n\n return this.userAuthConfig;\n }\n}"],"mappings":";AAAA,OAAO,WAAqD;;;ACuBrD,IAAM,MAAM;AAAA,EACf,WAAW;AAAA,EACX,aAAa;AAAA,EACb,aAAa;AAAA,IACT,gBAAgB;AAAA,EACpB;AACJ;AAEO,IAAM,iBAAiB;;;AD7B9B,SAAS,cAAc;;;AEAhB,IAAM,OAAO,OAAmB,QAAgB,WAA6B;AAChF,MAAI;AACA,UAAM,MAAM,MAAM,MAAM,YAAY;AAAA,MAChC,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU,EAAE,QAAQ,OAAO,CAAC;AAAA,IAC3C,CAAC;AAED,UAAM,OAAO,MAAM,IAAI,KAAK;AAE5B,QAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MA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,MAAM;AAAA,cAClB,MAAM,QAAQ,QAAQ;AAAA,cACtB,OAAO,QAAQ,SAAS;AAAA,cACxB,OAAO,QAAQ,SAAS;AAAA,YAC5B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAEA,WAAO,KAAK;AAAA,EAChB;AACJ;","names":["getCookie"]}
@@ -0,0 +1,16 @@
1
+ import winston from 'winston';
2
+ import { LogLevelType, LogCategoriesType } from '@c-rex/types';
3
+
4
+ declare class CrexLogger {
5
+ private customerConfig;
6
+ logger: winston.Logger;
7
+ private initLogger;
8
+ log({ level, message, category }: {
9
+ level: LogLevelType;
10
+ message: string;
11
+ category?: LogCategoriesType;
12
+ }): Promise<void>;
13
+ private createLogger;
14
+ }
15
+
16
+ export { CrexLogger };
@@ -0,0 +1,16 @@
1
+ import winston from 'winston';
2
+ import { LogLevelType, LogCategoriesType } from '@c-rex/types';
3
+
4
+ declare class CrexLogger {
5
+ private customerConfig;
6
+ logger: winston.Logger;
7
+ private initLogger;
8
+ log({ level, message, category }: {
9
+ level: LogLevelType;
10
+ message: string;
11
+ category?: LogCategoriesType;
12
+ }): Promise<void>;
13
+ private createLogger;
14
+ }
15
+
16
+ export { CrexLogger };
package/dist/logger.js ADDED
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/logger.ts
31
+ var logger_exports = {};
32
+ __export(logger_exports, {
33
+ CrexLogger: () => CrexLogger
34
+ });
35
+ module.exports = __toCommonJS(logger_exports);
36
+ var import_winston = __toESM(require("winston"));
37
+
38
+ // src/transports/matomo.ts
39
+ var import_winston_transport = __toESM(require("winston-transport"));
40
+
41
+ // ../constants/src/index.ts
42
+ var ALL = "*";
43
+ var LOG_LEVELS = {
44
+ critical: 2,
45
+ error: 3,
46
+ warning: 4,
47
+ info: 6,
48
+ debug: 7
49
+ };
50
+ var SDK_CONFIG_KEY = "crex-sdk-config";
51
+
52
+ // src/sdk.ts
53
+ var import_next_cookies = require("@c-rex/utils/next-cookies");
54
+ var CrexSDK = class {
55
+ userAuthConfig;
56
+ customerConfig;
57
+ async getConfig() {
58
+ if (!this.customerConfig) {
59
+ const jsonConfigs = await (0, import_next_cookies.getCookie)(SDK_CONFIG_KEY);
60
+ if (!jsonConfigs) {
61
+ throw new Error("SDK not initialized");
62
+ }
63
+ this.customerConfig = JSON.parse(jsonConfigs);
64
+ }
65
+ }
66
+ async getUserAuthConfig() {
67
+ if (this.userAuthConfig) {
68
+ return this.userAuthConfig;
69
+ }
70
+ await this.getConfig();
71
+ const user = this.customerConfig.OIDC.user;
72
+ this.userAuthConfig = {
73
+ providers: [
74
+ {
75
+ id: "crex",
76
+ name: "CREX",
77
+ type: "oauth",
78
+ clientId: user.id,
79
+ wellKnown: user.issuer,
80
+ clientSecret: user.secret,
81
+ authorization: { params: { scope: user.scope } },
82
+ profile(profile) {
83
+ return {
84
+ id: profile.id || "fake Id",
85
+ name: profile.name || "Fake Name",
86
+ email: profile.email || "fake Email",
87
+ image: profile.image || "fake Image"
88
+ };
89
+ }
90
+ }
91
+ ]
92
+ };
93
+ return this.userAuthConfig;
94
+ }
95
+ };
96
+
97
+ // src/transports/matomo.ts
98
+ var MatomoTransport = class extends import_winston_transport.default {
99
+ matomoTransport;
100
+ constructor(opts) {
101
+ super(opts);
102
+ this.matomoTransport = new import_winston_transport.default();
103
+ }
104
+ log(info, callback) {
105
+ const SDK = CrexSDK.getInstance();
106
+ const matomoCategory = SDK.customerConfig.logs.matomo.categoriesLevel;
107
+ if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
108
+ this.matomoTransport.log(info, callback);
109
+ }
110
+ }
111
+ };
112
+
113
+ // src/transports/graylog.ts
114
+ var import_winston_transport2 = __toESM(require("winston-transport"));
115
+ var import_winston_graylog2 = __toESM(require("winston-graylog2"));
116
+ var GraylogTransport = class extends import_winston_transport2.default {
117
+ graylogTransport;
118
+ constructor(opts) {
119
+ super(opts);
120
+ this.graylogTransport = new import_winston_graylog2.default({
121
+ name: "Periotto-TEST",
122
+ silent: false,
123
+ handleExceptions: false,
124
+ graylog: {
125
+ servers: [{ host: "localhost", port: 12201 }]
126
+ }
127
+ });
128
+ }
129
+ log(info, callback) {
130
+ const SDK = CrexSDK.getInstance();
131
+ const graylogCategory = SDK.customerConfig.logs.graylog.categoriesLevel;
132
+ if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
133
+ this.graylogTransport.log(info, callback);
134
+ }
135
+ }
136
+ };
137
+
138
+ // src/logger.ts
139
+ var import_next_cookies2 = require("@c-rex/utils/next-cookies");
140
+ var CrexLogger = class {
141
+ customerConfig;
142
+ logger;
143
+ async initLogger() {
144
+ if (!this.customerConfig) {
145
+ const jsonConfigs = await (0, import_next_cookies2.getCookie)(SDK_CONFIG_KEY);
146
+ if (!jsonConfigs) {
147
+ throw new Error("SDK not initialized");
148
+ }
149
+ this.customerConfig = JSON.parse(jsonConfigs);
150
+ }
151
+ if (!this.logger) {
152
+ this.logger = this.createLogger();
153
+ }
154
+ }
155
+ async log({ level, message, category }) {
156
+ await this.initLogger();
157
+ this.logger.log(level, message, category);
158
+ }
159
+ createLogger() {
160
+ return import_winston.default.createLogger({
161
+ levels: LOG_LEVELS,
162
+ transports: [
163
+ new import_winston.default.transports.Console({
164
+ level: this.customerConfig.logs.console.minimumLevel,
165
+ silent: this.customerConfig.logs.console.silent
166
+ }),
167
+ new MatomoTransport({
168
+ level: this.customerConfig.logs.console.minimumLevel,
169
+ silent: this.customerConfig.logs.console.silent
170
+ }),
171
+ new GraylogTransport({
172
+ level: this.customerConfig.logs.graylog.minimumLevel,
173
+ silent: this.customerConfig.logs.graylog.silent
174
+ })
175
+ ]
176
+ });
177
+ }
178
+ };
179
+ // Annotate the CommonJS export names for ESM import in node:
180
+ 0 && (module.exports = {
181
+ CrexLogger
182
+ });
183
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/logger.ts","../src/transports/matomo.ts","../../constants/src/index.ts","../src/sdk.ts","../src/transports/graylog.ts"],"sourcesContent":["import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS, SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { getCookie } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n private async initLogger() {\n if (!this.customerConfig) {\n const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\n }\n\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n }\n\n public async log({ level, message, category }: {\n level: LogLevelType,\n message: string,\n category?: LogCategoriesType\n }) {\n await this.initLogger();\n this.logger.log(level, message, category);\n }\n\n private createLogger() {\n return winston.createLogger({\n levels: LOG_LEVELS,\n transports: [\n new winston.transports.Console({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new MatomoTransport({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new GraylogTransport({\n level: this.customerConfig.logs.graylog.minimumLevel,\n silent: this.customerConfig.logs.graylog.silent,\n }),\n ],\n });\n }\n}","import Transport from \"winston-transport\";\nimport { CrexSDK } from \"..\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\n\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n\n constructor(opts: any) {\n super(opts);\n\n this.matomoTransport = new Transport();\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const SDK = CrexSDK.getInstance();\n const matomoCategory = SDK.customerConfig.logs.matomo.categoriesLevel\n\n if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {\n\n this.matomoTransport.log(info, callback);\n }\n }\n}\n","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_UI_LANG = \"en\";\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];","import { SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getCookie } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexSDK {\n public userAuthConfig!: any;\n public customerConfig!: ConfigInterface;\n\n private async getConfig() {\n if (!this.customerConfig) {\n const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\n }\n }\n\n public async getUserAuthConfig() {\n if (this.userAuthConfig) {\n return this.userAuthConfig;\n }\n\n await this.getConfig();\n\n const user = this.customerConfig.OIDC.user;\n\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: { params: { scope: user.scope } },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\n }\n },\n },\n ]\n };\n\n return this.userAuthConfig;\n }\n}","import Transport from \"winston-transport\";\nimport Graylog2Transport from \"winston-graylog2\";\nimport { CrexSDK } from \"..\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\n\nexport class GraylogTransport extends Transport {\n public graylogTransport: any;\n\n constructor(opts: any) {\n super(opts);\n\n this.graylogTransport = new Graylog2Transport({\n name: \"Periotto-TEST\",\n silent: false,\n handleExceptions: false,\n graylog: {\n servers: [{ host: \"localhost\", port: 12201 }],\n },\n });\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const SDK = CrexSDK.getInstance();\n const graylogCategory = SDK.customerConfig.logs.graylog.categoriesLevel\n\n if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {\n this.graylogTransport.log(info, callback);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAoB;;;ACApB,+BAAsB;;;ACAf,IAAM,MAAM;AAeZ,IAAM,aAAa;AAAA,EACtB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AACX;AAUO,IAAM,iBAAiB;;;AC7B9B,0BAA0B;AAEnB,IAAM,UAAN,MAAc;AAAA,EACV;AAAA,EACA;AAAA,EAEP,MAAc,YAAY;AACtB,QAAI,CAAC,KAAK,gBAAgB;AACtB,YAAM,cAAc,UAAM,+BAAU,cAAc;AAClD,UAAI,CAAC,aAAa;AACd,cAAM,IAAI,MAAM,qBAAqB;AAAA,MACzC;AACA,WAAK,iBAAiB,KAAK,MAAM,WAAW;AAAA,IAChD;AAAA,EACJ;AAAA,EAEA,MAAa,oBAAoB;AAC7B,QAAI,KAAK,gBAAgB;AACrB,aAAO,KAAK;AAAA,IAChB;AAEA,UAAM,KAAK,UAAU;AAErB,UAAM,OAAO,KAAK,eAAe,KAAK;AAEtC,SAAK,iBAAiB;AAAA,MAClB,WAAW;AAAA,QACP;AAAA,UACI,IAAI;AAAA,UACJ,MAAM;AAAA,UACN,MAAM;AAAA,UACN,UAAU,KAAK;AAAA,UACf,WAAW,KAAK;AAAA,UAChB,cAAc,KAAK;AAAA,UACnB,eAAe,EAAE,QAAQ,EAAE,OAAO,KAAK,MAAM,EAAE;AAAA,UAC/C,QAAQ,SAAc;AAClB,mBAAO;AAAA,cACH,IAAI,QAAQ,MAAM;AAAA,cAClB,MAAM,QAAQ,QAAQ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AAA,EAEP,MAAc,aAAa;AACvB,QAAI,CAAC,KAAK,gBAAgB;AACtB,YAAM,cAAc,UAAM,gCAAU,cAAc;AAClD,UAAI,CAAC,aAAa;AACd,cAAM,IAAI,MAAM,qBAAqB;AAAA,MACzC;AACA,WAAK,iBAAiB,KAAK,MAAM,WAAW;AAAA,IAChD;AAEA,QAAI,CAAC,KAAK,QAAQ;AACd,WAAK,SAAS,KAAK,aAAa;AAAA,IACpC;AAAA,EACJ;AAAA,EAEA,MAAa,IAAI,EAAE,OAAO,SAAS,SAAS,GAIzC;AACC,UAAM,KAAK,WAAW;AACtB,SAAK,OAAO,IAAI,OAAO,SAAS,QAAQ;AAAA,EAC5C;AAAA,EAEQ,eAAe;AACnB,WAAO,eAAAC,QAAQ,aAAa;AAAA,MACxB,QAAQ;AAAA,MACR,YAAY;AAAA,QACR,IAAI,eAAAA,QAAQ,WAAW,QAAQ;AAAA,UAC3B,OAAO,KAAK,eAAe,KAAK,QAAQ;AAAA,UACxC,QAAQ,KAAK,eAAe,KAAK,QAAQ;AAAA,QAC7C,CAAC;AAAA,QACD,IAAI,gBAAgB;AAAA,UAChB,OAAO,KAAK,eAAe,KAAK,QAAQ;AAAA,UACxC,QAAQ,KAAK,eAAe,KAAK,QAAQ;AAAA,QAC7C,CAAC;AAAA,QACD,IAAI,iBAAiB;AAAA,UACjB,OAAO,KAAK,eAAe,KAAK,QAAQ;AAAA,UACxC,QAAQ,KAAK,eAAe,KAAK,QAAQ;AAAA,QAC7C,CAAC;AAAA,MACL;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;","names":["Transport","import_winston_transport","Transport","Graylog2Transport","import_next_cookies","winston"]}
@@ -0,0 +1,148 @@
1
+ // src/logger.ts
2
+ import winston from "winston";
3
+
4
+ // src/transports/matomo.ts
5
+ import Transport from "winston-transport";
6
+
7
+ // ../constants/src/index.ts
8
+ var ALL = "*";
9
+ var LOG_LEVELS = {
10
+ critical: 2,
11
+ error: 3,
12
+ warning: 4,
13
+ info: 6,
14
+ debug: 7
15
+ };
16
+ var SDK_CONFIG_KEY = "crex-sdk-config";
17
+
18
+ // src/sdk.ts
19
+ import { getCookie } from "@c-rex/utils/next-cookies";
20
+ var CrexSDK = class {
21
+ userAuthConfig;
22
+ customerConfig;
23
+ async getConfig() {
24
+ if (!this.customerConfig) {
25
+ const jsonConfigs = await getCookie(SDK_CONFIG_KEY);
26
+ if (!jsonConfigs) {
27
+ throw new Error("SDK not initialized");
28
+ }
29
+ this.customerConfig = JSON.parse(jsonConfigs);
30
+ }
31
+ }
32
+ async getUserAuthConfig() {
33
+ if (this.userAuthConfig) {
34
+ return this.userAuthConfig;
35
+ }
36
+ await this.getConfig();
37
+ const user = this.customerConfig.OIDC.user;
38
+ this.userAuthConfig = {
39
+ providers: [
40
+ {
41
+ id: "crex",
42
+ name: "CREX",
43
+ type: "oauth",
44
+ clientId: user.id,
45
+ wellKnown: user.issuer,
46
+ clientSecret: user.secret,
47
+ authorization: { params: { scope: user.scope } },
48
+ profile(profile) {
49
+ return {
50
+ id: profile.id || "fake Id",
51
+ name: profile.name || "Fake Name",
52
+ email: profile.email || "fake Email",
53
+ image: profile.image || "fake Image"
54
+ };
55
+ }
56
+ }
57
+ ]
58
+ };
59
+ return this.userAuthConfig;
60
+ }
61
+ };
62
+
63
+ // src/transports/matomo.ts
64
+ var MatomoTransport = class extends Transport {
65
+ matomoTransport;
66
+ constructor(opts) {
67
+ super(opts);
68
+ this.matomoTransport = new Transport();
69
+ }
70
+ log(info, callback) {
71
+ const SDK = CrexSDK.getInstance();
72
+ const matomoCategory = SDK.customerConfig.logs.matomo.categoriesLevel;
73
+ if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
74
+ this.matomoTransport.log(info, callback);
75
+ }
76
+ }
77
+ };
78
+
79
+ // src/transports/graylog.ts
80
+ import Transport2 from "winston-transport";
81
+ import Graylog2Transport from "winston-graylog2";
82
+ var GraylogTransport = class extends Transport2 {
83
+ graylogTransport;
84
+ constructor(opts) {
85
+ super(opts);
86
+ this.graylogTransport = new Graylog2Transport({
87
+ name: "Periotto-TEST",
88
+ silent: false,
89
+ handleExceptions: false,
90
+ graylog: {
91
+ servers: [{ host: "localhost", port: 12201 }]
92
+ }
93
+ });
94
+ }
95
+ log(info, callback) {
96
+ const SDK = CrexSDK.getInstance();
97
+ const graylogCategory = SDK.customerConfig.logs.graylog.categoriesLevel;
98
+ if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
99
+ this.graylogTransport.log(info, callback);
100
+ }
101
+ }
102
+ };
103
+
104
+ // src/logger.ts
105
+ import { getCookie as getCookie2 } from "@c-rex/utils/next-cookies";
106
+ var CrexLogger = class {
107
+ customerConfig;
108
+ logger;
109
+ async initLogger() {
110
+ if (!this.customerConfig) {
111
+ const jsonConfigs = await getCookie2(SDK_CONFIG_KEY);
112
+ if (!jsonConfigs) {
113
+ throw new Error("SDK not initialized");
114
+ }
115
+ this.customerConfig = JSON.parse(jsonConfigs);
116
+ }
117
+ if (!this.logger) {
118
+ this.logger = this.createLogger();
119
+ }
120
+ }
121
+ async log({ level, message, category }) {
122
+ await this.initLogger();
123
+ this.logger.log(level, message, category);
124
+ }
125
+ createLogger() {
126
+ return winston.createLogger({
127
+ levels: LOG_LEVELS,
128
+ transports: [
129
+ new winston.transports.Console({
130
+ level: this.customerConfig.logs.console.minimumLevel,
131
+ silent: this.customerConfig.logs.console.silent
132
+ }),
133
+ new MatomoTransport({
134
+ level: this.customerConfig.logs.console.minimumLevel,
135
+ silent: this.customerConfig.logs.console.silent
136
+ }),
137
+ new GraylogTransport({
138
+ level: this.customerConfig.logs.graylog.minimumLevel,
139
+ silent: this.customerConfig.logs.graylog.silent
140
+ })
141
+ ]
142
+ });
143
+ }
144
+ };
145
+ export {
146
+ CrexLogger
147
+ };
148
+ //# sourceMappingURL=logger.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/logger.ts","../src/transports/matomo.ts","../../constants/src/index.ts","../src/sdk.ts","../src/transports/graylog.ts"],"sourcesContent":["import winston from \"winston\";\nimport { MatomoTransport } from \"./transports/matomo\";\nimport { GraylogTransport } from \"./transports/graylog\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { LOG_LEVELS, SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { getCookie } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexLogger {\n private customerConfig!: ConfigInterface;\n public logger!: winston.Logger;\n\n private async initLogger() {\n if (!this.customerConfig) {\n const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\n }\n\n if (!this.logger) {\n this.logger = this.createLogger();\n }\n }\n\n public async log({ level, message, category }: {\n level: LogLevelType,\n message: string,\n category?: LogCategoriesType\n }) {\n await this.initLogger();\n this.logger.log(level, message, category);\n }\n\n private createLogger() {\n return winston.createLogger({\n levels: LOG_LEVELS,\n transports: [\n new winston.transports.Console({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new MatomoTransport({\n level: this.customerConfig.logs.console.minimumLevel,\n silent: this.customerConfig.logs.console.silent,\n }),\n new GraylogTransport({\n level: this.customerConfig.logs.graylog.minimumLevel,\n silent: this.customerConfig.logs.graylog.silent,\n }),\n ],\n });\n }\n}","import Transport from \"winston-transport\";\nimport { CrexSDK } from \"..\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\n\nexport class MatomoTransport extends Transport {\n public matomoTransport: any;\n\n constructor(opts: any) {\n super(opts);\n\n this.matomoTransport = new Transport();\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const SDK = CrexSDK.getInstance();\n const matomoCategory = SDK.customerConfig.logs.matomo.categoriesLevel\n\n if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {\n\n this.matomoTransport.log(info, callback);\n }\n }\n}\n","export const ALL = \"*\"\n\nexport const LOG_CATEGORIES = [\n \"NoLicense\",\n \"Scenario\",\n \"Favorites\",\n \"Subscription\",\n \"Share\",\n \"Document\",\n \"Search\",\n \"History\",\n \"Notification\",\n \"UserProfile\",\n] as const;\n\nexport const LOG_LEVELS = {\n critical: 2,\n error: 3,\n warning: 4,\n info: 6,\n debug: 7,\n} as const;\n\nexport const API = {\n MAX_RETRY: 3,\n API_TIMEOUT: 10000,\n API_HEADERS: {\n \"content-Type\": \"application/json\",\n },\n};\n\nexport const SDK_CONFIG_KEY = \"crex-sdk-config\";\n\nexport const CONTENT_LANG_KEY = \"CONTENT_LANG_KEY\";\n\nexport const UI_LANG_KEY = \"UI_LANG_KEY\";\n\nexport const FLAGS_BY_LANG = {\n \"en\": \"US\",\n \"de\": \"DE\",\n};\n\nexport const DEFAULT_UI_LANG = \"en\";\nexport const UI_LANG_OPTIONS = [\"en\", \"de\"];","import { SDK_CONFIG_KEY } from \"@c-rex/constants\";\nimport { ConfigInterface } from \"@c-rex/interfaces\";\nimport { getCookie } from \"@c-rex/utils/next-cookies\";\n\nexport class CrexSDK {\n public userAuthConfig!: any;\n public customerConfig!: ConfigInterface;\n\n private async getConfig() {\n if (!this.customerConfig) {\n const jsonConfigs = await getCookie(SDK_CONFIG_KEY);\n if (!jsonConfigs) {\n throw new Error(\"SDK not initialized\");\n }\n this.customerConfig = JSON.parse(jsonConfigs) as ConfigInterface;\n }\n }\n\n public async getUserAuthConfig() {\n if (this.userAuthConfig) {\n return this.userAuthConfig;\n }\n\n await this.getConfig();\n\n const user = this.customerConfig.OIDC.user;\n\n this.userAuthConfig = {\n providers: [\n {\n id: \"crex\",\n name: \"CREX\",\n type: \"oauth\",\n clientId: user.id,\n wellKnown: user.issuer,\n clientSecret: user.secret,\n authorization: { params: { scope: user.scope } },\n profile(profile: any) {\n return {\n id: profile.id || \"fake Id\",\n name: profile.name || \"Fake Name\",\n email: profile.email || \"fake Email\",\n image: profile.image || \"fake Image\",\n }\n },\n },\n ]\n };\n\n return this.userAuthConfig;\n }\n}","import Transport from \"winston-transport\";\nimport Graylog2Transport from \"winston-graylog2\";\nimport { CrexSDK } from \"..\";\nimport { LogCategoriesType, LogLevelType } from \"@c-rex/types\";\nimport { ALL } from \"@c-rex/constants\";\n\nexport class GraylogTransport extends Transport {\n public graylogTransport: any;\n\n constructor(opts: any) {\n super(opts);\n\n this.graylogTransport = new Graylog2Transport({\n name: \"Periotto-TEST\",\n silent: false,\n handleExceptions: false,\n graylog: {\n servers: [{ host: \"localhost\", port: 12201 }],\n },\n });\n }\n\n log(\n info: { level: LogLevelType, message: string, category: LogCategoriesType },\n callback: () => void,\n ): void {\n const SDK = CrexSDK.getInstance();\n const graylogCategory = SDK.customerConfig.logs.graylog.categoriesLevel\n\n if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {\n this.graylogTransport.log(info, callback);\n }\n }\n}\n"],"mappings":";AAAA,OAAO,aAAa;;;ACApB,OAAO,eAAe;;;ACAf,IAAM,MAAM;AAeZ,IAAM,aAAa;AAAA,EACtB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,MAAM;AAAA,EACN,OAAO;AACX;AAUO,IAAM,iBAAiB;;;AC7B9B,SAAS,iBAAiB;AAEnB,IAAM,UAAN,MAAc;AAAA,EACV;AAAA,EACA;AAAA,EAEP,MAAc,YAAY;AACtB,QAAI,CAAC,KAAK,gBAAgB;AACtB,YAAM,cAAc,MAAM,UAAU,cAAc;AAClD,UAAI,CAAC,aAAa;AACd,cAAM,IAAI,MAAM,qBAAqB;AAAA,MACzC;AACA,WAAK,iBAAiB,KAAK,MAAM,WAAW;AAAA,IAChD;AAAA,EACJ;AAAA,EAEA,MAAa,oBAAoB;AAC7B,QAAI,KAAK,gBAAgB;AACrB,aAAO,KAAK;AAAA,IAChB;AAEA,UAAM,KAAK,UAAU;AAErB,UAAM,OA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Q;AAAA,QAC7C,CAAC;AAAA,MACL;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;","names":["Transport","Transport","getCookie"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c-rex/core",
3
- "version": "0.0.8",
3
+ "version": "0.1.0",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",
@@ -18,15 +18,17 @@
18
18
  "default": "./dist/index.js"
19
19
  },
20
20
  "./package.json": "./package.json",
21
- "./logger.server": {
22
- "import": "./dist/logger.server.mjs",
23
- "require": "./dist/logger.server.cjs"
21
+ "./logger": {
22
+ "types": "./dist/logger.d.ts",
23
+ "import": "./dist/logger.mjs",
24
+ "require": "./dist/logger.js",
25
+ "default": "./dist/logger.js"
24
26
  }
25
27
  },
26
28
  "sideEffects": false,
27
29
  "scripts": {
28
- "dev": "tsup src/index.ts --splitting --format cjs,esm --dts --watch",
29
- "build": "tsup src/index.ts --splitting --format cjs,esm --dts",
30
+ "dev": "tsup --watch",
31
+ "build": "tsup",
30
32
  "test:watch": "jest --watch",
31
33
  "test": "jest"
32
34
  },