@c-rex/services 0.1.13 → 0.1.14

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.mjs CHANGED
@@ -1,16 +1,7 @@
1
- // ../core/src/requests.ts
2
- import axios from "axios";
1
+ // src/baseService.ts
2
+ import { CrexApi } from "@c-rex/core/requests";
3
3
 
4
4
  // ../constants/src/index.ts
5
- var ALL = "*";
6
- var LOG_LEVELS = {
7
- critical: 2,
8
- error: 3,
9
- warning: 4,
10
- info: 6,
11
- debug: 7
12
- };
13
- var SDK_CONFIG_KEY = "crex-sdk-config";
14
5
  var CONTENT_LANG_KEY = "CONTENT_LANG_KEY";
15
6
  var UI_LANG_KEY = "UI_LANG_KEY";
16
7
  var FLAGS_BY_LANG = {
@@ -29,7 +20,6 @@ var RESULT_TYPES = {
29
20
  FRAGMENT
30
21
  };
31
22
  var DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1e3;
32
- var CREX_TOKEN_HEADER_KEY = "crex-token";
33
23
  var WILD_CARD_OPTIONS = {
34
24
  BOTH: "BOTH",
35
25
  END: "END",
@@ -41,280 +31,6 @@ var OPERATOR_OPTIONS = {
41
31
  OR: "OR"
42
32
  };
43
33
 
44
- // ../core/src/requests.ts
45
- import { cookies as cookies2 } from "next/headers";
46
-
47
- // ../core/src/logger.ts
48
- import winston from "winston";
49
-
50
- // ../core/src/transports/matomo.ts
51
- import Transport from "winston-transport";
52
- var MatomoTransport = class extends Transport {
53
- matomoTransport;
54
- configs;
55
- /**
56
- * Creates a new instance of MatomoTransport.
57
- *
58
- * @param configs - The application configuration containing logging settings
59
- */
60
- constructor(configs) {
61
- super({
62
- level: configs.logs.matomo.minimumLevel,
63
- silent: configs.logs.matomo.silent
64
- });
65
- this.matomoTransport = new Transport();
66
- this.configs = configs;
67
- }
68
- /**
69
- * Logs a message to Matomo if the message category is included in the configured categories.
70
- *
71
- * @param info - The log information including level, message, and category
72
- * @param callback - Callback function to execute after logging
73
- */
74
- log(info, callback) {
75
- const matomoCategory = this.configs.logs.matomo.categoriesLevel;
76
- if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
77
- this.matomoTransport.log(info, callback);
78
- }
79
- }
80
- };
81
-
82
- // ../core/src/transports/graylog.ts
83
- import Transport2 from "winston-transport";
84
- import Graylog2Transport from "winston-graylog2";
85
- var GraylogTransport = class extends Transport2 {
86
- graylogTransport;
87
- configs;
88
- /**
89
- * Creates a new instance of GraylogTransport.
90
- *
91
- * @param configs - The application configuration containing logging settings
92
- */
93
- constructor(configs) {
94
- if (!configs.logs.graylog.hostname || configs.logs.graylog.port === void 0) {
95
- throw new Error("Graylog hostname and port must be defined");
96
- }
97
- super({
98
- level: configs.logs.graylog.minimumLevel,
99
- silent: configs.logs.graylog.silent
100
- });
101
- this.configs = configs;
102
- this.graylogTransport = new Graylog2Transport({
103
- name: configs.logs.graylog.app,
104
- silent: configs.logs.graylog.silent,
105
- handleExceptions: false,
106
- graylog: {
107
- servers: [
108
- { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }
109
- ]
110
- }
111
- });
112
- }
113
- /**
114
- * Logs a message to Graylog if the message category is included in the configured categories.
115
- *
116
- * @param info - The log information including level, message, and category
117
- * @param callback - Callback function to execute after logging
118
- */
119
- log(info, callback) {
120
- const graylogCategory = this.configs.logs.graylog.categoriesLevel;
121
- if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
122
- this.graylogTransport.log(info, callback);
123
- }
124
- }
125
- };
126
-
127
- // ../core/src/config.ts
128
- import { cookies } from "next/headers";
129
- var getClientConfig = () => {
130
- const jsonConfigs = cookies().get(SDK_CONFIG_KEY)?.value;
131
- if (!jsonConfigs) {
132
- throw new Error("Configs not found");
133
- }
134
- const configs = JSON.parse(jsonConfigs);
135
- return configs;
136
- };
137
- function getServerConfig() {
138
- if (!global.__GLOBAL_CONFIG__) {
139
- throw new Error("Server config not initialized");
140
- }
141
- return global.__GLOBAL_CONFIG__;
142
- }
143
-
144
- // ../core/src/logger.ts
145
- var CrexLogger = class {
146
- customerConfig;
147
- logger;
148
- /**
149
- * Initializes the logger instance if it hasn't been initialized yet.
150
- * Loads customer configuration and creates the logger with appropriate transports.
151
- *
152
- * @private
153
- */
154
- async initLogger() {
155
- try {
156
- if (!this.customerConfig) {
157
- this.customerConfig = getServerConfig();
158
- }
159
- if (!this.logger) {
160
- this.logger = this.createLogger();
161
- }
162
- } catch (error) {
163
- console.log("Error initializing logger:", error);
164
- }
165
- }
166
- /**
167
- * Logs a message with the specified level and optional category.
168
- *
169
- * @param options - Logging options
170
- * @param options.level - The log level (error, warn, info, etc.)
171
- * @param options.message - The message to log
172
- * @param options.category - Optional category for the log message
173
- */
174
- async log({ level, message, category }) {
175
- await this.initLogger();
176
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
177
- const newMessage = `[${timestamp}] ${message}`;
178
- this.logger.log(level, newMessage, category);
179
- }
180
- /**
181
- * Creates a new Winston logger instance with configured transports.
182
- *
183
- * @private
184
- * @returns A configured Winston logger instance
185
- */
186
- createLogger() {
187
- return winston.createLogger({
188
- levels: LOG_LEVELS,
189
- transports: [
190
- new winston.transports.Console({
191
- level: this.customerConfig.logs.console.minimumLevel,
192
- silent: this.customerConfig.logs.console.silent
193
- }),
194
- new MatomoTransport(this.customerConfig),
195
- new GraylogTransport(this.customerConfig)
196
- ]
197
- });
198
- }
199
- };
200
-
201
- // ../core/src/OIDC.ts
202
- import { Issuer } from "openid-client";
203
- var getToken = async () => {
204
- try {
205
- const config = getServerConfig();
206
- const issuer = await Issuer.discover(config.OIDC.client.issuer);
207
- const client = new issuer.Client({
208
- client_id: config.OIDC.client.id,
209
- client_secret: config.OIDC.client.secret
210
- });
211
- const tokenSet = await client.grant({ grant_type: "client_credentials" });
212
- const token = tokenSet.access_token;
213
- const expiresAt = tokenSet.expires_at;
214
- return { token, expiresAt };
215
- } catch (error) {
216
- const logger = new CrexLogger();
217
- logger.log({
218
- level: "error",
219
- message: `getToken error: ${error}`
220
- });
221
- return { token: "", expiresAt: 0, error: JSON.stringify(error) };
222
- }
223
- };
224
-
225
- // ../core/src/requests.ts
226
- var CrexApi = class {
227
- customerConfig;
228
- apiClient;
229
- logger;
230
- /**
231
- * Initializes the API client if it hasn't been initialized yet.
232
- * Loads customer configuration, creates the axios instance, and initializes the logger.
233
- *
234
- * @private
235
- */
236
- async initAPI() {
237
- this.logger = new CrexLogger();
238
- if (!this.customerConfig) {
239
- this.customerConfig = getServerConfig();
240
- }
241
- if (!this.apiClient) {
242
- this.apiClient = axios.create({
243
- baseURL: this.customerConfig.baseUrl
244
- });
245
- }
246
- }
247
- async manageToken() {
248
- try {
249
- let token = "";
250
- const hasToken = cookies2().get(CREX_TOKEN_HEADER_KEY);
251
- if (hasToken == void 0 || hasToken.value === null) {
252
- const { token: tokenResult } = await getToken();
253
- if (tokenResult.length === 0) throw new Error("Token is undefined");
254
- token = tokenResult;
255
- } else {
256
- token = hasToken.value;
257
- }
258
- return token;
259
- } catch (error) {
260
- this.logger.log({
261
- level: "error",
262
- message: `CrexAPI.manageToken error: ${error}`
263
- });
264
- throw error;
265
- }
266
- }
267
- /**
268
- * Executes an API request with caching, authentication, and retry logic.
269
- *
270
- * @param options - Request options
271
- * @param options.url - The URL to request
272
- * @param options.method - The HTTP method to use
273
- * @param options.params - Optional query parameters
274
- * @param options.body - Optional request body
275
- * @param options.headers - Optional request headers
276
- * @returns The response data
277
- * @throws Error if the request fails after maximum retries
278
- */
279
- async execute({
280
- url,
281
- method,
282
- params,
283
- body,
284
- headers = {}
285
- }) {
286
- try {
287
- await this.initAPI();
288
- let response = void 0;
289
- if (this.customerConfig.OIDC.client.enabled) {
290
- const token = await this.manageToken();
291
- headers = {
292
- ...headers,
293
- Authorization: `Bearer ${token}`
294
- };
295
- this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
296
- }
297
- response = await this.apiClient.request({
298
- url,
299
- method,
300
- data: body,
301
- params,
302
- headers
303
- });
304
- if (response) {
305
- return response.data;
306
- }
307
- throw new Error("API.execute error: Failed to retrieve a valid response");
308
- } catch (error) {
309
- this.logger.log({
310
- level: "error",
311
- message: `CrexAPI.execute error: ${error}`
312
- });
313
- throw error;
314
- }
315
- }
316
- };
317
-
318
34
  // ../utils/src/utils.ts
