@startinblox/core 2.0.5-beta.3 → 2.0.5-beta.5

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.
@@ -1,8 +1,8 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
- import { l as isUrlOrRelativePath, m as jsonldContextParserExports, o as getRawContext, n as normalizeContext, q as mergeContexts, a as doesResourceContainList, r as requireJsonldContextParser, v as requireErrorCoded, w as requireLink } from "./helpers-Bew5Yvdt.js";
5
- let StoreService, formatAttributesToServerSearchOptions, base_context, hasQueryIndex, sibStore, formatAttributesToServerPaginationOptions, getDefaultExportFromCjs, hasSetLocalData, mergeServerSearchOptions, semantizer;
4
+ import { l as isUrlOrRelativePath, m as jsonldContextParserExports, o as getRawContext, n as normalizeContext, q as mergeContexts, c as doesResourceContainList, r as requireJsonldContextParser, v as requireErrorCoded, w as requireLink } from "./helpers-vZrb1UDN.js";
5
+ let StoreService, formatAttributesToServerSearchOptions, base_context, StoreType, StoreFactory, hasQueryIndex, formatAttributesToServerPaginationOptions, getDefaultExportFromCjs, hasSetLocalData, sibStore, mergeServerSearchOptions, semantizer;
6
6
  let __tla = (async () => {
7
7
  var _a;
8
8
  getDefaultExportFromCjs = function(x) {
@@ -86,6 +86,952 @@ let __tla = (async () => {
86
86
  const method = encodeURIComponent(options.method ?? "ibasic");
87
87
  return `${iri}${first}search-fields=${fields}&search-terms=${value}&search-method=${method}`;
88
88
  }
89
+ class InMemoryCacheManager {
90
+ constructor() {
91
+ __publicField(this, "resourceCache", /* @__PURE__ */ new Map());
92
+ __publicField(this, "urlToIdMap", /* @__PURE__ */ new Map());
93
+ }
94
+ async getByUrl(url2) {
95
+ const id = this.urlToIdMap.get(url2);
96
+ if (!id) return void 0;
97
+ return this.resourceCache.get(id);
98
+ }
99
+ hasUrlMatch(url2) {
100
+ if (!this.urlToIdMap.get(url2)) return false;
101
+ return true;
102
+ }
103
+ async getById(id) {
104
+ return this.resourceCache.get(id);
105
+ }
106
+ async get(ref) {
107
+ if (this.resourceCache.has(ref)) {
108
+ return this.resourceCache.get(ref);
109
+ }
110
+ const id = this.urlToIdMap.get(ref);
111
+ if (id) {
112
+ return this.resourceCache.get(id);
113
+ }
114
+ return void 0;
115
+ }
116
+ async length() {
117
+ return this.resourceCache.size;
118
+ }
119
+ async set(url2, resource) {
120
+ const id = resource == null ? void 0 : resource["@id"];
121
+ if (!id) {
122
+ console.warn("[CacheManager] Resource has no @id", resource);
123
+ return;
124
+ }
125
+ this.resourceCache.set(id, resource);
126
+ this.urlToIdMap.set(url2, id);
127
+ }
128
+ async linkUrlWithId(url2, emptyResource) {
129
+ if (!isUrlOrRelativePath(url2)) return;
130
+ if (this.hasUrlMatch(url2)) return;
131
+ await this.set(url2, emptyResource);
132
+ }
133
+ async has(urlOrId) {
134
+ if (this.resourceCache.has(urlOrId)) return true;
135
+ const id = this.urlToIdMap.get(urlOrId);
136
+ return id ? this.resourceCache.has(id) : false;
137
+ }
138
+ async getIdByUrl(url2) {
139
+ return this.urlToIdMap.get(url2);
140
+ }
141
+ async clear() {
142
+ this.resourceCache.clear();
143
+ this.urlToIdMap.clear();
144
+ }
145
+ async delete(idOrUrl) {
146
+ if (this.resourceCache.has(idOrUrl)) {
147
+ this.resourceCache.delete(idOrUrl);
148
+ for (const [url2, id2] of this.urlToIdMap.entries()) {
149
+ if (id2 === idOrUrl) {
150
+ this.urlToIdMap.delete(url2);
151
+ break;
152
+ }
153
+ }
154
+ return true;
155
+ }
156
+ const id = this.urlToIdMap.get(idOrUrl);
157
+ if (id && this.resourceCache.has(id)) {
158
+ this.resourceCache.delete(id);
159
+ this.urlToIdMap.delete(idOrUrl);
160
+ return true;
161
+ }
162
+ return false;
163
+ }
164
+ }
165
+ class DataspaceConnectorStore {
166
+ constructor(config) {
167
+ __publicField(this, "cache");
168
+ __publicField(this, "session");
169
+ __publicField(this, "headers");
170
+ __publicField(this, "config");
171
+ __publicField(this, "authToken", null);
172
+ __publicField(this, "contractNegotiations", /* @__PURE__ */ new Map());
173
+ __publicField(this, "transferProcesses", /* @__PURE__ */ new Map());
174
+ var _a2, _b;
175
+ this.validateConfig(config);
176
+ this.config = config;
177
+ this.cache = ((_a2 = config.options) == null ? void 0 : _a2.cacheManager) ?? new InMemoryCacheManager();
178
+ this.session = (_b = config.options) == null ? void 0 : _b.session;
179
+ this.headers = {
180
+ "Content-Type": "application/json",
181
+ Accept: "application/json"
182
+ };
183
+ }
184
+ validateConfig(config) {
185
+ const required = [
186
+ "catalogEndpoint",
187
+ "contractNegotiationEndpoint",
188
+ "transferProcessEndpoint",
189
+ "authMethod"
190
+ ];
191
+ const missing = required.filter((field) => !config[field]);
192
+ if (missing.length > 0) {
193
+ throw new Error(`Missing required configuration: ${missing.join(", ")}`);
194
+ }
195
+ }
196
+ async getData(args) {
197
+ if ("targetType" in args) {
198
+ return await this.getCatalog(args.targetType);
199
+ }
200
+ return await this.get(args.id, args.serverPagination, args.serverSearch);
201
+ }
202
+ async get(id, _serverPagination, _serverSearch) {
203
+ const cached = await this.cache.get(id);
204
+ if (cached) return cached;
205
+ try {
206
+ const resource = await this.fetchThroughDataspace(id);
207
+ if (resource) {
208
+ await this.cacheResource(id, resource);
209
+ }
210
+ return resource;
211
+ } catch (error2) {
212
+ console.error(`Failed to fetch resource ${id}:`, error2);
213
+ return null;
214
+ }
215
+ }
216
+ async getCatalog(counterPartyAddress) {
217
+ await this.ensureAuthenticated();
218
+ const catalogRequest = this.buildV3CatalogRequest(counterPartyAddress);
219
+ console.log("Sending v3 catalog request:", JSON.stringify(catalogRequest, null, 2));
220
+ const response = await this.fetchAuthn(this.config.catalogEndpoint, {
221
+ method: "POST",
222
+ headers: this.headers,
223
+ body: JSON.stringify(catalogRequest)
224
+ });
225
+ if (!response.ok) {
226
+ console.error(`Catalog request failed: ${response.status} ${response.statusText}`);
227
+ const errorText = await response.text();
228
+ console.error("Error response:", errorText);
229
+ return null;
230
+ }
231
+ const catalog = await response.json();
232
+ if (catalog["@id"]) {
233
+ await this.cache.set(catalog["@id"], catalog);
234
+ }
235
+ if (catalog["dcat:dataset"] && Array.isArray(catalog["dcat:dataset"])) {
236
+ for (const dataset2 of catalog["dcat:dataset"]) {
237
+ if (dataset2["@id"]) {
238
+ await this.cache.set(dataset2["@id"], dataset2);
239
+ }
240
+ }
241
+ }
242
+ return catalog;
243
+ }
244
+ async negotiateContract(counterPartyAddress, _offerId, policy, counterPartyId) {
245
+ await this.ensureAuthenticated();
246
+ const negotiationRequest = {
247
+ "@context": {
248
+ "@vocab": "https://w3id.org/edc/v0.0.1/ns/"
249
+ },
250
+ "@type": "ContractRequest",
251
+ counterPartyAddress,
252
+ counterPartyId,
253
+ protocol: "dataspace-protocol-http",
254
+ policy: {
255
+ "@context": "http://www.w3.org/ns/odrl.jsonld",
256
+ "@id": policy["@id"],
257
+ "@type": "Offer",
258
+ assigner: counterPartyId || "provider",
259
+ target: policy.target
260
+ }
261
+ };
262
+ const response = await this.fetchAuthn(this.config.contractNegotiationEndpoint, {
263
+ method: "POST",
264
+ headers: this.headers,
265
+ body: JSON.stringify(negotiationRequest)
266
+ });
267
+ if (!response.ok) {
268
+ const errorText = await response.text();
269
+ console.error(`Contract negotiation failed: ${response.status} ${response.statusText}`, errorText);
270
+ throw new Error(`Contract negotiation failed: ${response.status} ${response.statusText} - ${errorText}`);
271
+ }
272
+ const negotiation = await response.json();
273
+ const negotiationId = negotiation["@id"];
274
+ this.contractNegotiations.set(negotiationId, negotiation);
275
+ return negotiationId;
276
+ }
277
+ initiateNegotiation(counterPartyAddress, assetId, policy, counterPartyId) {
278
+ return this.negotiateContract(counterPartyAddress, assetId, policy, counterPartyId);
279
+ }
280
+ getNegotiationStatus(negotiationId) {
281
+ return this._getNegotiationStatus(negotiationId);
282
+ }
283
+ async initiateTransfer(counterPartyAddress, contractId, dataDestination) {
284
+ await this.ensureAuthenticated();
285
+ const transferRequest = {
286
+ "@context": [
287
+ "https://w3id.org/edc/v0.0.1/ns/",
288
+ "https://w3id.org/dspace/2024/1/context.json"
289
+ ],
290
+ "@type": "https://w3id.org/edc/v0.0.1/ns/TransferRequestMessage",
291
+ counterPartyAddress,
292
+ contractId,
293
+ dataDestination
294
+ };
295
+ const response = await this.fetchAuthn(this.config.transferProcessEndpoint, {
296
+ method: "POST",
297
+ headers: this.headers,
298
+ body: JSON.stringify(transferRequest)
299
+ });
300
+ if (!response.ok) {
301
+ throw new Error(`Transfer initiation failed: ${response.status} ${response.statusText}`);
302
+ }
303
+ const transfer = await response.json();
304
+ const transferId = transfer["@id"];
305
+ this.transferProcesses.set(transferId, transfer);
306
+ return transferId;
307
+ }
308
+ async fetchThroughDataspace(resourceId) {
309
+ try {
310
+ console.log(`Fetching resource through dataspace: ${resourceId}`);
311
+ const catalog = await this.getCatalog();
312
+ if (!catalog) {
313
+ console.error("No catalog available");
314
+ return null;
315
+ }
316
+ console.log("Catalog received:", catalog);
317
+ const dataset2 = this.findDatasetInCatalog(catalog, resourceId);
318
+ if (!dataset2) {
319
+ console.error(`Dataset ${resourceId} not found in catalog`);
320
+ return null;
321
+ }
322
+ console.log("Dataset found:", dataset2);
323
+ return catalog;
324
+ } catch (error2) {
325
+ console.error("Dataspace fetch failed:", error2);
326
+ return null;
327
+ }
328
+ }
329
+ findDatasetInCatalog(catalog, resourceId) {
330
+ const datasets = catalog["dcat:dataset"] || [];
331
+ return datasets.find((dataset2) => {
332
+ var _a2;
333
+ return dataset2["@id"] === resourceId || ((_a2 = dataset2["dcat:distribution"]) == null ? void 0 : _a2.some((dist) => dist["@id"] === resourceId));
334
+ }) || null;
335
+ }
336
+ async _getNegotiationStatus(negotiationId) {
337
+ const response = await this.fetchAuthn(`${this.config.contractNegotiationEndpoint}/${negotiationId}`, {
338
+ method: "GET",
339
+ headers: this.headers
340
+ });
341
+ return response.json();
342
+ }
343
+ async ensureAuthenticated() {
344
+ if (this.authToken && this.headers) return;
345
+ switch (this.config.authMethod) {
346
+ case "edc-api-key":
347
+ if (!this.config.edcApiKey) {
348
+ throw new Error("EDC API key required but not provided. Set edcApiKey in configuration.");
349
+ }
350
+ this.authToken = this.config.edcApiKey;
351
+ this.headers = {
352
+ ...this.headers,
353
+ "X-Api-Key": this.authToken
354
+ };
355
+ break;
356
+ case "bearer":
357
+ if (!this.config.bearerToken) {
358
+ throw new Error("Bearer token required but not provided");
359
+ }
360
+ this.authToken = this.config.bearerToken;
361
+ this.headers = {
362
+ ...this.headers,
363
+ Authorization: `Bearer ${this.authToken}`
364
+ };
365
+ break;
366
+ case "oauth2":
367
+ this.authToken = await this.getOAuth2Token();
368
+ this.headers = {
369
+ ...this.headers,
370
+ Authorization: `Bearer ${this.authToken}`
371
+ };
372
+ break;
373
+ case "delegated":
374
+ if (!this.config.delegatedAuthConfig) {
375
+ throw new Error("Delegated auth config required but not provided");
376
+ }
377
+ this.authToken = await this.getDelegatedAuthToken();
378
+ this.headers = {
379
+ ...this.headers,
380
+ Authorization: `Bearer ${this.authToken}`
381
+ };
382
+ break;
383
+ }
384
+ }
385
+ async getOAuth2Token() {
386
+ if (!this.config.oauth2Config) {
387
+ throw new Error("OAuth2 config required");
388
+ }
389
+ const { tokenEndpoint, clientId, clientSecret, scope } = this.config.oauth2Config;
390
+ const body = new URLSearchParams({
391
+ grant_type: "client_credentials",
392
+ client_id: clientId,
393
+ client_secret: clientSecret
394
+ });
395
+ if (scope) {
396
+ body.append("scope", scope);
397
+ }
398
+ const response = await fetch(tokenEndpoint, {
399
+ method: "POST",
400
+ headers: {
401
+ "Content-Type": "application/x-www-form-urlencoded"
402
+ },
403
+ body
404
+ });
405
+ if (!response.ok) {
406
+ throw new Error(`OAuth2 token request failed: ${response.status}`);
407
+ }
408
+ const data = await response.json();
409
+ return data.access_token;
410
+ }
411
+ async getDelegatedAuthToken() {
412
+ if (!this.config.delegatedAuthConfig) {
413
+ throw new Error("Delegated auth config required");
414
+ }
415
+ const { identityProviderEndpoint, clientId, clientSecret } = this.config.delegatedAuthConfig;
416
+ if (!clientId || !clientSecret) {
417
+ throw new Error("Client ID and secret required for delegated authentication");
418
+ }
419
+ const body = new URLSearchParams({
420
+ grant_type: "client_credentials",
421
+ client_id: clientId,
422
+ client_secret: clientSecret
423
+ });
424
+ const response = await fetch(identityProviderEndpoint, {
425
+ method: "POST",
426
+ headers: {
427
+ "Content-Type": "application/x-www-form-urlencoded"
428
+ },
429
+ body
430
+ });
431
+ if (!response.ok) {
432
+ throw new Error(`Delegated auth token request failed: ${response.status}`);
433
+ }
434
+ const data = await response.json();
435
+ return data.access_token;
436
+ }
437
+ buildV3CatalogRequest(counterPartyAddress) {
438
+ const apiVersion = this.config.apiVersion || "v3";
439
+ if (apiVersion === "v3") {
440
+ return {
441
+ "@context": {
442
+ "@vocab": "https://w3id.org/edc/v0.0.1/ns/",
443
+ edc: "https://w3id.org/edc/v0.0.1/ns/",
444
+ dcat: "https://www.w3.org/ns/dcat#",
445
+ dct: "https://purl.org/dc/terms/",
446
+ odrl: "http://www.w3.org/ns/odrl/2/"
447
+ },
448
+ "@type": "CatalogRequestMessage",
449
+ counterPartyAddress: counterPartyAddress || this.getProtocolEndpoint(),
450
+ protocol: "dataspace-protocol-http"
451
+ };
452
+ }
453
+ return {
454
+ "@context": [
455
+ "https://w3id.org/edc/v0.0.1/ns/",
456
+ "https://w3id.org/dspace/2024/1/context.json"
457
+ ],
458
+ "@type": "https://w3id.org/edc/v0.0.1/ns/CatalogRequestMessage",
459
+ counterPartyAddress: counterPartyAddress || this.config.endpoint || "",
460
+ protocol: "dataspace-protocol-http"
461
+ };
462
+ }
463
+ getProtocolEndpoint() {
464
+ if (this.config.endpoint) {
465
+ const baseUrl = this.config.endpoint.replace("/management", "");
466
+ return `${baseUrl}/protocol`;
467
+ }
468
+ return this.config.endpoint || "";
469
+ }
470
+ async getAssets(querySpec) {
471
+ await this.ensureAuthenticated();
472
+ const apiVersion = this.config.apiVersion || "v3";
473
+ const assetsEndpoint = this.config.assetsEndpoint || this.config.catalogEndpoint.replace("/catalog/request", apiVersion === "v3" ? "/assets/request" : "/assets");
474
+ const requestBody = querySpec || this.buildV3QuerySpec();
475
+ const method = apiVersion === "v3" ? "POST" : "GET";
476
+ const requestOptions = {
477
+ method,
478
+ headers: this.headers
479
+ };
480
+ if (method === "POST") {
481
+ requestOptions.body = JSON.stringify(requestBody);
482
+ }
483
+ const response = await this.fetchAuthn(assetsEndpoint, requestOptions);
484
+ if (!response.ok) {
485
+ console.error(`Assets request failed: ${response.status} ${response.statusText}`);
486
+ const errorText = await response.text();
487
+ console.error("Error response:", errorText);
488
+ return [];
489
+ }
490
+ const assets = await response.json();
491
+ const assetsArray = Array.isArray(assets) ? assets : [];
492
+ for (const asset of assetsArray) {
493
+ if (asset["@id"]) {
494
+ await this.cache.set(asset["@id"], asset);
495
+ }
496
+ }
497
+ return assetsArray;
498
+ }
499
+ async getPolicyDefinitions(querySpec) {
500
+ await this.ensureAuthenticated();
501
+ const apiVersion = this.config.apiVersion || "v3";
502
+ const policiesEndpoint = this.config.policiesEndpoint || this.config.catalogEndpoint.replace("/catalog/request", apiVersion === "v3" ? "/policydefinitions/request" : "/policydefinitions");
503
+ const requestBody = querySpec || this.buildV3QuerySpec();
504
+ const method = apiVersion === "v3" ? "POST" : "GET";
505
+ const requestOptions = {
506
+ method,
507
+ headers: this.headers
508
+ };
509
+ if (method === "POST") {
510
+ requestOptions.body = JSON.stringify(requestBody);
511
+ }
512
+ const response = await this.fetchAuthn(policiesEndpoint, requestOptions);
513
+ if (!response.ok) {
514
+ console.error(`Policy definitions request failed: ${response.status} ${response.statusText}`);
515
+ const errorText = await response.text();
516
+ console.error("Error response:", errorText);
517
+ return [];
518
+ }
519
+ const policies = await response.json();
520
+ const policiesArray = Array.isArray(policies) ? policies : [];
521
+ for (const policy of policiesArray) {
522
+ if (policy["@id"]) {
523
+ await this.cache.set(policy["@id"], policy);
524
+ }
525
+ }
526
+ return policiesArray;
527
+ }
528
+ async getContractDefinitions(querySpec) {
529
+ await this.ensureAuthenticated();
530
+ const apiVersion = this.config.apiVersion || "v3";
531
+ const contractDefsEndpoint = this.config.contractDefinitionsEndpoint || this.config.catalogEndpoint.replace("/catalog/request", apiVersion === "v3" ? "/contractdefinitions/request" : "/contractdefinitions");
532
+ const requestBody = querySpec || this.buildV3QuerySpec();
533
+ const method = apiVersion === "v3" ? "POST" : "GET";
534
+ const requestOptions = {
535
+ method,
536
+ headers: this.headers
537
+ };
538
+ if (method === "POST") {
539
+ requestOptions.body = JSON.stringify(requestBody);
540
+ }
541
+ const response = await this.fetchAuthn(contractDefsEndpoint, requestOptions);
542
+ if (!response.ok) {
543
+ console.error(`Contract definitions request failed: ${response.status} ${response.statusText}`);
544
+ const errorText = await response.text();
545
+ console.error("Error response:", errorText);
546
+ return [];
547
+ }
548
+ const contracts = await response.json();
549
+ const contractsArray = Array.isArray(contracts) ? contracts : [];
550
+ for (const contract of contractsArray) {
551
+ if (contract["@id"]) {
552
+ await this.cache.set(contract["@id"], contract);
553
+ }
554
+ }
555
+ return contractsArray;
556
+ }
557
+ buildV3QuerySpec(offset = 0, limit = 50) {
558
+ return {
559
+ "@context": {
560
+ "@vocab": "https://w3id.org/edc/v0.0.1/ns/",
561
+ edc: "https://w3id.org/edc/v0.0.1/ns/"
562
+ },
563
+ "@type": "QuerySpec",
564
+ offset,
565
+ limit,
566
+ filterExpression: [],
567
+ sortField: null,
568
+ sortOrder: "ASC"
569
+ };
570
+ }
571
+ async fetchAuthn(iri, options) {
572
+ await this.ensureAuthenticated();
573
+ return fetch(iri, {
574
+ ...options,
575
+ headers: {
576
+ ...this.headers,
577
+ ...options.headers
578
+ },
579
+ mode: "cors"
580
+ });
581
+ }
582
+ async post(_resource, _id, _skipFetch) {
583
+ await Promise.resolve();
584
+ throw new Error("POST not implemented for DataspaceConnectorStore");
585
+ }
586
+ async put(_resource, _id, _skipFetch) {
587
+ await Promise.resolve();
588
+ throw new Error("PUT not implemented for DataspaceConnectorStore");
589
+ }
590
+ async patch(_resource, _id, _skipFetch) {
591
+ await Promise.resolve();
592
+ throw new Error("PATCH not implemented for DataspaceConnectorStore");
593
+ }
594
+ delete(_id, _context) {
595
+ throw new Error("DELETE not implemented for DataspaceConnectorStore");
596
+ }
597
+ async clearCache(id) {
598
+ await this.cache.delete(id);
599
+ }
600
+ async cacheResource(key, resourceProxy) {
601
+ await this.cache.set(key, resourceProxy);
602
+ }
603
+ _getLanguage() {
604
+ return localStorage.getItem("language") || "en";
605
+ }
606
+ selectLanguage(selectedLanguageCode) {
607
+ localStorage.setItem("language", selectedLanguageCode);
608
+ }
609
+ subscribeResourceTo(_resourceId, _nestedResourceId) {
610
+ }
611
+ getExpandedPredicate(property, _context) {
612
+ return property;
613
+ }
614
+ }
615
+ const _DataspaceConnectorStoreAdapter = class _DataspaceConnectorStoreAdapter {
616
+ constructor() {
617
+ }
618
+ static getStoreInstance(cfg) {
619
+ if (!_DataspaceConnectorStoreAdapter.store) {
620
+ if (!cfg) {
621
+ throw new Error("DataspaceConnectorStore configuration is required");
622
+ }
623
+ _DataspaceConnectorStoreAdapter.store = new DataspaceConnectorStore(cfg);
624
+ }
625
+ return _DataspaceConnectorStoreAdapter.store;
626
+ }
627
+ };
628
+ __publicField(_DataspaceConnectorStoreAdapter, "store");
629
+ let DataspaceConnectorStoreAdapter = _DataspaceConnectorStoreAdapter;
630
+ class FederatedCatalogueAPIWrapper {
631
+ constructor(options, fcBaseUrl) {
632
+ __publicField(this, "fcBaseUrl");
633
+ __publicField(this, "connect");
634
+ this.fcBaseUrl = fcBaseUrl;
635
+ const connection = this.firstConnect(options);
636
+ this.connect = () => connection;
637
+ }
638
+ async firstConnect(options) {
639
+ const body = new URLSearchParams({
640
+ grant_type: options.kc_grant_type,
641
+ client_id: options.kc_client_id,
642
+ client_secret: options.kc_client_secret,
643
+ scope: options.kc_scope,
644
+ username: options.kc_username,
645
+ password: options.kc_password
646
+ });
647
+ const headers = new Headers({
648
+ "Content-Type": "application/x-www-form-urlencoded"
649
+ });
650
+ const response = await fetch(options.kc_url, {
651
+ method: "POST",
652
+ headers,
653
+ body
654
+ });
655
+ const data = await response.json();
656
+ const token = data.access_token;
657
+ if (token == null) {
658
+ throw new Error("connexion fails", {
659
+ cause: data
660
+ });
661
+ }
662
+ return token;
663
+ }
664
+ async getAllSelfDescriptions() {
665
+ console.log("Fetching all self-descriptions from Federated Catalogue...", this.fcBaseUrl);
666
+ const token = await this.connect();
667
+ console.log("Token received:", token);
668
+ const url2 = `${this.fcBaseUrl}/self-descriptions`;
669
+ const headers = new Headers({
670
+ Authorization: `Bearer ${token}`
671
+ });
672
+ const response = await fetch(url2, {
673
+ headers
674
+ });
675
+ console.log("Response status:", response.status);
676
+ return await response.json();
677
+ }
678
+ async getSelfDescriptionByHash(sdHash) {
679
+ const token = await this.connect();
680
+ const url2 = `${this.fcBaseUrl}/self-descriptions/${sdHash}`;
681
+ const headers = new Headers({
682
+ Authorization: `Bearer ${token}`
683
+ });
684
+ const response = await fetch(url2, {
685
+ method: "GET",
686
+ headers
687
+ });
688
+ if (!response.ok) throw new Error(`GET /self-descriptions/${sdHash} failed: ${response.status} ${response.statusText}`, {
689
+ cause: response
690
+ });
691
+ return await response.json();
692
+ }
693
+ async postQuery(statement, parameters = {}) {
694
+ const token = await this.connect();
695
+ const url2 = `${this.fcBaseUrl}/query`;
696
+ const headers = new Headers({
697
+ Authorization: `Bearer ${token}`,
698
+ "Content-Type": "application/json"
699
+ });
700
+ const body = JSON.stringify({
701
+ statement,
702
+ parameters
703
+ });
704
+ const response = await fetch(url2, {
705
+ method: "POST",
706
+ headers,
707
+ body
708
+ });
709
+ if (!response.ok) {
710
+ throw new Error(`[ERROR] POST /query failed: ${response.status} ${response.statusText}`, {
711
+ cause: response
712
+ });
713
+ }
714
+ return await response.json();
715
+ }
716
+ async postQuerySearch(statement, parameters = {}, queryLanguage = "OPENCYPHER", annotations) {
717
+ const token = await this.connect();
718
+ const url2 = `${this.fcBaseUrl}/query/search`;
719
+ const headers = new Headers({
720
+ Authorization: `Bearer ${token}`,
721
+ "Content-Type": "application/json"
722
+ });
723
+ const body = JSON.stringify({
724
+ statement,
725
+ parameters,
726
+ annotations: annotations || {
727
+ queryLanguage
728
+ }
729
+ });
730
+ const response = await fetch(url2, {
731
+ method: "POST",
732
+ headers,
733
+ body
734
+ });
735
+ if (!response.ok) {
736
+ throw new Error(`[ERROR] POST /query/search failed: ${response.status} ${response.statusText}`, {
737
+ cause: response
738
+ });
739
+ }
740
+ return await response.json();
741
+ }
742
+ }
743
+ function getFederatedCatalogueAPIWrapper(baseUrl, optionLogin, optionsServer) {
744
+ const options = Object.assign({}, optionsServer, optionLogin);
745
+ return new FederatedCatalogueAPIWrapper(options, baseUrl);
746
+ }
747
+ class FederatedCatalogueStore {
748
+ constructor(cfg) {
749
+ __publicField(this, "cache");
750
+ __publicField(this, "session");
751
+ __publicField(this, "fcApi");
752
+ this.cfg = cfg;
753
+ if (!this.cfg.login) {
754
+ throw new Error("Login must be provided for FederatedCatalogueStore");
755
+ }
756
+ if (!this.cfg.endpoint) {
757
+ throw new Error("Missing required `endpoint` in StoreConfig for FederatedCatalogueStore");
758
+ }
759
+ if (!this.cfg.optionsServer) {
760
+ throw new Error("Missing required `optionsServer` in StoreConfig for FederatedCatalogueStore");
761
+ }
762
+ this.fcApi = getFederatedCatalogueAPIWrapper(this.cfg.endpoint, this.cfg.login, this.cfg.optionsServer);
763
+ this.cache = new InMemoryCacheManager();
764
+ }
765
+ async getData(args) {
766
+ const targetType = "targetType" in args ? args.targetType : args.id;
767
+ if (!this.fcApi) {
768
+ throw new Error("Federated API not initialized, returning empty data.");
769
+ }
770
+ let resource = await this.get(targetType);
771
+ if (!resource || resource["ldp:contains"].length === 0) {
772
+ resource = await this.initLocalDataSourceContainer(targetType);
773
+ const dataset2 = await this.fcApi.getAllSelfDescriptions();
774
+ for (const item in dataset2.items) {
775
+ const sd = await this.fcApi.getSelfDescriptionByHash(dataset2.items[item].meta.sdHash);
776
+ if (sd) {
777
+ const mappedResource = this.mapSourceToDestination(sd, {
778
+ temsServiceBase: this.cfg.temsServiceBase,
779
+ temsCategoryBase: this.cfg.temsCategoryBase,
780
+ temsImageBase: this.cfg.temsImageBase,
781
+ temsProviderBase: this.cfg.temsProviderBase
782
+ });
783
+ resource["ldp:contains"].push(mappedResource);
784
+ }
785
+ }
786
+ this.setLocalData(resource, targetType);
787
+ }
788
+ document.dispatchEvent(new CustomEvent("save", {
789
+ detail: {
790
+ resource: {
791
+ "@id": resource["@id"]
792
+ }
793
+ },
794
+ bubbles: true
795
+ }));
796
+ return resource;
797
+ }
798
+ async initLocalDataSourceContainer(dataSrc = "", containerType = "default") {
799
+ var _a2;
800
+ const endpointHash = ((_a2 = this.cfg.endpoint) == null ? void 0 : _a2.replace(/[^a-zA-Z0-9]/g, "")) || "unknown";
801
+ const idField = `fc-${endpointHash}-${containerType}`;
802
+ if (!dataSrc) {
803
+ dataSrc = `store://local.${idField}/`;
804
+ }
805
+ const localContainer = {
806
+ "@context": "https://cdn.startinblox.com/owl/context.jsonld",
807
+ "@type": "ldp:Container",
808
+ "@id": dataSrc,
809
+ "ldp:contains": new Array(),
810
+ permissions: [
811
+ "view"
812
+ ]
813
+ };
814
+ await this.setLocalData(localContainer, dataSrc);
815
+ return localContainer;
816
+ }
817
+ async get(id, _serverPagination, _serverSearch) {
818
+ try {
819
+ const resource = await this.cache.get(id);
820
+ return resource || null;
821
+ } catch (error2) {
822
+ console.error(`[FederatedCatalogueStore] Error getting resource ${id}:`, error2);
823
+ return null;
824
+ }
825
+ }
826
+ post(_resource, _id, _skipFetch) {
827
+ return Promise.resolve(null);
828
+ }
829
+ put(_resource, _id, _skipFetch) {
830
+ return Promise.resolve(null);
831
+ }
832
+ patch(_resource, _id, _skipFetch) {
833
+ return Promise.resolve(null);
834
+ }
835
+ delete(_id, _context) {
836
+ return Promise.resolve(null);
837
+ }
838
+ async clearCache(id) {
839
+ try {
840
+ if (await this.cache.has(id)) {
841
+ await this.cache.delete(id);
842
+ console.log(`[FederatedCatalogueStore] Cleared cache for ${id}`);
843
+ }
844
+ } catch (error2) {
845
+ console.error(`[FederatedCatalogueStore] Error clearing cache for ${id}:`, error2);
846
+ }
847
+ }
848
+ async cacheResource(key, resourceProxy) {
849
+ try {
850
+ await this.cache.set(key, resourceProxy);
851
+ console.log(`[FederatedCatalogueStore] Cached resource ${key}`);
852
+ } catch (error2) {
853
+ console.error(`[FederatedCatalogueStore] Error caching resource ${key}:`, error2);
854
+ }
855
+ }
856
+ _getLanguage() {
857
+ return "";
858
+ }
859
+ selectLanguage(_selectedLanguageCode) {
860
+ }
861
+ getExpandedPredicate(_property, _context) {
862
+ return null;
863
+ }
864
+ subscribeResourceTo(_resourceId, _nestedResourceId) {
865
+ }
866
+ fetchAuthn(_iri, _options) {
867
+ return Promise.resolve({});
868
+ }
869
+ async setLocalData(resource, id, _skipFetch) {
870
+ try {
871
+ const resourceWithId = {
872
+ ...resource,
873
+ "@id": id
874
+ };
875
+ await this.cache.set(id, resourceWithId);
876
+ console.log(`[FederatedCatalogueStore] Stored local data for ${id}`);
877
+ this.notifyComponents(id, resourceWithId);
878
+ return id;
879
+ } catch (error2) {
880
+ console.error(`[FederatedCatalogueStore] Error storing local data for ${id}:`, error2);
881
+ return null;
882
+ }
883
+ }
884
+ notifyComponents(id, resource) {
885
+ document.dispatchEvent(new CustomEvent("resoureReady", {
886
+ detail: {
887
+ id,
888
+ resource,
889
+ fetchedResource: resource
890
+ },
891
+ bubbles: true
892
+ }));
893
+ }
894
+ mapSourceToDestination(src, opts) {
895
+ var _a2, _b, _c, _d, _e, _f, _g, _h;
896
+ const vc = src.verifiableCredential;
897
+ const cs = vc.credentialSubject;
898
+ let catInfo;
899
+ let usedKey;
900
+ let type;
901
+ if (cs["dcat:service"]) {
902
+ catInfo = cs["dcat:service"];
903
+ usedKey = "service";
904
+ type = "tems:Service";
905
+ } else if (cs["dcat:dataset"] && cs["dcat:dataset"].length > 0) {
906
+ catInfo = cs["dcat:dataset"][0];
907
+ usedKey = "dataset";
908
+ type = "tems:DataOffer";
909
+ } else {
910
+ throw new Error("Expected either credentialSubject['dcat:service'] or a non-empty array in ['dcat:dataset']");
911
+ }
912
+ const resourceId = cs["@id"];
913
+ const slug = resourceId.split("/").pop() || "unknown";
914
+ const serviceId = `${opts.temsServiceBase}${encodeURIComponent(slug)}/`;
915
+ const creation_date = vc.issuanceDate;
916
+ const update_date = vc.expirationDate;
917
+ const name = catInfo["dcterms:title"];
918
+ const description = catInfo["rdfs:comment"];
919
+ const keywords = catInfo["dcat:keyword"] || [];
920
+ const long_description = keywords.length > 0 ? `Keywords: ${keywords.join(", ")}` : "";
921
+ const categories = {
922
+ "@id": `${serviceId}categories/`,
923
+ "@type": "ldp:Container",
924
+ "ldp:contains": keywords.map((kw) => ({
925
+ "@id": `${opts.temsCategoryBase}${encodeURIComponent(kw)}/`,
926
+ "@type": "tems:Category",
927
+ name: kw
928
+ }))
929
+ };
930
+ const endpointURL = catInfo["dcat:endpointURL"] || "";
931
+ const hasEndpoint = endpointURL.trim().length > 0;
932
+ const activation_status = hasEndpoint;
933
+ const is_in_app = hasEndpoint;
934
+ const is_external = hasEndpoint;
935
+ const is_api = hasEndpoint;
936
+ const imageUrls = [];
937
+ if ((_a2 = catInfo["foaf:thumbnail"]) == null ? void 0 : _a2["rdf:resource"]) {
938
+ imageUrls.push(catInfo["foaf:thumbnail"]["rdf:resource"]);
939
+ }
940
+ if ((_c = (_b = catInfo["dcterms:creator"]) == null ? void 0 : _b["foaf:thumbnail"]) == null ? void 0 : _c["rdf:resource"]) {
941
+ imageUrls.push(catInfo["dcterms:creator"]["foaf:thumbnail"]["rdf:resource"]);
942
+ }
943
+ const images = {
944
+ "@id": `${serviceId}images/`,
945
+ "@type": "ldp:Container",
946
+ "ldp:contains": imageUrls.map((url2) => ({
947
+ "@id": `${opts.temsImageBase}${encodeURIComponent(url2.split("/").pop() || "0")}/`,
948
+ url: url2,
949
+ iframe: false,
950
+ name: url2.split("/").pop() || "image",
951
+ "@type": "tems:Image"
952
+ }))
953
+ };
954
+ const contact_url = catInfo["dcat:endpointDescription"] || "";
955
+ const documentation_url = contact_url || "";
956
+ let service_url = catInfo["dcat:endpointURL"] || "";
957
+ if (service_url.includes("demo.isan.org")) service_url = new URL(service_url).origin;
958
+ let providerRef;
959
+ if (usedKey === "service") {
960
+ providerRef = ((_d = cs["gax-core:operatedBy"]) == null ? void 0 : _d["@id"]) || "";
961
+ } else {
962
+ providerRef = ((_e = cs["gax-core:offeredBy"]) == null ? void 0 : _e["@id"]) || "";
963
+ }
964
+ const providerSlug = providerRef.split(":").pop() + String(Math.random()) || "0";
965
+ const providerLogo = ((_g = (_f = catInfo["dcterms:creator"]) == null ? void 0 : _f["foaf:thumbnail"]) == null ? void 0 : _g["rdf:resource"]) || "";
966
+ const provider = {
967
+ "@id": `${opts.temsProviderBase}${encodeURIComponent(providerSlug)}/`,
968
+ "@type": "tems:Provider",
969
+ name: ((_h = catInfo["dcterms:creator"]) == null ? void 0 : _h["foaf:name"]) || "",
970
+ image: {
971
+ "@id": `${opts.temsImageBase}${encodeURIComponent(providerLogo.split("/").pop() || "0")}/`,
972
+ "@type": "tems:Image",
973
+ iframe: false,
974
+ url: providerLogo,
975
+ name: providerLogo.split("/").pop() || "provider-logo"
976
+ }
977
+ };
978
+ const data_offers = [];
979
+ const dest = {
980
+ "@id": serviceId,
981
+ creation_date,
982
+ update_date,
983
+ name,
984
+ description,
985
+ long_description,
986
+ categories,
987
+ activation_status,
988
+ activation_date: null,
989
+ licence: null,
990
+ is_in_app,
991
+ is_external,
992
+ is_api,
993
+ images,
994
+ release_date: null,
995
+ last_update: null,
996
+ developper: null,
997
+ contact_url,
998
+ documentation_url,
999
+ url: service_url,
1000
+ provider,
1001
+ data_offers,
1002
+ "@type": type
1003
+ };
1004
+ return dest;
1005
+ }
1006
+ }
1007
+ const _FederatedCatalogueStoreAdapter = class _FederatedCatalogueStoreAdapter {
1008
+ constructor() {
1009
+ }
1010
+ static validateConfiguration(cfg) {
1011
+ const requiredFields = [
1012
+ "temsServiceBase",
1013
+ "temsCategoryBase",
1014
+ "temsImageBase",
1015
+ "temsProviderBase"
1016
+ ];
1017
+ const missingFields = requiredFields.filter((field) => !cfg[field]);
1018
+ if (missingFields.length > 0) {
1019
+ throw new Error(`[FederatedCatalogueStoreAdapter] Missing required configuration fields: ${missingFields.join(", ")}`);
1020
+ }
1021
+ }
1022
+ static getStoreInstance(cfg) {
1023
+ if (!_FederatedCatalogueStoreAdapter.store) {
1024
+ if (!cfg) {
1025
+ throw new Error("[FederatedCatalogueStoreAdapter] configuration is required");
1026
+ }
1027
+ _FederatedCatalogueStoreAdapter.validateConfiguration(cfg);
1028
+ _FederatedCatalogueStoreAdapter.store = new FederatedCatalogueStore(cfg);
1029
+ }
1030
+ return _FederatedCatalogueStoreAdapter.store;
1031
+ }
1032
+ };
1033
+ __publicField(_FederatedCatalogueStoreAdapter, "store");
1034
+ let FederatedCatalogueStoreAdapter = _FederatedCatalogueStoreAdapter;
89
1035
  var lib = {};
90
1036
  var IdentifierIssuer_1;
91
1037
  var hasRequiredIdentifierIssuer;
@@ -8449,105 +9395,29 @@ let __tla = (async () => {
8449
9395
  for (m in messages) {
8450
9396
  if (Object.prototype.hasOwnProperty.call(messages, m)) {
8451
9397
  message = messages[m];
8452
- if (isToken && message[value]) {
8453
- delete message[value];
8454
- result = value;
8455
- break;
8456
- }
8457
- if (isFunction) {
8458
- for (t in message) {
8459
- if (Object.prototype.hasOwnProperty.call(message, t) && message[t] === value) {
8460
- delete message[t];
8461
- result = true;
8462
- }
8463
- }
8464
- }
8465
- }
8466
- }
8467
- return result;
8468
- };
8469
- });
8470
- })(pubsub$1, pubsub$1.exports);
8471
- return pubsub$1.exports;
8472
- }
8473
- var pubsubExports = requirePubsub();
8474
- const PubSub = getDefaultExportFromCjs(pubsubExports);
8475
- class InMemoryCacheManager {
8476
- constructor() {
8477
- __publicField(this, "resourceCache", /* @__PURE__ */ new Map());
8478
- __publicField(this, "urlToIdMap", /* @__PURE__ */ new Map());
8479
- }
8480
- async getByUrl(url2) {
8481
- const id = this.urlToIdMap.get(url2);
8482
- if (!id) return void 0;
8483
- return this.resourceCache.get(id);
8484
- }
8485
- hasUrlMatch(url2) {
8486
- if (!this.urlToIdMap.get(url2)) return false;
8487
- return true;
8488
- }
8489
- async getById(id) {
8490
- return this.resourceCache.get(id);
8491
- }
8492
- async get(ref) {
8493
- if (this.resourceCache.has(ref)) {
8494
- return this.resourceCache.get(ref);
8495
- }
8496
- const id = this.urlToIdMap.get(ref);
8497
- if (id) {
8498
- return this.resourceCache.get(id);
8499
- }
8500
- return void 0;
8501
- }
8502
- async length() {
8503
- return this.resourceCache.size;
8504
- }
8505
- async set(url2, resource) {
8506
- const id = resource == null ? void 0 : resource["@id"];
8507
- if (!id) {
8508
- console.warn("[CacheManager] Resource has no @id", resource);
8509
- return;
8510
- }
8511
- this.resourceCache.set(id, resource);
8512
- this.urlToIdMap.set(url2, id);
8513
- }
8514
- async linkUrlWithId(url2, emptyResource) {
8515
- if (!isUrlOrRelativePath(url2)) return;
8516
- if (this.hasUrlMatch(url2)) return;
8517
- await this.set(url2, emptyResource);
8518
- }
8519
- async has(urlOrId) {
8520
- if (this.resourceCache.has(urlOrId)) return true;
8521
- const id = this.urlToIdMap.get(urlOrId);
8522
- return id ? this.resourceCache.has(id) : false;
8523
- }
8524
- async getIdByUrl(url2) {
8525
- return this.urlToIdMap.get(url2);
8526
- }
8527
- async clear() {
8528
- this.resourceCache.clear();
8529
- this.urlToIdMap.clear();
8530
- }
8531
- async delete(idOrUrl) {
8532
- if (this.resourceCache.has(idOrUrl)) {
8533
- this.resourceCache.delete(idOrUrl);
8534
- for (const [url2, id2] of this.urlToIdMap.entries()) {
8535
- if (id2 === idOrUrl) {
8536
- this.urlToIdMap.delete(url2);
8537
- break;
9398
+ if (isToken && message[value]) {
9399
+ delete message[value];
9400
+ result = value;
9401
+ break;
9402
+ }
9403
+ if (isFunction) {
9404
+ for (t in message) {
9405
+ if (Object.prototype.hasOwnProperty.call(message, t) && message[t] === value) {
9406
+ delete message[t];
9407
+ result = true;
9408
+ }
9409
+ }
9410
+ }
9411
+ }
8538
9412
  }
8539
- }
8540
- return true;
8541
- }
8542
- const id = this.urlToIdMap.get(idOrUrl);
8543
- if (id && this.resourceCache.has(id)) {
8544
- this.resourceCache.delete(id);
8545
- this.urlToIdMap.delete(idOrUrl);
8546
- return true;
8547
- }
8548
- return false;
8549
- }
9413
+ return result;
9414
+ };
9415
+ });
9416
+ })(pubsub$1, pubsub$1.exports);
9417
+ return pubsub$1.exports;
8550
9418
  }
