@c-rex/services 0.1.16 → 0.1.18

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 DELETED
@@ -1,650 +0,0 @@
1
- // src/baseService.ts
2
- import { CrexApi } from "@c-rex/core/requests";
3
-
4
- // ../constants/src/index.ts
5
- var CONTENT_LANG_KEY = "CONTENT_LANG_KEY";
6
- var UI_LANG_KEY = "UI_LANG_KEY";
7
- var FLAGS_BY_LANG = {
8
- "en": "US",
9
- "de": "DE"
10
- };
11
- var EN_LANG = "en";
12
- var TOPIC = "TOPIC";
13
- var DOCUMENT = "DOCUMENT";
14
- var PACKAGE = "PACKAGE";
15
- var FRAGMENT = "FRAGMENT";
16
- var RESULT_TYPES = {
17
- TOPIC,
18
- DOCUMENT,
19
- PACKAGE,
20
- FRAGMENT
21
- };
22
- var DEFAULT_COOKIE_LIMIT = 30 * 24 * 60 * 60 * 1e3;
23
- var WILD_CARD_OPTIONS = {
24
- BOTH: "BOTH",
25
- END: "END",
26
- START: "START",
27
- NONE: "NONE"
28
- };
29
- var OPERATOR_OPTIONS = {
30
- AND: "AND",
31
- OR: "OR"
32
- };
33
-
34
- // ../utils/src/utils.ts
35
- var getCountryCodeByLang = (lang) => {
36
- const mappedKeys = Object.keys(FLAGS_BY_LANG);
37
- if (!mappedKeys.includes(lang)) {
38
- return lang;
39
- }
40
- const country = FLAGS_BY_LANG[lang];
41
- return country;
42
- };
43
- var formatDateToLocale = (date, locale) => {
44
- if (typeof date !== "string" || !date) {
45
- return date;
46
- }
47
- const dateAux = new Date(date);
48
- return new Intl.DateTimeFormat(locale, {
49
- day: "2-digit",
50
- month: "long",
51
- year: "numeric"
52
- }).format(dateAux);
53
- };
54
-
55
- // ../utils/src/classMerge.ts
56
- import { clsx } from "clsx";
57
- import { twMerge } from "tailwind-merge";
58
-
59
- // ../utils/src/params.ts
60
- var createParams = (fieldsList, key = "Fields") => {
61
- if (!fieldsList || fieldsList.length === 0) {
62
- return [];
63
- }
64
- return fieldsList.map((item) => ({
65
- key,
66
- value: item
67
- }));
68
- };
69
- var generateQueryParams = (params) => {
70
- const queryParams = params.map((param) => `${encodeURIComponent(param.key)}=${encodeURIComponent(param.value)}`).join("&");
71
- return queryParams;
72
- };
73
-
74
- // ../utils/src/renditions.ts
75
- var getFileRenditions = ({ renditions }) => {
76
- if (renditions == void 0 || renditions.length == 0) {
77
- return {};
78
- }
79
- const filteredRenditions = renditions.filter(
80
- (item) => item.format != "application/xhtml+xml" && item.format != "application/json" && item.format != "application/llm+xml"
81
- );
82
- if (filteredRenditions.length == 0 || filteredRenditions[0] == void 0) {
83
- return {};
84
- }
85
- const result = {};
86
- filteredRenditions.forEach((item) => {
87
- const key = item.format;
88
- if (result[key] == void 0) {
89
- result[key] = {
90
- view: "",
91
- download: ""
92
- };
93
- }
94
- result[key].download = item.links.filter((link) => link.rel == "download")[0]?.href;
95
- result[key].view = item.links.filter((link) => link.rel == "view")[0]?.href;
96
- });
97
- return result;
98
- };
99
-
100
- // src/baseService.ts
101
- var BaseService = class {
102
- api;
103
- endpoint;
104
- /**
105
- * Creates a new instance of BaseService.
106
- *
107
- * @param endpoint - The API endpoint URL for this service
108
- */
109
- constructor(endpoint) {
110
- this.api = new CrexApi();
111
- this.endpoint = endpoint;
112
- }
113
- /**
114
- * Makes an API request to the specified endpoint.
115
- *
116
- * @param options - Request configuration options
117
- * @param options.path - Optional path to append to the endpoint
118
- * @param options.params - Optional query parameters to include in the request
119
- * @param options.method - HTTP method to use (defaults to 'get')
120
- * @param options.transformer - Optional function to transform the response data
121
- * @returns The response data, optionally transformed
122
- * @throws Error if the API request fails
123
- */
124
- async request({
125
- path = "",
126
- method = "get",
127
- params = [],
128
- headers = {},
129
- transformer = (response) => response
130
- }) {
131
- let url = `${this.endpoint}${path}`;
132
- const queryParams = generateQueryParams(params);
133
- if (queryParams.length > 0) {
134
- url += `?${queryParams}`;
135
- }
136
- const response = await this.api.execute({
137
- url,
138
- method,
139
- headers
140
- });
141
- return await transformer(response);
142
- }
143
- };
144
-
145
- // src/renditions.ts
146
- var RenditionsService = class extends BaseService {
147
- constructor() {
148
- super("Renditions/");
149
- }
150
- /**
151
- * Retrieves the HTML rendition from a list of renditions.
152
- * Filters for renditions with format 'application/xhtml+xml' and rel 'view'.
153
- *
154
- * @param renditions - Array of rendition objects to process
155
- * @returns A promise that resolves to the HTML content as a string, or empty string if no suitable rendition is found
156
- * @throws Error if the API request fails
157
- */
158
- async getHTMLRendition({ renditions }) {
159
- const filteredRenditions = renditions.filter(
160
- (item2) => item2.format == "application/xhtml+xml"
161
- );
162
- if (filteredRenditions.length == 0 || filteredRenditions[0] == void 0) return "";
163
- const item = filteredRenditions[0];
164
- const filteredLinks = item.links.filter((item2) => item2.rel == "view");
165
- if (filteredLinks.length == 0 || filteredLinks[0] == void 0) return "";
166
- const url = filteredLinks[0].href;
167
- const response = await this.api.execute({
168
- url,
169
- method: "get",
170
- headers: {
171
- Accept: "application/xhtml+xml"
172
- }
173
- });
174
- return response;
175
- }
176
- };
177
-
178
- // src/directoryNodes.ts
179
- var DirectoryNodesService = class extends BaseService {
180
- constructor() {
181
- super("DirectoryNodes/");
182
- }
183
- /**
184
- * Retrieves a specific directory node by its ID.
185
- *
186
- * @param id - The unique identifier of the directory node
187
- * @returns A promise that resolves to the directory node data
188
- * @throws Error if the API request fails
189
- */
190
- async getItem(id) {
191
- return await this.request({
192
- path: id
193
- });
194
- }
195
- /**
196
- * Retrieves a list of directory nodes based on specified filters.
197
- *
198
- * @param options - Options for filtering the directory nodes list
199
- * @param options.filters - Optional array of filter strings to apply
200
- * @returns A promise that resolves to the directory nodes response
201
- * @throws Error if the API request fails
202
- */
203
- async getList({
204
- filters = []
205
- }) {
206
- const remainFilters = createParams(filters, "Filter");
207
- return await this.request({
208
- params: {
209
- ...remainFilters
210
- }
211
- });
212
- }
213
- };
214
-
215
- // src/transforms/documentTypes.ts
216
- import { CrexSDK } from "@c-rex/core/sdk";
217
- import { cookies } from "next/headers";
218
- var transformDocumentTypes = async (data) => {
219
- const labels = [];
220
- const sdk = new CrexSDK();
221
- const config = sdk.getClientConfig();
222
- const contentLanguage = cookies().get(CONTENT_LANG_KEY)?.value || config.languageSwitcher.default;
223
- const language = contentLanguage.split("-")[0];
224
- data.items.forEach((documentItem) => {
225
- const label = documentItem.labels.find((item) => item.language.toLowerCase() === language.toLowerCase());
226
- labels.push({
227
- shortId: documentItem.shortId,
228
- label: label ? label.value : ""
229
- });
230
- });
231
- return labels;
232
- };
233
-
234
- // src/documentTypes.ts
235
- var DocumentTypesService = class extends BaseService {
236
- constructor() {
237
- super("DocumentTypes/");
238
- }
239
- /**
240
- * Retrieves document type labels for the specified fields.
241
- *
242
- * @returns A promise that resolves to an array of label strings
243
- * @throws Error if the API request fails
244
- */
245
- async getLabels() {
246
- return await this.request({
247
- params: [{
248
- key: "sparqlWhere",
249
- value: "?iu iirds:is-applicable-for-document-type ?s . ?iu iirds:has-topic-type <https://www.c-rex.net/iirds/td#Blogpost>"
250
- }],
251
- transformer: transformDocumentTypes
252
- });
253
- }
254
- };
255
-
256
- // src/transforms/information.ts
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";
260
- var transformInformationUnits = async (data) => {
261
- const logger = new CrexLogger();
262
- const sdk = new CrexSDK2();
263
- const frontEndConfig = sdk.getClientConfig();
264
- const backEndConfig = sdk.getServerConfig();
265
- const filteredTags = {};
266
- const items = data.items.map((item) => {
267
- const type = item.class.labels.filter((item2) => item2.language === EN_LANG)[0].value.toUpperCase();
268
- const files = getFileRenditions({ renditions: item?.renditions });
269
- let link = `/topics/${item.shortId}`;
270
- if (frontEndConfig.results.articlePageLayout == "BLOG") {
271
- link = `/blog/${item.shortId}`;
272
- } else if (type == RESULT_TYPES.DOCUMENT) {
273
- link = `/documents/${item.shortId}`;
274
- }
275
- let title = "NO TITLE";
276
- if (item.titles) {
277
- title = item.titles[0].value;
278
- } else if (item.labels) {
279
- title = item.labels[0].value;
280
- }
281
- let language = "NO LANGUAGE";
282
- if (item.languages.length > 0) {
283
- language = item.languages[0];
284
- }
285
- let versionOf = [];
286
- if (item?.versionOf && item.versionOf?.labels) {
287
- versionOf = item.versionOf.labels.map((item2) => item2.language).filter((value) => value !== void 0);
288
- }
289
- return {
290
- language,
291
- title,
292
- type,
293
- localeType: "",
294
- revision: item.revision,
295
- shortId: item.shortId,
296
- multipleVersions: versionOf,
297
- disabled: frontEndConfig.results.disabledResults.includes(type),
298
- link,
299
- files
300
- };
301
- });
302
- if (data.tags) {
303
- const contentLang = (cookies2().get(CONTENT_LANG_KEY)?.value || EN_LANG).toLowerCase();
304
- const splittedContentLang = contentLang.split("-")[0];
305
- for (const [key, value] of Object.entries(data.tags)) {
306
- if (!value || !value.items || value.items.length === 0) {
307
- continue;
308
- }
309
- if (!backEndConfig.search.tags.includes(key)) {
310
- continue;
311
- }
312
- const aux = value.items.map((item) => {
313
- if (item?.shortId === void 0) return null;
314
- if (Number(item.hits) === 0) return null;
315
- if (item?.labels === void 0 || item?.labels.length === 0) {
316
- logger.log({
317
- level: "warning",
318
- message: `No labels on item with id ${item.shortId} from category ${key}`
319
- });
320
- return null;
321
- }
322
- let label = "";
323
- for (const labelItem of item.labels) {
324
- if (labelItem.language === void 0) {
325
- logger.log({
326
- level: "info",
327
- message: `No language on label ${labelItem.value} from category ${key}`
328
- });
329
- label = labelItem.value;
330
- break;
331
- }
332
- if (labelItem.language.toLowerCase() === contentLang || labelItem.language.toLowerCase() === splittedContentLang) {
333
- label = labelItem.value;
334
- break;
335
- }
336
- label = labelItem.value;
337
- }
338
- return {
339
- hits: item.hits,
340
- total: item.total,
341
- label,
342
- active: false,
343
- shortId: item.shortId
344
- };
345
- }).filter((item) => item !== null);
346
- if (aux.length === 0) {
347
- continue;
348
- }
349
- filteredTags[key] = aux;
350
- }
351
- }
352
- return {
353
- tags: filteredTags,
354
- items,
355
- pageInfo: data.pageInfo
356
- };
357
- };
358
- var transformSuggestions = (data, query) => {
359
- const suggestions = [];
360
- const comparableList = [];
361
- data.suggestions.forEach((item) => {
362
- suggestions.push(item.value);
363
- comparableList.push(item.value.toLowerCase());
364
- });
365
- if (!comparableList.includes(query.toLowerCase())) {
366
- return [query, ...suggestions];
367
- }
368
- return suggestions;
369
- };
370
-
371
- // src/informationUnits.ts
372
- var InformationUnitsService = class extends BaseService {
373
- constructor() {
374
- super("InformationUnits/");
375
- }
376
- /**
377
- * Retrieves a list of information units based on specified criteria.
378
- *
379
- * @param options - Options for filtering and paginating the information units list
380
- * @param options.queries - Optional search query string
381
- * @param options.page - Optional page number for pagination (defaults to 1)
382
- * @param options.fields - Optional array of fields to include in the response
383
- * @param options.filters - Optional array of filter strings to apply
384
- * @param options.languages - Optional array of language codes to filter by
385
- * @returns A promise that resolves to the information units response
386
- * @throws Error if the API request fails
387
- */
388
- async getList({
389
- queries = "",
390
- page = 1,
391
- fields = [],
392
- filters = [],
393
- tags = [],
394
- restrict = [],
395
- languages = [],
396
- wildcard = WILD_CARD_OPTIONS.BOTH,
397
- operator = OPERATOR_OPTIONS.AND,
398
- like = false
399
- }) {
400
- const remainFields = createParams(fields, "Fields");
401
- const remainFilters = createParams(filters, "Filter");
402
- const restrictions = createParams(restrict, "Restrict");
403
- const remainTags = createParams(tags, "Tags");
404
- const params = [
405
- { key: "pageSize", value: "12" },
406
- { key: "wildcard", value: wildcard.toLowerCase() },
407
- { key: "PageNumber", value: page.toString() },
408
- { key: "Operator", value: operator },
409
- { key: "Like", value: like.toString() },
410
- ...remainTags,
411
- ...remainFields,
412
- ...remainFilters,
413
- ...restrictions
414
- ];
415
- if (languages.length > 0) {
416
- const languageParam = `VALUES ?lang { ${languages.map((lang) => `"${lang}"`).join(" ")} } ?s iirds:language ?lang .`;
417
- params.push({ key: "sparqlWhere", value: languageParam });
418
- }
419
- if (queries.length > 0) {
420
- params.push(
421
- { key: "Query", value: queries }
422
- );
423
- }
424
- return await this.request({
425
- params,
426
- transformer: transformInformationUnits
427
- });
428
- }
429
- /**
430
- * Retrieves a specific information unit by its ID.
431
- * Includes renditions, directory nodes, version information, titles, languages, and labels.
432
- *
433
- * @param options - Options for retrieving the information unit
434
- * @param options.id - The unique identifier of the information unit
435
- * @returns A promise that resolves to the information unit data
436
- * @throws Error if the API request fails
437
- */
438
- async getItem({ id, shouldGetAllFields = false }) {
439
- const params = [];
440
- if (!shouldGetAllFields) {
441
- params.push(
442
- { key: "Fields", value: "renditions" },
443
- { key: "Fields", value: "directoryNodes" },
444
- { key: "Fields", value: "versionOf" },
445
- { key: "Fields", value: "titles" },
446
- { key: "Fields", value: "languages" },
447
- { key: "Fields", value: "labels" },
448
- { key: "Fields", value: "packages" },
449
- { key: "Fields", value: "created" },
450
- { key: "Fields", value: "revision" }
451
- );
452
- }
453
- return await this.request({
454
- path: id,
455
- params
456
- });
457
- }
458
- /**
459
- * Retrieves autocomplete suggestions based on a query prefix.
460
- *
461
- * @param options - Options for retrieving suggestions
462
- * @param options.query - The query prefix to get suggestions for
463
- * @param options.language - The language of the suggestions
464
- * @returns A promise that resolves to an array of suggestion strings
465
- * @throws Error if the API request fails
466
- */
467
- async getSuggestions({ query, language }) {
468
- return await this.request({
469
- path: "Suggestions",
470
- params: [
471
- { key: "prefix", value: query },
472
- { key: "lang", value: language }
473
- ],
474
- transformer: (data) => transformSuggestions(data, query)
475
- });
476
- }
477
- };
478
-
479
- // src/language.ts
480
- import { CrexSDK as CrexSDK3 } from "@c-rex/core/sdk";
481
- var LanguageService = class extends BaseService {
482
- constructor() {
483
- const sdk = new CrexSDK3();
484
- const configs = sdk.getClientConfig();
485
- super(configs.languageSwitcher.endpoint);
486
- }
487
- /**
488
- * Retrieves a list of available languages and their associated countries.
489
- * Transforms the API response to include language code, country code, and original value.
490
- *
491
- * @returns A promise that resolves to an array of language and country objects
492
- * @throws Error if the API request fails
493
- */
494
- async getLanguagesAndCountries() {
495
- return await this.request({
496
- transformer: (data) => {
497
- const countryCodeList = data.map((item) => {
498
- const splittedValue = item.value.split("-");
499
- const lang = splittedValue[0];
500
- let country = splittedValue[0];
501
- if (splittedValue.length > 1) {
502
- country = splittedValue[1];
503
- } else {
504
- country = getCountryCodeByLang(lang);
505
- }
506
- return {
507
- country,
508
- lang,
509
- value: item.value
510
- };
511
- });
512
- return countryCodeList.sort((a, b) => {
513
- return a.value.localeCompare(b.value);
514
- });
515
- }
516
- });
517
- }
518
- };
519
-
520
- // src/transforms/topics.ts
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";
524
- var transformTopics = async (data) => {
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();
529
- const items = data.items.map((item) => {
530
- const type = item.class.labels.filter((item2) => item2.language === EN_LANG)[0].value.toUpperCase();
531
- let link = `/topics/${item.shortId}`;
532
- if (config.results.articlePageLayout == "BLOG") {
533
- link = `/blog/${item.shortId}`;
534
- } else if (type == RESULT_TYPES.DOCUMENT) {
535
- link = `/documents/${item.shortId}`;
536
- }
537
- let title = "NO TITLE";
538
- let language = "NO LANGUAGE";
539
- try {
540
- if (item.titles) {
541
- title = item.titles[0].value;
542
- language = item.titles[0].language;
543
- } else {
544
- title = item.labels[0].value;
545
- language = item.labels[0].language;
546
- }
547
- } catch {
548
- logger.log({
549
- level: "error",
550
- message: `No label or title on item ${item.shortId}`
551
- });
552
- }
553
- let renditionUrl = "";
554
- const renditions = item.renditions.filter((item2) => item2.format == "application/xhtml+xml");
555
- if (renditions.length > 0 || renditions[0] !== void 0) {
556
- const filteredLinks = renditions[0].links.filter((renditionItem) => renditionItem.rel == "view");
557
- if (filteredLinks.length > 0 || filteredLinks[0] !== void 0) {
558
- renditionUrl = filteredLinks[0].href;
559
- }
560
- ;
561
- }
562
- ;
563
- let categoryType = type;
564
- if (item.applicableForTypes && item.applicableForTypes.length > 0) {
565
- const splittedContentLang = uiLang.split("-")[0];
566
- categoryType = item.applicableForTypes[0].labels.find((item2) => item2.language === splittedContentLang)?.value || categoryType;
567
- }
568
- return {
569
- language,
570
- title,
571
- type: categoryType,
572
- localeType: "",
573
- shortId: item.shortId,
574
- created: formatDateToLocale(item.created, uiLang),
575
- disabled: config.results.disabledResults.includes(type),
576
- link,
577
- renditionUrl,
578
- image: null,
579
- description: null
580
- };
581
- });
582
- return {
583
- tags: null,
584
- items,
585
- pageInfo: data.pageInfo
586
- };
587
- };
588
-
589
- // src/topics.ts
590
- var TopicsService = class extends BaseService {
591
- constructor() {
592
- super("Topics/");
593
- }
594
- /**
595
- * Retrieves a list of topics based on specified criteria.
596
- *
597
- * @param options - Options for filtering and paginating the topics list
598
- * @param options.queries - Optional search query string
599
- * @param options.page - Optional page number for pagination (defaults to 1)
600
- * @param options.fields - Optional array of fields to include in the response
601
- * @param options.filters - Optional array of filter strings to apply
602
- * @param options.languages - Optional array of language codes to filter by
603
- * @returns A promise that resolves to the information units response
604
- * @throws Error if the API request fails
605
- */
606
- async getList({
607
- queries = "",
608
- page = 1,
609
- fields = [],
610
- filters = [],
611
- languages = [],
612
- wildcard = WILD_CARD_OPTIONS.BOTH,
613
- operator = OPERATOR_OPTIONS.AND,
614
- pageSize = 12
615
- }) {
616
- const remainFields = createParams(fields, "Fields");
617
- const remainFilters = createParams(filters, "Filter");
618
- const params = [
619
- { key: "pageSize", value: pageSize.toString() },
620
- { key: "PageNumber", value: page.toString() },
621
- { key: "Sort", value: "-created;-score" },
622
- { key: "Operator", value: operator },
623
- { key: "wildcard", value: wildcard.toLowerCase() },
624
- ...remainFields,
625
- ...remainFilters
626
- ];
627
- if (languages.length > 0) {
628
- const languageParam = `VALUES ?lang { ${languages.map((lang) => `"${lang}"`).join(" ")} } ?s iirds:language ?lang .`;
629
- params.push({ key: "sparqlWhere", value: languageParam });
630
- }
631
- if (queries.length > 0) {
632
- params.push(
633
- { key: "Query", value: queries }
634
- );
635
- }
636
- return await this.request({
637
- params,
638
- transformer: transformTopics
639
- });
640
- }
641
- };
642
- export {
643
- DirectoryNodesService,
644
- DocumentTypesService,
645
- InformationUnitsService,
646
- LanguageService,
647
- RenditionsService,
648
- TopicsService
649
- };
650
- //# sourceMappingURL=index.mjs.map