@c-rex/services 0.1.2 → 0.1.3

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
@@ -14,15 +14,16 @@ var FLAGS_BY_LANG = {
14
14
  "de": "DE"
15
15
  };
16
16
  var EN_LANG = "en";
17
+ var TOPIC = "TOPIC";
18
+ var DOCUMENT = "DOCUMENT";
19
+ var PACKAGE = "PACKAGE";
17
20
  var RESULT_TYPES = {
18
- TOPIC: "TOPIC",
19
- DOCUMENT: "DOCUMENT",
20
- PACKAGE: "PACKAGE"
21
+ TOPIC,
22
+ DOCUMENT,
23
+ PACKAGE
21
24
  };
22
25
  var DEFAULT_COOKIE_LIMIT = 7 * 24 * 60 * 60 * 1e3;
23
-
24
- // ../core/src/requests.ts
25
- import { Issuer } from "openid-client";
26
+ var CREX_TOKEN_HEADER_KEY = "crex-token";
26
27
 
27
28
  // ../utils/src/utils.ts
28
29
  var call = async (method, params) => {
@@ -30,7 +31,8 @@ var call = async (method, params) => {
30
31
  const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/rpc`, {
31
32
  method: "POST",
32
33
  headers: { "Content-Type": "application/json" },
33
- body: JSON.stringify({ method, params })
34
+ body: JSON.stringify({ method, params }),
35
+ credentials: "include"
34
36
  });
35
37
  const json = await res.json();
36
38
  if (!res.ok) throw new Error(json.error || "Unknown error");
@@ -50,23 +52,35 @@ var getCountryCodeByLang = (lang) => {
50
52
  };
51
53
 
52
54
  // ../utils/src/memory.ts
53
- function isBrowser() {
54
- return typeof window !== "undefined" && typeof document !== "undefined";
55
- }
56
- function saveInMemory(value, key) {
57
- if (isBrowser()) throw new Error("saveInMemory is not supported in browser");
58
- if (typeof global !== "undefined" && !(key in global)) {
59
- global[key] = null;
55
+ var getCookie = async (key) => {
56
+ const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/cookies?key=${key}`);
57
+ if (!res.ok) {
58
+ return { key, value: null };
60
59
  }
61
- const globalConfig = global[key];
62
- if (globalConfig === null) {
63
- global[key] = value;
60
+ const json = await res.json();
61
+ return json;
62
+ };
63
+ var setCookie = async (key, value, maxAge) => {
64
+ try {
65
+ if (maxAge === void 0) {
66
+ maxAge = DEFAULT_COOKIE_LIMIT;
67
+ }
68
+ await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/cookies`, {
69
+ method: "POST",
70
+ credentials: "include",
71
+ body: JSON.stringify({
72
+ key,
73
+ value,
74
+ maxAge
75
+ })
76
+ });
77
+ } catch (error) {
78
+ call("CrexLogger.log", {
79
+ level: "error",
80
+ message: `utils.setCookie error: ${error}`
81
+ });
64
82
  }
65
- }
66
- function getFromMemory(key) {
67
- if (isBrowser()) throw new Error("getFromMemory is not supported in browser");
68
- return global[key];
69
- }
83
+ };
70
84
 
71
85
  // ../utils/src/classMerge.ts
72
86
  import { clsx } from "clsx";
@@ -84,55 +98,128 @@ var generateQueryParams = (params) => {
84
98
  return queryParams;
85
99
  };
86
100
 
101
+ // ../utils/src/token.ts
102
+ var updateToken = async () => {
103
+ try {
104
+ const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/token`, {
105
+ method: "POST",
106
+ credentials: "include"
107
+ });
108
+ const cookies = response.headers.get("set-cookie");
109
+ if (cookies === null) return null;
110
+ const aux = cookies.split(`${CREX_TOKEN_HEADER_KEY}=`);
111
+ if (aux.length == 0) return null;
112
+ const token = aux[1].split(";")[0];
113
+ if (token === void 0) throw new Error("Token is undefined");
114
+ return token;
115
+ } catch (error) {
116
+ call("CrexLogger.log", {
117
+ level: "error",
118
+ message: `utils.updateToken error: ${error}`
119
+ });
120
+ return null;
121
+ }
122
+ };
123
+ var manageToken = async () => {
124
+ try {
125
+ const hasToken = await getCookie(CREX_TOKEN_HEADER_KEY);
126
+ let token = hasToken.value;
127
+ if (hasToken.value === null) {
128
+ const tokenResult = await updateToken();
129
+ if (tokenResult === null) throw new Error("Token is undefined");
130
+ token = tokenResult;
131
+ }
132
+ return token;
133
+ } catch (error) {
134
+ call("CrexLogger.log", {
135
+ level: "error",
136
+ message: `utils.manageToken error: ${error}`
137
+ });
138
+ return null;
139
+ }
140
+ };
141
+
87
142
  // ../core/src/requests.ts
