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