@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.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { CrexApi } from '@c-rex/core';
1
+ import { CrexApi } from '@c-rex/core/requests';
2
2
  import { Method } from 'axios';
3
3
  import { informationUnitsRenditions, DirectoryNodes, DirectoryNodesResponse, informationUnitsResponse, informationUnitsItems, LanguageAndCountries, DefaultResponse, TopicsResponseItem } from '@c-rex/interfaces';
4
4
 
@@ -122,8 +122,7 @@ declare class DocumentTypesService extends BaseService {
122
122
  * Provides methods to retrieve and search information units.
123
123
  */
124
124
  declare class InformationUnitsService extends BaseService {
125
- private directoryNodesService;
126
- constructor(directoryNodesService?: DirectoryNodesService);
125
+ constructor();
127
126
  /**
128
127
  * Retrieves a list of information units based on specified criteria.
129
128
  *
@@ -174,12 +173,6 @@ declare class InformationUnitsService extends BaseService {
174
173
  query: string;
175
174
  language: string;
176
175
  }): Promise<string[]>;
177
- getDocumentInfo({ shortId }: {
178
- shortId: string;
179
- }): Promise<{
180
- documentId?: string;
181
- label?: string;
182
- }>;
183
176
  }
184
177
 
185
178
  /**
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { CrexApi } from '@c-rex/core';
1
+ import { CrexApi } from '@c-rex/core/requests';
2
2
  import { Method } from 'axios';
3
3
  import { informationUnitsRenditions, DirectoryNodes, DirectoryNodesResponse, informationUnitsResponse, informationUnitsItems, LanguageAndCountries, DefaultResponse, TopicsResponseItem } from '@c-rex/interfaces';
4
4
 
@@ -122,8 +122,7 @@ declare class DocumentTypesService extends BaseService {
122
122
  * Provides methods to retrieve and search information units.
123
123
  */
124
124
  declare class InformationUnitsService extends BaseService {
125
- private directoryNodesService;
126
- constructor(directoryNodesService?: DirectoryNodesService);
125
+ constructor();
127
126
  /**
128
127
  * Retrieves a list of information units based on specified criteria.
129
128
  *
@@ -174,12 +173,6 @@ declare class InformationUnitsService extends BaseService {
174
173
  query: string;
175
174
  language: string;
176
175
  }): Promise<string[]>;
177
- getDocumentInfo({ shortId }: {
178
- shortId: string;
179
- }): Promise<{
180
- documentId?: string;
181
- label?: string;
182
- }>;
183
176
  }
184
177
 
185
178
  /**
package/dist/index.js CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
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
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
@@ -39,19 +29,10 @@ __export(index_exports, {
39
29
  });
40
30
  module.exports = __toCommonJS(index_exports);
41
31
 
42
- // ../core/src/requests.ts
43
- var import_axios = __toESM(require("axios"));
32
+ // src/baseService.ts
33
+ var import_requests = require("@c-rex/core/requests");
44
34
 
45
35
  // ../constants/src/index.ts
46
- var ALL = "*";
47
- var LOG_LEVELS = {
48
- critical: 2,
49
- error: 3,
50
- warning: 4,
51
- info: 6,
52
- debug: 7
53
- };
54
- var SDK_CONFIG_KEY = "crex-sdk-config";
55
36
  var CONTENT_LANG_KEY = "CONTENT_LANG_KEY";
56
37
  var UI_LANG_KEY = "UI_LANG_KEY";
57
38
  var FLAGS_BY_LANG = {
@@ -70,7 +51,6 @@ var RESULT_TYPES = {
70
51
  FRAGMENT
71
52
  };
72
53
  var DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1e3;
73
- var CREX_TOKEN_HEADER_KEY = "crex-token";
74
54
  var WILD_CARD_OPTIONS = {
75
55
  BOTH: "BOTH",
76
56
  END: "END",
@@ -82,280 +62,6 @@ var OPERATOR_OPTIONS = {
82
62
  OR: "OR"
83
63
  };
84
64
 
85
- // ../core/src/requests.ts
86
- var import_headers2 = require("next/headers");
87
-
88
- // ../core/src/logger.ts
89
- var import_winston = __toESM(require("winston"));
90
-
91
- // ../core/src/transports/matomo.ts
92
- var import_winston_transport = __toESM(require("winston-transport"));
93
- var MatomoTransport = class extends import_winston_transport.default {
94
- matomoTransport;
95
- configs;
96
- /**
97
- * Creates a new instance of MatomoTransport.
98
- *
99
- * @param configs - The application configuration containing logging settings
100
- */
101
- constructor(configs) {
102
- super({
103
- level: configs.logs.matomo.minimumLevel,
104
- silent: configs.logs.matomo.silent
105
- });
106
- this.matomoTransport = new import_winston_transport.default();
107
- this.configs = configs;
108
- }
109
- /**
110
- * Logs a message to Matomo if the message category is included in the configured categories.
111
- *
112
- * @param info - The log information including level, message, and category
113
- * @param callback - Callback function to execute after logging
114
- */
115
- log(info, callback) {
116
- const matomoCategory = this.configs.logs.matomo.categoriesLevel;
117
- if (matomoCategory.includes(info.category) || matomoCategory.includes(ALL)) {
118
- this.matomoTransport.log(info, callback);
119
- }
120
- }
121
- };
122
-
123
- // ../core/src/transports/graylog.ts
124
- var import_winston_transport2 = __toESM(require("winston-transport"));
125
- var import_winston_graylog2 = __toESM(require("winston-graylog2"));
126
- var GraylogTransport = class extends import_winston_transport2.default {
127
- graylogTransport;
128
- configs;
129
- /**
130
- * Creates a new instance of GraylogTransport.
131
- *
132
- * @param configs - The application configuration containing logging settings
133
- */
134
- constructor(configs) {
135
- if (!configs.logs.graylog.hostname || configs.logs.graylog.port === void 0) {
136
- throw new Error("Graylog hostname and port must be defined");
137
- }
138
- super({
139
- level: configs.logs.graylog.minimumLevel,
140
- silent: configs.logs.graylog.silent
141
- });
142
- this.configs = configs;
143
- this.graylogTransport = new import_winston_graylog2.default({
144
- name: configs.logs.graylog.app,
145
- silent: configs.logs.graylog.silent,
146
- handleExceptions: false,
147
- graylog: {
148
- servers: [
149
- { host: configs.logs.graylog.hostname, port: configs.logs.graylog.port }
150
- ]
151
- }
152
- });
153
- }
154
- /**
155
- * Logs a message to Graylog if the message category is included in the configured categories.
156
- *
157
- * @param info - The log information including level, message, and category
158
- * @param callback - Callback function to execute after logging
159
- */
160
- log(info, callback) {
161
- const graylogCategory = this.configs.logs.graylog.categoriesLevel;
162
- if (graylogCategory.includes(info.category) || graylogCategory.includes(ALL)) {
163
- this.graylogTransport.log(info, callback);
164
- }
165
- }
166
- };
167
-
168
- // ../core/src/config.ts
169
- var import_headers = require("next/headers");
170
- var getClientConfig = () => {
171
- const jsonConfigs = (0, import_headers.cookies)().get(SDK_CONFIG_KEY)?.value;
172
- if (!jsonConfigs) {
173
- throw new Error("Configs not found");
174
- }
175
- const configs = JSON.parse(jsonConfigs);
176
- return configs;
177
- };
178
- function getServerConfig() {
179
- if (!global.__GLOBAL_CONFIG__) {
180
- throw new Error("Server config not initialized");
181
- }
182
- return global.__GLOBAL_CONFIG__;
183
- }
184
-
185
- // ../core/src/logger.ts
186
- var CrexLogger = class {
187
- customerConfig;
188
- logger;
189
- /**
190
- * Initializes the logger instance if it hasn't been initialized yet.
191
- * Loads customer configuration and creates the logger with appropriate transports.
192
- *
193
- * @private
194
- */
195
- async initLogger() {
196
- try {
197
- if (!this.customerConfig) {
198
- this.customerConfig = getServerConfig();
199
- }
200
- if (!this.logger) {
201
- this.logger = this.createLogger();
202
- }
203
- } catch (error) {
204
- console.log("Error initializing logger:", error);
205
- }
206
- }
207
- /**
208
- * Logs a message with the specified level and optional category.
209
- *
210
- * @param options - Logging options
211
- * @param options.level - The log level (error, warn, info, etc.)
212
- * @param options.message - The message to log
213
- * @param options.category - Optional category for the log message
214
- */
215
- async log({ level, message, category }) {
216
- await this.initLogger();
217
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
218
- const newMessage = `[${timestamp}] ${message}`;
219
- this.logger.log(level, newMessage, category);
220
- }
221
- /**
222
- * Creates a new Winston logger instance with configured transports.
223
- *
224
- * @private
225
- * @returns A configured Winston logger instance
226
- */
227
- createLogger() {
228
- return import_winston.default.createLogger({
229
- levels: LOG_LEVELS,
230
- transports: [
231
- new import_winston.default.transports.Console({
232
- level: this.customerConfig.logs.console.minimumLevel,
233
- silent: this.customerConfig.logs.console.silent
234
- }),
235
- new MatomoTransport(this.customerConfig),
236
- new GraylogTransport(this.customerConfig)
237
- ]
238
- });
239
- }
240
- };
241
-
242
- // ../core/src/OIDC.ts
243
- var import_openid_client = require("openid-client");
244
- var getToken = async () => {
245
- try {
246
- const config = getServerConfig();
247
- const issuer = await import_openid_client.Issuer.discover(config.OIDC.client.issuer);
248
- const client = new issuer.Client({
249
- client_id: config.OIDC.client.id,
250
- client_secret: config.OIDC.client.secret
251
- });
252
- const tokenSet = await client.grant({ grant_type: "client_credentials" });
253
- const token = tokenSet.access_token;
254
- const expiresAt = tokenSet.expires_at;
255
- return { token, expiresAt };
256
- } catch (error) {
257
- const logger = new CrexLogger();
258
- logger.log({
259
- level: "error",
260
- message: `getToken error: ${error}`
261
- });
262
- return { token: "", expiresAt: 0, error: JSON.stringify(error) };
263
- }
264
- };
265
-
266
- // ../core/src/requests.ts
267
- var CrexApi = class {
268
- customerConfig;
269
- apiClient;
270
- logger;
271
- /**
272
- * Initializes the API client if it hasn't been initialized yet.
273
- * Loads customer configuration, creates the axios instance, and initializes the logger.
274
- *
275
- * @private
276
- */
277
- async initAPI() {
278
- this.logger = new CrexLogger();
279
- if (!this.customerConfig) {
280
- this.customerConfig = getServerConfig();
281
- }
282
- if (!this.apiClient) {
283
- this.apiClient = import_axios.default.create({
284
- baseURL: this.customerConfig.baseUrl
285
- });
286
- }
287
- }
288
- async manageToken() {
289
- try {
290
- let token = "";
291
- const hasToken = (0, import_headers2.cookies)().get(CREX_TOKEN_HEADER_KEY);
292
- if (hasToken == void 0 || hasToken.value === null) {
293
- const { token: tokenResult } = await getToken();
294
- if (tokenResult.length === 0) throw new Error("Token is undefined");
295
- token = tokenResult;
296
- } else {
297
- token = hasToken.value;
298
- }
299
- return token;
300
- } catch (error) {
301
- this.logger.log({
302
- level: "error",
303
- message: `CrexAPI.manageToken error: ${error}`
304
- });
305
- throw error;
306
- }
307
- }
308
- /**
309
- * Executes an API request with caching, authentication, and retry logic.
310
- *
311
- * @param options - Request options
312
- * @param options.url - The URL to request
313
- * @param options.method - The HTTP method to use
314
- * @param options.params - Optional query parameters
315
- * @param options.body - Optional request body
316
- * @param options.headers - Optional request headers
317
- * @returns The response data
318
- * @throws Error if the request fails after maximum retries
319
- */
320
- async execute({
321
- url,
322
- method,
323
- params,
324
- body,
325
- headers = {}
326
- }) {
327
- try {
328
- await this.initAPI();
329
- let response = void 0;
330
- if (this.customerConfig.OIDC.client.enabled) {
331
- const token = await this.manageToken();
332
- headers = {
333
- ...headers,
334
- Authorization: `Bearer ${token}`
335
- };
336
- this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
337
- }
338
- response = await this.apiClient.request({
339
- url,
340
- method,
341
- data: body,
342
- params,
343
- headers
344
- });
345
- if (response) {
346
- return response.data;
347
- }
348
- throw new Error("API.execute error: Failed to retrieve a valid response");
349
- } catch (error) {
350
- this.logger.log({
351
- level: "error",
352
- message: `CrexAPI.execute error: ${error}`
353
- });
354
- throw error;
355
- }
356
- }
357
- };
358
-
359
65
  // ../utils/src/utils.ts
360
66
  var getCountryCodeByLang = (lang) => {
361
67
  const mappedKeys = Object.keys(FLAGS_BY_LANG);
@@ -432,7 +138,7 @@ var BaseService = class {
432
138
  * @param endpoint - The API endpoint URL for this service
433
139
  */
434
140
  constructor(endpoint) {
435
- this.api = new CrexApi();
141
+ this.api = new import_requests.CrexApi();
436
142
  this.endpoint = endpoint;
437
143
  }
438
144
  /**
@@ -538,11 +244,13 @@ var DirectoryNodesService = class extends BaseService {
538
244
  };
539
245
 
540
246
  // src/transforms/documentTypes.ts
541
- var import_headers3 = require("next/headers");
247
+ var import_sdk = require("@c-rex/core/sdk");
248
+ var import_headers = require("next/headers");
542
249
  var transformDocumentTypes = async (data) => {
543
250
  const labels = [];
544
- const config = getClientConfig();
545
- const contentLanguage = (0, import_headers3.cookies)().get(CONTENT_LANG_KEY)?.value || config.languageSwitcher.default;
251
+ const sdk = new import_sdk.CrexSDK();
252
+ const config = sdk.getClientConfig();
253
+ const contentLanguage = (0, import_headers.cookies)().get(CONTENT_LANG_KEY)?.value || config.languageSwitcher.default;
546
254
  const language = contentLanguage.split("-")[0];
547
255
  data.items.forEach((documentItem) => {
548
256
  const label = documentItem.labels.find((item) => item.language.toLowerCase() === language.toLowerCase());
@@ -577,12 +285,14 @@ var DocumentTypesService = class extends BaseService {
577
285
  };
578
286
 
579
287
  // src/transforms/information.ts
580
- var import_headers4 = require("next/headers");
581
- var import_logger3 = require("@c-rex/core/logger");
288
+ var import_headers2 = require("next/headers");
289
+ var import_logger = require("@c-rex/core/logger");
290
+ var import_sdk2 = require("@c-rex/core/sdk");
582
291
  var transformInformationUnits = async (data) => {
583
- const logger = new import_logger3.CrexLogger();
584
- const frontEndConfig = getClientConfig();
585
- const backEndConfig = getServerConfig();
292
+ const logger = new import_logger.CrexLogger();
293
+ const sdk = new import_sdk2.CrexSDK();
294
+ const frontEndConfig = sdk.getClientConfig();
295
+ const backEndConfig = sdk.getServerConfig();
586
296
  const filteredTags = {};
587
297
  const items = data.items.map((item) => {
588
298
  const type = item.class.labels.filter((item2) => item2.language === EN_LANG)[0].value.toUpperCase();
@@ -621,7 +331,7 @@ var transformInformationUnits = async (data) => {
621
331
  };
622
332
  });
623
333
  if (data.tags) {
624
- const contentLang = ((0, import_headers4.cookies)().get(CONTENT_LANG_KEY)?.value || EN_LANG).toLowerCase();
334
+ const contentLang = ((0, import_headers2.cookies)().get(CONTENT_LANG_KEY)?.value || EN_LANG).toLowerCase();
625
335
  const splittedContentLang = contentLang.split("-")[0];
626
336
  for (const [key, value] of Object.entries(data.tags)) {
627
337
  if (!value || !value.items || value.items.length === 0) {
@@ -691,10 +401,8 @@ var transformSuggestions = (data, query) => {
691
401
 
692
402
  // src/informationUnits.ts
693
403
  var InformationUnitsService = class extends BaseService {
694
- directoryNodesService;
695
- constructor(directoryNodesService) {
404
+ constructor() {
696
405
  super("InformationUnits/");
697
- this.directoryNodesService = directoryNodesService || new DirectoryNodesService();
698
406
  }
699
407
  /**
700
408
  * Retrieves a list of information units based on specified criteria.
@@ -797,39 +505,14 @@ var InformationUnitsService = class extends BaseService {
797
505
  transformer: (data) => transformSuggestions(data, query)
798
506
  });
799
507
  }
800
- async getDocumentInfo({ shortId }) {
801
- const response = await this.getItem({
802
- id: shortId,
803
- shouldGetAllFields: true
804
- });
805
- const directoryNodes = response.directoryNodes;
806
- if (directoryNodes.length === 0 || !directoryNodes[0]) {
807
- return {};
808
- }
809
- let id = directoryNodes[0].shortId;
810
- let node = await this.directoryNodesService.getItem(id);
811
- if (!node.ancestors || node.ancestors.length === 0) return {};
812
- const hasInfo = node.informationUnits?.[0];
813
- const hasLabel = node.labels?.[0];
814
- if (!hasInfo || !hasLabel) return {};
815
- const lastIndex = node.ancestors[0]?.length - 1;
816
- const ancestorNode = node.ancestors[0][lastIndex];
817
- if (!ancestorNode?.shortId) return {};
818
- id = ancestorNode.shortId;
819
- node = await this.directoryNodesService.getItem(id);
820
- const ancestorInfoUnit = node.informationUnits?.[0];
821
- const ancestorLabel = ancestorInfoUnit?.labels?.[0];
822
- return {
823
- documentId: ancestorInfoUnit?.shortId,
824
- label: ancestorLabel?.value || ""
825
- };
826
- }
827
508
  };
828
509
 
829
510
  // src/language.ts
511
+ var import_sdk3 = require("@c-rex/core/sdk");
830
512
  var LanguageService = class extends BaseService {
831
513
  constructor() {
832
- const configs = getClientConfig();
514
+ const sdk = new import_sdk3.CrexSDK();
515
+ const configs = sdk.getClientConfig();
833
516
  super(configs.languageSwitcher.endpoint);
834
517
  }
835
518
  /**
@@ -866,12 +549,14 @@ var LanguageService = class extends BaseService {
866
549
  };
867
550
 
868
551
  // src/transforms/topics.ts
869
- var import_headers5 = require("next/headers");
870
- var import_logger4 = require("@c-rex/core/logger");
552
+ var import_headers3 = require("next/headers");
553
+ var import_logger2 = require("@c-rex/core/logger");
554
+ var import_sdk4 = require("@c-rex/core/sdk");
871
555
  var transformTopics = async (data) => {
872
- const logger = new import_logger4.CrexLogger();
873
- const config = getClientConfig();
874
- const uiLang = ((0, import_headers5.cookies)().get(UI_LANG_KEY)?.value || config.languageSwitcher.default).toLowerCase();
556
+ const logger = new import_logger2.CrexLogger();
557
+ const sdk = new import_sdk4.CrexSDK();
558
+ const config = sdk.getClientConfig();
559
+ const uiLang = ((0, import_headers3.cookies)().get(UI_LANG_KEY)?.value || config.languageSwitcher.default).toLowerCase();
875
560
  const items = data.items.map((item) => {
876
561
  const type = item.class.labels.filter((item2) => item2.language === EN_LANG)[0].value.toUpperCase();
877
562
  let link = `/topics/${item.shortId}`;