9419
+ var pubsubExports = requirePubsub();
9420
+ const PubSub = getDefaultExportFromCjs(pubsubExports);
8551
9421
  var events = {
8552
9422
  exports: {}
8553
9423
  };
@@ -27093,7 +27963,7 @@ sh:property [
27093
27963
  this.searchProvider = new SolidIndexingSearchProvider(this.getData.bind(this));
27094
27964
  }
27095
27965
  async initGetter() {
27096
- const { CustomGetter } = await import("./custom-getter-BvGSkLWj.js");
27966
+ const { CustomGetter } = await import("./custom-getter-FYE7WERU.js");
27097
27967
  return CustomGetter;
27098
27968
  }
27099
27969
  async getData(id, context2, parentId, localData, forceFetch, serverPagination, serverSearch, headers, bypassLoadingList) {
@@ -27347,8 +28217,8 @@ sh:property [
27347
28217
  await this.cache.delete(id);
27348
28218
  }
27349
28219
  }
27350
- setLocalData(resource, id, skipFetch = false, bypassLoadingList = false) {
27351
- return this._updateResource("_LOCAL", resource, id, skipFetch, bypassLoadingList);
28220
+ setLocalData(resource, id, skipFetch = false) {
28221
+ return this._updateResource("_LOCAL", resource, id, skipFetch);
27352
28222
  }
27353
28223
  post(resource, id, skipFetch = false) {
27354
28224
  return this._updateResource("POST", resource, id, skipFetch);
@@ -27466,373 +28336,12 @@ sh:property [
27466
28336
  hasSetLocalData = function(store2) {
27467
28337
  return "setLocalData" in store2 && typeof store2.setLocalData === "function";
27468
28338
  };
27469
- var StoreType = ((StoreType2) => {
28339
+ StoreType = ((StoreType2) => {
27470
28340
  StoreType2["LDP"] = "ldp";
27471
28341
  StoreType2["FederatedCatalogue"] = "federatedCatalogue";
28342
+ StoreType2["DataspaceConnector"] = "dataspaceConnector";
27472
28343
  return StoreType2;
27473
28344
  })(StoreType || {});
27474
- class FederatedCatalogueAPIWrapper {
27475
- constructor(options, fcBaseUrl) {
27476
- __publicField(this, "fcBaseUrl");
27477
- __publicField(this, "connect");
27478
- this.fcBaseUrl = fcBaseUrl;
27479
- const connection = this.firstConnect(options);
27480
- this.connect = () => connection;
27481
- }
27482
- async firstConnect(options) {
27483
- const body = new URLSearchParams({
27484
- grant_type: options.kc_grant_type,
27485
- client_id: options.kc_client_id,
27486
- client_secret: options.kc_client_secret,
27487
- scope: options.kc_scope,
27488
- username: options.kc_username,
27489
- password: options.kc_password
27490
- });
27491
- const headers = new Headers({
27492
- "Content-Type": "application/x-www-form-urlencoded"
27493
- });
27494
- const response = await fetch(options.kc_url, {
27495
- method: "POST",
27496
- headers,
27497
- body
27498
- });
27499
- const data = await response.json();
27500
- const token = data.access_token;
27501
- if (token == null) {
27502
- throw new Error("connexion fails", {
27503
- cause: data
27504
- });
27505
- }
27506
- return token;
27507
- }
27508
- async getAllSelfDescriptions() {
27509
- console.log("Fetching all self-descriptions from Federated Catalogue...", this.fcBaseUrl);
27510
- const token = await this.connect();
27511
- console.log("Token received:", token);
27512
- const url2 = `${this.fcBaseUrl}/self-descriptions`;
27513
- const headers = new Headers({
27514
- Authorization: `Bearer ${token}`
27515
- });
27516
- const response = await fetch(url2, {
27517
- headers
27518
- });
27519
- console.log("Response status:", response.status);
27520
- return await response.json();
27521
- }
27522
- async getSelfDescriptionByHash(sdHash) {
27523
- const token = await this.connect();
27524
- const url2 = `${this.fcBaseUrl}/self-descriptions/${sdHash}`;
27525
- const headers = new Headers({
27526
- Authorization: `Bearer ${token}`
27527
- });
27528
- const response = await fetch(url2, {
27529
- method: "GET",
27530
- headers
27531
- });
27532
- if (!response.ok) throw new Error(`GET /self-descriptions/${sdHash} failed: ${response.status} ${response.statusText}`, {
27533
- cause: response
27534
- });
27535
- return await response.json();
27536
- }
27537
- async postQuery(statement, parameters = {}) {
27538
- const token = await this.connect();
27539
- const url2 = `${this.fcBaseUrl}/query`;
27540
- const headers = new Headers({
27541
- Authorization: `Bearer ${token}`,
27542
- "Content-Type": "application/json"
27543
- });
27544
- const body = JSON.stringify({
27545
- statement,
27546
- parameters
27547
- });
27548
- const response = await fetch(url2, {
27549
- method: "POST",
27550
- headers,
27551
- body
27552
- });
27553
- if (!response.ok) {
27554
- throw new Error(`[ERROR] POST /query failed: ${response.status} ${response.statusText}`, {
27555
- cause: response
27556
- });
27557
- }
27558
- return await response.json();
27559
- }
27560
- async postQuerySearch(statement, parameters = {}, queryLanguage = "OPENCYPHER", annotations) {
27561
- const token = await this.connect();
27562
- const url2 = `${this.fcBaseUrl}/query/search`;
27563
- const headers = new Headers({
27564
- Authorization: `Bearer ${token}`,
27565
- "Content-Type": "application/json"
27566
- });
27567
- const body = JSON.stringify({
27568
- statement,
27569
- parameters,
27570
- annotations: annotations || {
27571
- queryLanguage
27572
- }
27573
- });
27574
- const response = await fetch(url2, {
27575
- method: "POST",
27576
- headers,
27577
- body
27578
- });
27579
- if (!response.ok) {
27580
- throw new Error(`[ERROR] POST /query/search failed: ${response.status} ${response.statusText}`, {
27581
- cause: response
27582
- });
27583
- }
27584
- return await response.json();
27585
- }
27586
- }
27587
- function getFederatedCatalogueAPIWrapper(baseUrl, optionLogin, optionsServer) {
27588
- const options = Object.assign({}, optionsServer, optionLogin);
27589
- return new FederatedCatalogueAPIWrapper(options, baseUrl);
27590
- }
27591
- function mapSourceToDestination(src, opts) {
27592
- var _a2, _b, _c, _d, _e, _f, _g, _h;
27593
- const vc = src.verifiableCredential;
27594
- const cs = vc.credentialSubject;
27595
- let catInfo;
27596
- let usedKey;
27597
- let type;
27598
- if (cs["dcat:service"]) {
27599
- catInfo = cs["dcat:service"];
27600
- usedKey = "service";
27601
- type = "tems:Service";
27602
- } else if (cs["dcat:dataset"] && cs["dcat:dataset"].length > 0) {
27603
- catInfo = cs["dcat:dataset"][0];
27604
- usedKey = "dataset";
27605
- type = "tems:DataOffer";
27606
- } else {
27607
- throw new Error("Expected either credentialSubject['dcat:service'] or a non-empty array in ['dcat:dataset']");
27608
- }
27609
- const resourceId = cs["@id"];
27610
- const slug = resourceId.split("/").pop() || "unknown";
27611
- const serviceId = `${opts.temsServiceBase}${encodeURIComponent(slug)}/`;
27612
- const creation_date = vc.issuanceDate;
27613
- const update_date = vc.expirationDate;
27614
- const name = catInfo["dcterms:title"];
27615
- const description = catInfo["rdfs:comment"];
27616
- const keywords = catInfo["dcat:keyword"] || [];
27617
- const long_description = keywords.length > 0 ? `Keywords: ${keywords.join(", ")}` : "";
27618
- const categories = {
27619
- "@id": `${serviceId}categories/`,
27620
- "@type": "ldp:Container",
27621
- "ldp:contains": keywords.map((kw) => ({
27622
- "@id": `${opts.temsCategoryBase}${encodeURIComponent(kw)}/`,
27623
- "@type": "tems:Category",
27624
- name: kw
27625
- }))
27626
- };
27627
- const endpointURL = catInfo["dcat:endpointURL"] || "";
27628
- const hasEndpoint = endpointURL.trim().length > 0;
27629
- const activation_status = hasEndpoint;
27630
- const is_in_app = hasEndpoint;
27631
- const is_external = hasEndpoint;
27632
- const is_api = hasEndpoint;
27633
- const imageUrls = [];
27634
- if ((_a2 = catInfo["foaf:thumbnail"]) == null ? void 0 : _a2["rdf:resource"]) {
27635
- imageUrls.push(catInfo["foaf:thumbnail"]["rdf:resource"]);
27636
- }
27637
- if ((_c = (_b = catInfo["dcterms:creator"]) == null ? void 0 : _b["foaf:thumbnail"]) == null ? void 0 : _c["rdf:resource"]) {
27638
- imageUrls.push(catInfo["dcterms:creator"]["foaf:thumbnail"]["rdf:resource"]);
27639
- }
27640
- const images = {
27641
- "@id": `${serviceId}images/`,
27642
- "@type": "ldp:Container",
27643
- "ldp:contains": imageUrls.map((url2) => ({
27644
- "@id": `${opts.temsImageBase}${encodeURIComponent(url2.split("/").pop() || "0")}/`,
27645
- url: url2,
27646
- iframe: false,
27647
- name: url2.split("/").pop() || "image",
27648
- "@type": "tems:Image"
27649
- }))
27650
- };
27651
- const contact_url = catInfo["dcat:endpointDescription"] || "";
27652
- const documentation_url = contact_url || "";
27653
- let service_url = catInfo["dcat:endpointURL"] || "";
27654
- if (service_url.includes("demo.isan.org")) service_url = new URL(service_url).origin;
27655
- let providerRef;
27656
- if (usedKey === "service") {
27657
- providerRef = ((_d = cs["gax-core:operatedBy"]) == null ? void 0 : _d["@id"]) || "";
27658
- } else {
27659
- providerRef = ((_e = cs["gax-core:offeredBy"]) == null ? void 0 : _e["@id"]) || "";
27660
- }
27661
- const providerSlug = providerRef.split(":").pop() + String(Math.random()) || "0";
27662
- const providerLogo = ((_g = (_f = catInfo["dcterms:creator"]) == null ? void 0 : _f["foaf:thumbnail"]) == null ? void 0 : _g["rdf:resource"]) || "";
27663
- const provider = {
27664
- "@id": `${opts.temsProviderBase}${encodeURIComponent(providerSlug)}/`,
27665
- "@type": "tems:Provider",
27666
- name: ((_h = catInfo["dcterms:creator"]) == null ? void 0 : _h["foaf:name"]) || "",
27667
- image: {
27668
- "@id": `${opts.temsImageBase}${encodeURIComponent(providerLogo.split("/").pop() || "0")}/`,
27669
- "@type": "tems:Image",
27670
- iframe: false,
27671
- url: providerLogo,
27672
- name: providerLogo.split("/").pop() || "provider-logo"
27673
- }
27674
- };
27675
- const data_offers = [];
27676
- const dest = {
27677
- "@id": serviceId,
27678
- creation_date,
27679
- update_date,
27680
- name,
27681
- description,
27682
- long_description,
27683
- categories,
27684
- activation_status,
27685
- activation_date: null,
27686
- licence: null,
27687
- is_in_app,
27688
- is_external,
27689
- is_api,
27690
- images,
27691
- release_date: null,
27692
- last_update: null,
27693
- developper: null,
27694
- contact_url,
27695
- documentation_url,
27696
- url: service_url,
27697
- provider,
27698
- data_offers,
27699
- "@type": type
27700
- };
27701
- return dest;
27702
- }
27703
- async function initLocalDataSourceContainer() {
27704
- const idField = Array.from(Array(20), () => Math.floor(Math.random() * 36).toString(36)).join("");
27705
- const dataSrc = `store://local.${idField}/`;
27706
- const localContainer = {
27707
- "@context": "https://cdn.startinblox.com/owl/context.jsonld",
27708
- "@type": "ldp:Container",
27709
- "@id": dataSrc,
27710
- "ldp:contains": new Array(),
27711
- permissions: [
27712
- "view"
27713
- ]
27714
- };
27715
- return localContainer;
27716
- }
27717
- class FederatedCatalogueStore {
27718
- constructor(cfg) {
27719
- __publicField(this, "cache");
27720
- __publicField(this, "session");
27721
- __publicField(this, "fcApi");
27722
- __publicField(this, "fcContainer");
27723
- this.cfg = cfg;
27724
- if (!this.cfg.login) {
27725
- throw new Error("Login must be provided for FederatedCatalogueStore");
27726
- }
27727
- if (!this.cfg.endpoint) {
27728
- throw new Error("Missing required `endpoint` in StoreConfig for FederatedCatalogueStore");
27729
- }
27730
- if (!this.cfg.optionsServer) {
27731
- throw new Error("Missing required `optionsServer` in StoreConfig for FederatedCatalogueStore");
27732
- }
27733
- this.fcApi = getFederatedCatalogueAPIWrapper(this.cfg.endpoint, this.cfg.login, this.cfg.optionsServer);
27734
- this.fcContainer = void 0;
27735
- this.cache = new InMemoryCacheManager();
27736
- }
27737
- async getData(args) {
27738
- const targetType = "targetType" in args ? args.targetType : args.id;
27739
- if (!this.fcApi) {
27740
- throw new Error("Federated API not initialized, returning empty data.");
27741
- }
27742
- if (!this.fcContainer || this.fcContainer["ldp:contains"].length === 0) {
27743
- this.fcContainer = await initLocalDataSourceContainer();
27744
- const dataset2 = await this.fcApi.getAllSelfDescriptions();
27745
- for (const item in dataset2.items) {
27746
- const sd = await this.fcApi.getSelfDescriptionByHash(dataset2.items[item].meta.sdHash);
27747
- if (sd) {
27748
- const resource = mapSourceToDestination(sd, {
27749
- temsServiceBase: this.cfg.temsServiceBase,
27750
- temsCategoryBase: this.cfg.temsCategoryBase,
27751
- temsImageBase: this.cfg.temsImageBase,
27752
- temsProviderBase: this.cfg.temsProviderBase
27753
- });
27754
- if (!this.fcContainer["ldp:contains"].some((r) => r["@id"] === resource["@id"])) {
27755
- this.fcContainer["ldp:contains"].push(resource);
27756
- }
27757
- }
27758
- }
27759
- }
27760
- const localContainer = await initLocalDataSourceContainer();
27761
- localContainer["ldp:contains"] = this.fcContainer["ldp:contains"].filter((item) => item["@type"] === targetType);
27762
- document.dispatchEvent(new CustomEvent("save", {
27763
- detail: {
27764
- resource: {
27765
- "@id": this.fcContainer["@id"]
27766
- }
27767
- },
27768
- bubbles: true
27769
- }));
27770
- return localContainer;
27771
- }
27772
- get(_id, _serverPagination, _serverSearch) {
27773
- return Promise.resolve(null);
27774
- }
27775
- post(_resource, _id, _skipFetch) {
27776
- return Promise.resolve(null);
27777
- }
27778
- put(_resource, _id, _skipFetch) {
27779
- return Promise.resolve(null);
27780
- }
27781
- patch(_resource, _id, _skipFetch) {
27782
- return Promise.resolve(null);
27783
- }
27784
- delete(_id, _context) {
27785
- return Promise.resolve(null);
27786
- }
27787
- clearCache(_id) {
27788
- return Promise.resolve();
27789
- }
27790
- cacheResource(_key, _resourceProxy) {
27791
- return Promise.resolve();
27792
- }
27793
- _getLanguage() {
27794
- return "";
27795
- }
27796
- selectLanguage(_selectedLanguageCode) {
27797
- }
27798
- getExpandedPredicate(_property, _context) {
27799
- return null;
27800
- }
27801
- subscribeResourceTo(_resourceId, _nestedResourceId) {
27802
- }
27803
- fetchAuthn(_iri, _options) {
27804
- return Promise.resolve({});
27805
- }
27806
- }
27807
- const _FederatedCatalogueStoreAdapter = class _FederatedCatalogueStoreAdapter {
27808
- constructor() {
27809
- }
27810
- static validateConfiguration(cfg) {
27811
- const requiredFields = [
27812
- "temsServiceBase",
27813
- "temsCategoryBase",
27814
- "temsImageBase",
27815
- "temsProviderBase"
27816
- ];
27817
- const missingFields = requiredFields.filter((field) => !cfg[field]);
27818
- if (missingFields.length > 0) {
27819
- throw new Error(`[FederatedCatalogueStoreAdapter] Missing required configuration fields: ${missingFields.join(", ")}`);
27820
- }
27821
- }
27822
- static getStoreInstance(cfg) {
27823
- if (!_FederatedCatalogueStoreAdapter.store) {
27824
- if (!cfg) {
27825
- throw new Error("[FederatedCatalogueStoreAdapter] configuration is required");
27826
- }
27827
- _FederatedCatalogueStoreAdapter.validateConfiguration(cfg);
27828
- _FederatedCatalogueStoreAdapter.store = new FederatedCatalogueStore(cfg);
27829
- }
27830
- return _FederatedCatalogueStoreAdapter.store;
27831
- }
27832
- };
27833
- __publicField(_FederatedCatalogueStoreAdapter, "store");
27834
- let FederatedCatalogueStoreAdapter = _FederatedCatalogueStoreAdapter;
27835
- var StoreFactory;
27836
28345
  ((StoreFactory2) => {
27837
28346
  const registry = /* @__PURE__ */ new Map();
27838
28347
  function register(name, adapter) {
@@ -27848,6 +28357,7 @@ sh:property [
27848
28357
  })(StoreFactory || (StoreFactory = {}));
27849
28358
  StoreFactory.register(StoreType.LDP, LdpStoreAdapter);
27850
28359
  StoreFactory.register(StoreType.FederatedCatalogue, FederatedCatalogueStoreAdapter);
28360
+ StoreFactory.register(StoreType.DataspaceConnector, DataspaceConnectorStoreAdapter);
27851
28361
  StoreService = (_a = class {
27852
28362
  static init(config) {
27853
28363
  if (StoreService.currentStore) {
@@ -31929,11 +32439,13 @@ export {
31929
32439
  __tla,
31930
32440
  formatAttributesToServerSearchOptions as a,
31931
32441
  base_context as b,
31932
- hasQueryIndex as c,
31933
- sibStore as d,
32442
+ StoreType as c,
32443
+ StoreFactory as d,
32444
+ hasQueryIndex as e,
31934
32445
  formatAttributesToServerPaginationOptions as f,
31935
32446
  getDefaultExportFromCjs as g,
31936
32447
  hasSetLocalData as h,
32448
+ sibStore as i,
31937
32449
  mergeServerSearchOptions as m,
31938
32450
  semantizer as s
31939
32451
  };