319
35
  var getCountryCodeByLang = (lang) => {
320
36
  const mappedKeys = Object.keys(FLAGS_BY_LANG);
@@ -497,11 +213,13 @@ var DirectoryNodesService = class extends BaseService {
497
213
  };
498
214
 
499
215
  // src/transforms/documentTypes.ts
500
- import { cookies as cookies3 } from "next/headers";
216
+ import { CrexSDK } from "@c-rex/core/sdk";
217
+ import { cookies } from "next/headers";
501
218
  var transformDocumentTypes = async (data) => {
502
219
  const labels = [];
503
- const config = getClientConfig();
504
- const contentLanguage = cookies3().get(CONTENT_LANG_KEY)?.value || config.languageSwitcher.default;
220
+ const sdk = new CrexSDK();
221
+ const config = sdk.getClientConfig();
222
+ const contentLanguage = cookies().get(CONTENT_LANG_KEY)?.value || config.languageSwitcher.default;
505
223
  const language = contentLanguage.split("-")[0];
506
224
  data.items.forEach((documentItem) => {
507
225
  const label = documentItem.labels.find((item) => item.language.toLowerCase() === language.toLowerCase());
@@ -536,12 +254,14 @@ var DocumentTypesService = class extends BaseService {
536
254
  };
537
255
 
538
256
  // src/transforms/information.ts
539
- import { cookies as cookies4 } from "next/headers";
540
- import { CrexLogger as CrexLogger2 } from "@c-rex/core/logger";
257
+ import { cookies as cookies2 } from "next/headers";
258
+ import { CrexLogger } from "@c-rex/core/logger";
259
+ import { CrexSDK as CrexSDK2 } from "@c-rex/core/sdk";
541
260
  var transformInformationUnits = async (data) => {
542
- const logger = new CrexLogger2();
543
- const frontEndConfig = getClientConfig();
544
- const backEndConfig = getServerConfig();
261
+ const logger = new CrexLogger();
262
+ const sdk = new CrexSDK2();
263
+ const frontEndConfig = sdk.getClientConfig();
264
+ const backEndConfig = sdk.getServerConfig();
545
265
  const filteredTags = {};
546
266
  const items = data.items.map((item) => {
547
267
  const type = item.class.labels.filter((item2) => item2.language === EN_LANG)[0].value.toUpperCase();
@@ -580,7 +300,7 @@ var transformInformationUnits = async (data) => {
580
300
  };
581
301
  });
582
302
  if (data.tags) {
583
- const contentLang = (cookies4().get(CONTENT_LANG_KEY)?.value || EN_LANG).toLowerCase();
303
+ const contentLang = (cookies2().get(CONTENT_LANG_KEY)?.value || EN_LANG).toLowerCase();
584
304
  const splittedContentLang = contentLang.split("-")[0];
585
305
  for (const [key, value] of Object.entries(data.tags)) {
586
306
  if (!value || !value.items || value.items.length === 0) {
@@ -650,10 +370,8 @@ var transformSuggestions = (data, query) => {
650
370
 
651
371
  // src/informationUnits.ts
652
372
  var InformationUnitsService = class extends BaseService {
653
- directoryNodesService;
654
- constructor(directoryNodesService) {
373
+ constructor() {
655
374
  super("InformationUnits/");
656
- this.directoryNodesService = directoryNodesService || new DirectoryNodesService();
657
375
  }
658
376
  /**
659
377
  * Retrieves a list of information units based on specified criteria.
@@ -756,39 +474,14 @@ var InformationUnitsService = class extends BaseService {
756
474
  transformer: (data) => transformSuggestions(data, query)
757
475
  });
758
476
  }
759
- async getDocumentInfo({ shortId }) {
760
- const response = await this.getItem({
761
- id: shortId,
762
- shouldGetAllFields: true
763
- });
764
- const directoryNodes = response.directoryNodes;
765
- if (directoryNodes.length === 0 || !directoryNodes[0]) {
766
- return {};
767
- }
768
- let id = directoryNodes[0].shortId;
769
- let node = await this.directoryNodesService.getItem(id);
770
- if (!node.ancestors || node.ancestors.length === 0) return {};
771
- const hasInfo = node.informationUnits?.[0];
772
- const hasLabel = node.labels?.[0];
773
- if (!hasInfo || !hasLabel) return {};
774
- const lastIndex = node.ancestors[0]?.length - 1;
775
- const ancestorNode = node.ancestors[0][lastIndex];
776
- if (!ancestorNode?.shortId) return {};
777
- id = ancestorNode.shortId;
778
- node = await this.directoryNodesService.getItem(id);
779
- const ancestorInfoUnit = node.informationUnits?.[0];
780
- const ancestorLabel = ancestorInfoUnit?.labels?.[0];
781
- return {
782
- documentId: ancestorInfoUnit?.shortId,
783
- label: ancestorLabel?.value || ""
784
- };
785
- }
786
477
  };
787
478
 
788
479
  // src/language.ts
480
+ import { CrexSDK as CrexSDK3 } from "@c-rex/core/sdk";
789
481
  var LanguageService = class extends BaseService {
790
482
  constructor() {
791
- const configs = getClientConfig();
483
+ const sdk = new CrexSDK3();
484
+ const configs = sdk.getClientConfig();
792
485
  super(configs.languageSwitcher.endpoint);
793
486
  }
794
487
  /**
@@ -825,12 +518,14 @@ var LanguageService = class extends BaseService {
825
518
  };
826
519
 
827
520
  // src/transforms/topics.ts
828
- import { cookies as cookies5 } from "next/headers";
829
- import { CrexLogger as CrexLogger3 } from "@c-rex/core/logger";
521
+ import { cookies as cookies3 } from "next/headers";
522
+ import { CrexLogger as CrexLogger2 } from "@c-rex/core/logger";
523
+ import { CrexSDK as CrexSDK4 } from "@c-rex/core/sdk";
830
524
  var transformTopics = async (data) => {
831
- const logger = new CrexLogger3();
832
- const config = getClientConfig();
833
- const uiLang = (cookies5().get(UI_LANG_KEY)?.value || config.languageSwitcher.default).toLowerCase();
525
+ const logger = new CrexLogger2();
526
+ const sdk = new CrexSDK4();
527
+ const config = sdk.getClientConfig();
528
+ const uiLang = (cookies3().get(UI_LANG_KEY)?.value || config.languageSwitcher.default).toLowerCase();
834
529
  const items = data.items.map((item) => {
835
530
  const type = item.class.labels.filter((item2) => item2.language === EN_LANG)[0].value.toUpperCase();
836
531
  let link = `/topics/${item.shortId}`;