88
143
  import { getConfigs } from "@c-rex/utils/next-cookies";
89
- var CREX_TOKEN_HEADER_KEY = "crex-token";
90
- var CREX_TOKEN_EXPIRY_HEADER_KEY = "crex-token-expiry";
91
- var CrexApi = class {
92
- customerConfig;
93
- apiClient;
94
- async manageToken() {
95
- const headersAux = {};
96
- if (this.customerConfig.OIDC.client.enabled) {
97
- let token = getFromMemory(CREX_TOKEN_HEADER_KEY);
98
- const tokenExpiry = Number(
99
- getFromMemory(CREX_TOKEN_EXPIRY_HEADER_KEY)
100
- );
101
- const now = Math.floor(Date.now() / 1e3);
102
- if (!(token && tokenExpiry > now + 60)) {
103
- const { token: tokenAux, tokenExpiry: tokenExpiryAux } = await this.getToken();
104
- token = tokenAux;
105
- saveInMemory(token, CREX_TOKEN_HEADER_KEY);
106
- saveInMemory(tokenExpiryAux.toString(), CREX_TOKEN_EXPIRY_HEADER_KEY);
107
- }
108
- headersAux["Authorization"] = `Bearer ${token}`;
109
- }
110
- return headersAux;
144
+
145
+ // ../core/src/cache.ts
146
+ var CrexCache = class {
147
+ /**
148
+ * Retrieves a value from the cache by key.
149
+ *
150
+ * @param key - The cache key to retrieve
151
+ * @returns The cached value as a string, or null if not found
152
+ */
153
+ async get(key) {
154
+ const cookie = await getCookie(key);
155
+ return cookie.value;
111
156
  }
112
- async getToken() {
113
- let token = "";
114
- let tokenExpiry = 0;
157
+ /**
158
+ * Stores a value in the cache with the specified key.
159
+ * Checks if the value size is within cookie size limits (4KB).
160
+ *
161
+ * @param key - The cache key
162
+ * @param value - The value to store
163
+ */
164
+ async set(key, value) {
115
165
  try {
116
- const now = Math.floor(Date.now() / 1e3);
117
- const issuer = await Issuer.discover(this.customerConfig.OIDC.client.issuer);
118
- const client = new issuer.Client({
119
- client_id: this.customerConfig.OIDC.client.id,
120
- client_secret: this.customerConfig.OIDC.client.secret
121
- });
122
- const tokenSet = await client.grant({ grant_type: "client_credentials" });
123
- token = tokenSet.access_token;
124
- tokenExpiry = now + tokenSet.expires_at;
166
+ const byteLength = new TextEncoder().encode(value).length;
167
+ if (byteLength <= 4096) {
168
+ await setCookie(key, value);
169
+ } else {
170
+ console.warn(`Cookie ${key} value is too large to be stored in a single cookie`);
171
+ }
125
172
  } catch (error) {
126
173
  call("CrexLogger.log", {
127
174
  level: "error",
128
- message: `API.getToken error when request ${this.customerConfig.OIDC.client.issuer}. Error: ${error}`
175
+ message: `CrexCache.set error: ${error}`
129
176
  });
130
177
  }
131
- return {
132
- token,
133
- tokenExpiry
134
- };
135
178
  }
179
+ /**
180
+ * Generates a cache key based on request parameters.
181
+ * Combines URL, method, and optionally params, body, and headers into a single string key.
182
+ *
183
+ * @param options - Request options to generate key from
184
+ * @param options.url - The request URL
185
+ * @param options.method - The HTTP method
186
+ * @param options.body - Optional request body
187
+ * @param options.params - Optional query parameters
188
+ * @param options.headers - Optional request headers
189
+ * @returns A string cache key
190
+ */
191
+ generateCacheKey({
192
+ url,
193
+ method,
194
+ body,
195
+ params,
196
+ headers
197
+ }) {
198
+ let cacheKey = `${url}-${method}`;
199
+ if (params !== void 0 && Object.keys(params).length > 0) {
200
+ cacheKey += `-${JSON.stringify(params)}`;
201
+ }
202
+ if (body !== void 0 && Object.keys(body).length > 0) {
203
+ cacheKey += `-${JSON.stringify(body)}`;
204
+ }
205
+ if (headers !== void 0 && Object.keys(headers).length > 0) {
206
+ cacheKey += `-${JSON.stringify(headers)}`;
207
+ }
208
+ return cacheKey;
209
+ }
210
+ };
211
+
212
+ // ../core/src/requests.ts
213
+ var CrexApi = class {
214
+ customerConfig;
215
+ apiClient;
216
+ cache;
217
+ /**
218
+ * Initializes the API client if it hasn't been initialized yet.
219
+ * Loads customer configuration, creates the axios instance, and initializes the cache.
220
+ *
221
+ * @private
222
+ */
136
223
  async initAPI() {
137
224
  if (!this.customerConfig) {
138
225
  this.customerConfig = await getConfigs();
@@ -142,7 +229,22 @@ var CrexApi = class {
142
229
  baseURL: this.customerConfig.baseUrl
143
230
  });
144
231
  }
232
+ if (!this.cache) {
233
+ this.cache = new CrexCache();
234
+ }
145
235
  }
236
+ /**
237
+ * Executes an API request with caching, authentication, and retry logic.
238
+ *
239
+ * @param options - Request options
240
+ * @param options.url - The URL to request
241
+ * @param options.method - The HTTP method to use
242
+ * @param options.params - Optional query parameters
243
+ * @param options.body - Optional request body
244
+ * @param options.headers - Optional request headers
245
+ * @returns The response data
246
+ * @throws Error if the request fails after maximum retries
247
+ */
146
248
  async execute({
147
249
  url,
148
250
  method,
@@ -152,10 +254,14 @@ var CrexApi = class {
152
254
  }) {
153
255
  await this.initAPI();
154
256
  let response = void 0;
155
- headers = {
156
- ...headers,
157
- ...await this.manageToken()
158
- };
257
+ if (this.customerConfig.OIDC.client.enabled) {
258
+ const token = await manageToken();
259
+ headers = {
260
+ ...headers,
261
+ Authorization: `Bearer ${token}`
262
+ };
263
+ this.apiClient.defaults.headers.common["Authorization"] = `Bearer ${token}`;
264
+ }
159
265
  for (let retry = 0; retry < API.MAX_RETRY; retry++) {
160
266
  try {
161
267
  response = await this.apiClient.request({
@@ -241,7 +347,15 @@ var RenditionsService = class extends BaseService {
241
347
  constructor() {
242
348
  super("Renditions/");
243
349
  }
244
- async getHTMLRendition(renditions) {
350
+ /**
351
+ * Retrieves the HTML rendition from a list of renditions.
352
+ * Filters for renditions with format 'application/xhtml+xml' and rel 'view'.
353
+ *
354
+ * @param renditions - Array of rendition objects to process
355
+ * @returns A promise that resolves to the HTML content as a string, or empty string if no suitable rendition is found
356
+ * @throws Error if the API request fails
357
+ */
358
+ async getHTMLRendition({ renditions }) {
245
359
  const filteredRenditions = renditions.filter(
246
360
  (item2) => item2.format == "application/xhtml+xml"
247
361
  );
@@ -259,7 +373,14 @@ var RenditionsService = class extends BaseService {
259
373
  });
260
374
  return response;
261
375
  }
262
- getFileRenditions = (renditions) => {
376
+ /**
377
+ * Processes a list of renditions and categorizes them into files to download and files to open.
378
+ * Excludes renditions with formats 'application/xhtml+xml', 'application/json', and 'application/llm+xml'.
379
+ *
380
+ * @param renditions - Array of rendition objects to process
381
+ * @returns An object containing arrays of file renditions categorized as 'filesToDownload' and 'filesToOpen'
382
+ */
383
+ getFileRenditions = ({ renditions }) => {
263
384
  if (renditions == void 0 || renditions.length == 0) {
264
385
  return {
265
386
  filesToDownload: [],
@@ -301,11 +422,26 @@ var DirectoryNodesService = class extends BaseService {
301
422
  constructor() {
302
423
  super("DirectoryNodes/");
303
424
  }
425
+ /**
426
+ * Retrieves a specific directory node by its ID.
427
+ *
428
+ * @param id - The unique identifier of the directory node
429
+ * @returns A promise that resolves to the directory node data
430
+ * @throws Error if the API request fails
431
+ */
304
432
  async getItem(id) {
305
433
  return await this.request({
306
434
  path: id
307
435
  });
308
436
  }
437
+ /**
438
+ * Retrieves a list of directory nodes based on specified filters.
439
+ *
440
+ * @param options - Options for filtering the directory nodes list
441
+ * @param options.filters - Optional array of filter strings to apply
442
+ * @returns A promise that resolves to the directory nodes response
443
+ * @throws Error if the API request fails
444
+ */
309
445
  async getList({
310
446
  filters = []
311
447
  }) {
@@ -335,6 +471,14 @@ var DocumentTypesService = class extends BaseService {
335
471
  constructor() {
336
472
  super("DocumentTypes/");
337
473
  }
474
+ /**
475
+ * Retrieves document type labels for the specified fields.
476
+ * The labels are restricted to English language (EN-us).
477
+ *
478
+ * @param fields - Array of field names to retrieve labels for
479
+ * @returns A promise that resolves to an array of label strings
480
+ * @throws Error if the API request fails
481
+ */
338
482
  async getLabels(fields) {
339
483
  const params = [
340
484
  {
@@ -353,13 +497,15 @@ var DocumentTypesService = class extends BaseService {
353
497
  // src/transforms/information.ts
354
498
  import { getConfigs as getConfigs2 } from "@c-rex/utils/next-cookies";
355
499
  var transformInformationUnits = async (data) => {
356
- const config = await getConfigs2();
500
+ const config = getConfigs2();
357
501
  const items = await Promise.all(data.items.map(async (item) => {
358
- let link = `/topics/${item.shortId}`;
359
502
  const type = item.class.labels.filter((item2) => item2.language === EN_LANG)[0].value.toUpperCase();
360
503
  const service = new RenditionsService();
361
- const { filesToOpen, filesToDownload } = service.getFileRenditions(item?.renditions);
362
- if (type == RESULT_TYPES.DOCUMENT) {
504
+ const { filesToOpen, filesToDownload } = service.getFileRenditions({ renditions: item?.renditions });
505
+ let link = `/topics/${item.shortId}`;
506
+ if (config.results.articlePageLayout == "BLOG") {
507
+ link = `/blog/${item.shortId}`;
508
+ } else if (type == RESULT_TYPES.DOCUMENT) {
363
509
  link = `/documents/${item.shortId}`;
364
510
  }
365
511
  return {
@@ -385,6 +531,18 @@ var InformationUnitsService = class extends BaseService {
385
531
  constructor() {
386
532
  super("InformationUnits/");
387
533
  }
534
+ /**
535
+ * Retrieves a list of information units based on specified criteria.
536
+ *
537
+ * @param options - Options for filtering and paginating the information units list
538
+ * @param options.queries - Optional search query string
539
+ * @param options.page - Optional page number for pagination (defaults to 1)
540
+ * @param options.fields - Optional array of fields to include in the response
541
+ * @param options.filters - Optional array of filter strings to apply
542
+ * @param options.languages - Optional array of language codes to filter by
543
+ * @returns A promise that resolves to the information units response
544
+ * @throws Error if the API request fails
545
+ */
388
546
  async getList({
389
547
  queries = "",
390
548
  page = 1,
@@ -415,6 +573,15 @@ var InformationUnitsService = class extends BaseService {
415
573
  transformer: transformInformationUnits
416
574
  });
417
575
  }
576
+ /**
577
+ * Retrieves a specific information unit by its ID.
578
+ * Includes renditions, directory nodes, version information, titles, languages, and labels.
579
+ *
580
+ * @param options - Options for retrieving the information unit
581
+ * @param options.id - The unique identifier of the information unit
582
+ * @returns A promise that resolves to the information unit data
583
+ * @throws Error if the API request fails
584
+ */
418
585
  async getItem({ id }) {
419
586
  const params = [
420
587
  { key: "Fields", value: "renditions" },
@@ -429,21 +596,44 @@ var InformationUnitsService = class extends BaseService {
429
596
  params
430
597
  });
431
598
  }
432
- async getSuggestions({ query }) {
599
+ /**
600
+ * Retrieves autocomplete suggestions based on a query prefix.
601
+ *
602
+ * @param options - Options for retrieving suggestions
603
+ * @param options.query - The query prefix to get suggestions for
604
+ * @param options.language - The language of the suggestions
605
+ * @returns A promise that resolves to an array of suggestion strings
606
+ * @throws Error if the API request fails
607
+ */
608
+ async getSuggestions({ query, language }) {
433
609
  return await this.request({
434
610
  path: `Suggestions`,
435
- params: [{ key: "prefix", value: query }],
611
+ params: [
612
+ { key: "prefix", value: query },
613
+ { key: "lang", value: language }
614
+ ],
436
615
  transformer: (data) => {
437
- return data.suggestions.map((item) => item.value);
616
+ const suggestions = [];
617
+ const comparableList = [];
618
+ data.suggestions.forEach((item) => {
619
+ suggestions.push(item.value);
620
+ comparableList.push(item.value.toLowerCase());
621
+ });
622
+ if (!comparableList.includes(query.toLowerCase())) {
623
+ return [query, ...suggestions];
624
+ }
625
+ return suggestions;
438
626
  }
439
627
  });
440
628
  }
441
629
  };
442
630
 
443
631
  // src/language.ts
632
+ import { getConfigs as getConfigs3 } from "@c-rex/utils/next-cookies";
444
633
  var LanguageService = class extends BaseService {
445
- constructor(endpoint) {
446
- super(endpoint);
634
+ constructor() {
635
+ const configs = getConfigs3();
636
+ super(configs.languageSwitcher.endpoint);
447
637
  }
448
638
  /*
449
639
  public static async getInstance(): Promise<LanguageService> {
@@ -455,6 +645,13 @@ var LanguageService = class extends BaseService {
455
645
  return LanguageService.instance;
456
646
  }
457
647
  */
648
+ /**
649
+ * Retrieves a list of available languages and their associated countries.
650
+ * Transforms the API response to include language code, country code, and original value.
651
+ *
652
+ * @returns A promise that resolves to an array of language and country objects
653
+ * @throws Error if the API request fails
654
+ */
458
655
  async getLanguagesAndCountries() {
459
656
  return await this.request({
460
657
  transformer: (data) => {