@opengeospatial/jsonld-ui-utils 0.4.12 → 0.5.0

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.cjs.js CHANGED
@@ -24,11 +24,22 @@ function _interopNamespaceDefault(e) {
24
24
 
25
25
  var N3__namespace = /*#__PURE__*/_interopNamespaceDefault(N3);
26
26
 
27
- const jsonFetch = async (url) => {
28
- const response = await fetch(url, {
29
- headers: { 'Accept': 'application/json' },
30
- });
31
- return await response.json();
27
+ const jsonFetch = async (url, timeout) => {
28
+ const controller = new AbortController();
29
+ const timer = setTimeout(() => controller.abort(), timeout);
30
+ try {
31
+ const response = await fetch(url, {
32
+ headers: { 'Accept': 'application/json' },
33
+ signal: controller.signal,
34
+ });
35
+ if (!response.ok) {
36
+ throw new Error(`HTTP error ${response.status} loading context ${url}`);
37
+ }
38
+ return await response.json();
39
+ }
40
+ finally {
41
+ clearTimeout(timer);
42
+ }
32
43
  };
33
44
  const mergeContexts = (definitions) => {
34
45
  const mergePair = (a, b) => {
@@ -54,54 +65,84 @@ const mergeContexts = (definitions) => {
54
65
  return currentContext;
55
66
  };
56
67
  const urlCache = new Map();
57
- async function loadContext(context) {
58
- const walk = async (definition, refChain) => {
68
+ const resolveUrl = (url, baseUrl) => {
69
+ try {
70
+ return new URL(url, baseUrl).toString();
71
+ }
72
+ catch (_a) {
73
+ return url;
74
+ }
75
+ };
76
+ /**
77
+ * Loads a context without merging its entries. Remote references are replaced by their contents,
78
+ * including the scoped contexts of term definitions, which are modified in place.
79
+ */
80
+ async function loadContextEntries(context, options = {}) {
81
+ const { requestTimeout = 10000 } = options;
82
+ const walk = async (definition, refChain, baseUrl) => {
59
83
  for (const [key, value] of Object.entries(definition)) {
60
84
  if (key === '@context') {
85
+ const entries = await load(value, refChain, baseUrl);
61
86
  // @ts-ignore
62
- definition[key] = await load(value, refChain);
87
+ definition[key] = entries.length === 1 ? entries[0] : entries;
63
88
  }
64
89
  else if (typeof value === 'object' && value !== null) {
65
- await walk(value, refChain);
90
+ await walk(value, refChain, baseUrl);
66
91
  }
67
92
  }
68
93
  };
69
- const load = async (context, refChain) => {
70
- if (context === null || typeof context === 'undefined') {
71
- return {};
94
+ const load = async (context, refChain, baseUrl) => {
95
+ if (context === undefined) {
96
+ return [];
97
+ }
98
+ if (context === null) {
99
+ return [null];
72
100
  }
73
101
  if (Array.isArray(context)) {
74
- // fetch and merge
75
- const contextEntries = await Promise.all(context.map(e => load(e, refChain)));
76
- return mergeContexts(contextEntries);
102
+ return (await Promise.all(context.map(e => load(e, refChain, baseUrl)))).flat();
77
103
  }
78
- else if (typeof context === 'object') {
79
- await walk(context, refChain);
80
- return context;
104
+ if (typeof context === 'object') {
105
+ await walk(context, refChain, baseUrl);
106
+ return [context];
81
107
  }
82
- else {
83
- if (refChain === null || refChain === void 0 ? void 0 : refChain.includes(context)) {
84
- throw new Error('Circular dependencies found: ' + refChain.join(' -> ') + ' -> ' + context);
85
- }
86
- const newRefChain = Array.isArray(refChain) ? refChain === null || refChain === void 0 ? void 0 : refChain.slice() : [];
87
- newRefChain.push(context);
88
- if (!urlCache.has(context)) {
89
- urlCache.set(context, jsonFetch(context).then(obj => load(obj['@context'], newRefChain)));
90
- }
91
- return urlCache.get(context);
108
+ const url = resolveUrl(context, baseUrl);
109
+ if (refChain === null || refChain === void 0 ? void 0 : refChain.includes(url)) {
110
+ throw new Error('Circular dependencies found: ' + refChain.join(' -> ') + ' -> ' + url);
92
111
  }
112
+ const newRefChain = [...(refChain !== null && refChain !== void 0 ? refChain : []), url];
113
+ if (!urlCache.has(url)) {
114
+ // Relative references inside a remote context are resolved against that context's own URL
115
+ const request = jsonFetch(url, requestTimeout).then(async (obj) => {
116
+ const entries = await load(obj['@context'], newRefChain, url);
117
+ // @base is ignored in remote contexts
118
+ return entries.map(entry => {
119
+ if (!entry) {
120
+ return entry;
121
+ }
122
+ const { '@base': _, ...loaded } = entry;
123
+ return loaded;
124
+ });
125
+ });
126
+ // Failures are not cached, so that they can be retried
127
+ request.catch(() => urlCache.delete(url));
128
+ urlCache.set(url, request);
129
+ }
130
+ return urlCache.get(url);
93
131
  };
94
- if (typeof context === 'object' && context !== null && '@context' in context) {
95
- return load(context['@context']);
96
- }
97
- else {
98
- return load(context);
99
- }
132
+ return load(context, undefined, options.baseUrl);
133
+ }
134
+ async function loadContext(context, options = {}) {
135
+ const unwrapped = typeof context === 'object' && context !== null && '@context' in context
136
+ ? context['@context']
137
+ : context;
138
+ const entries = await loadContextEntries(unwrapped, options);
139
+ return mergeContexts(entries.map(entry => entry !== null && entry !== void 0 ? entry : {}));
100
140
  }
101
141
 
102
142
  var jsonld = /*#__PURE__*/Object.freeze({
103
143
  __proto__: null,
104
- loadContext: loadContext
144
+ loadContext: loadContext,
145
+ loadContextEntries: loadContextEntries
105
146
  });
106
147
 
107
148
  const ns = (base) => (local) => `${base}${local}`;
@@ -126,9 +167,106 @@ const descriptionPredicates = [
126
167
  RDFS('comment'),
127
168
  ];
128
169
 
170
+ // Limits how many HTTP requests run at once, across all lookups
171
+ let active = 0;
172
+ const waiting = [];
173
+ function startWaiting() {
174
+ while (waiting.length && active < waiting[0].limit) {
175
+ active++;
176
+ waiting.shift().start();
177
+ }
178
+ }
179
+ /**
180
+ * Runs a task holding one request slot. The task must pass the signal to fetch() and include reading
181
+ * the response body, so that the slot is held (and the timeout applies) until the request is done.
182
+ */
183
+ async function withRequestSlot(task, { limit, timeout, priority = false }) {
184
+ await new Promise(start => {
185
+ // Priority requests queue up behind earlier priority ones, ahead of everything else
186
+ const firstNormal = priority ? waiting.findIndex(entry => !entry.priority) : -1;
187
+ waiting.splice(firstNormal < 0 ? waiting.length : firstNormal, 0, { limit: Math.max(1, limit), priority, start });
188
+ startWaiting();
189
+ });
190
+ const controller = new AbortController();
191
+ const timer = setTimeout(() => controller.abort(), timeout);
192
+ try {
193
+ return await task(controller.signal);
194
+ }
195
+ finally {
196
+ clearTimeout(timer);
197
+ active--;
198
+ startWaiting();
199
+ }
200
+ }
201
+
202
+ // Collects URIs into one DESCRIBE query per endpoint. A batch is sent when the first of these happens:
203
+ // it is full, no earlier lookup is pending (so nothing else can join soon), or MAX_WAIT has passed.
204
+ const MAX_WAIT = 500;
205
+ const batches = {};
206
+ let pendingLookups = 0;
207
+ let idleCheckScheduled = false;
208
+ // Deferred, so that URIs arriving in the same burst end up in the same batch
209
+ function scheduleIdleCheck() {
210
+ if (idleCheckScheduled) {
211
+ return;
212
+ }
213
+ idleCheckScheduled = true;
214
+ setTimeout(() => {
215
+ idleCheckScheduled = false;
216
+ if (!pendingLookups) {
217
+ Object.values(batches).forEach(batch => batch.send());
218
+ }
219
+ }, 0);
220
+ }
221
+ /** Tracks the lookup stages that run before SPARQL, and can therefore still feed a batch */
222
+ async function trackLookup(lookup) {
223
+ pendingLookups++;
224
+ try {
225
+ return await lookup();
226
+ }
227
+ finally {
228
+ pendingLookups--;
229
+ scheduleIdleCheck();
230
+ }
231
+ }
232
+ // Characters not allowed inside <...> in SPARQL: one such URI would break the query for its whole batch
233
+ const isQueryableIri = (uri) => /^[a-z][a-z0-9+.-]*:[^\u0000- <>"{}|^`\\]*$/i.test(uri);
234
+ function createBatch(endpoint, sendQuery) {
235
+ const uris = [];
236
+ let resolve;
237
+ const result = new Promise(r => resolve = r);
238
+ const batch = {
239
+ uris,
240
+ result,
241
+ send() {
242
+ clearTimeout(timer);
243
+ delete batches[endpoint];
244
+ resolve(sendQuery(`DESCRIBE ${uris.map(uri => `<${uri}>`).join(' ')}`));
245
+ },
246
+ };
247
+ const timer = setTimeout(batch.send, MAX_WAIT);
248
+ return batch;
249
+ }
250
+ /** Resolves with the response to the query that included this URI */
251
+ function describeInBatch(endpoint, uri, batchSize, sendQuery) {
252
+ var _a;
253
+ const batch = (_a = batches[endpoint]) !== null && _a !== void 0 ? _a : (batches[endpoint] = createBatch(endpoint, sendQuery));
254
+ batch.uris.push(uri);
255
+ if (batch.uris.length >= batchSize) {
256
+ batch.send();
257
+ }
258
+ else {
259
+ scheduleIdleCheck();
260
+ }
261
+ return batch.result;
262
+ }
263
+
129
264
  const defaultFetchResourceOptions = {
130
265
  labelPredicates,
131
266
  descriptionPredicates,
267
+ maxConcurrentRequests: 6,
268
+ sparqlBatchSize: 50,
269
+ requestTimeout: 10000,
132
270
  };
133
271
  const fetchResourceCache = {};
134
272
  const requestCache = {};
@@ -208,8 +346,11 @@ function parseTurtle(text, baseIRI, contentType) {
208
346
  });
209
347
  }
210
348
  async function parseJsonLd(text, baseIRI) {
211
- const jsonldMod = await import('jsonld');
212
- if (!jsonldMod) {
349
+ var _a;
350
+ // jsonld is CommonJS: a dynamic import usually exposes it as the default export
351
+ const imported = await import('jsonld');
352
+ const jsonldMod = (_a = imported.default) !== null && _a !== void 0 ? _a : imported;
353
+ if (!(jsonldMod === null || jsonldMod === void 0 ? void 0 : jsonldMod.toRDF)) {
213
354
  throw new Error('jsonld peer dependency is not available');
214
355
  }
215
356
  const doc = JSON.parse(text);
@@ -228,39 +369,41 @@ async function parseRdfXml(text, baseIRI) {
228
369
  });
229
370
  }
230
371
  const toArray = (val) => !val ? [] : Array.isArray(val) ? val : [val];
231
- const getSparqlQuery = (uri) => `DESCRIBE <${uri}>`;
232
- const fetchAndParse = async (fetchFn, baseIRI) => {
233
- var _a;
234
- let response;
372
+ const fetchAndParse = async (url, init, baseIRI, options, priority = false) => {
235
373
  try {
236
- response = await fetchFn();
237
- if (!response.ok) {
374
+ // The slot covers reading the body, but not parsing it
375
+ const received = await withRequestSlot(async (signal) => {
376
+ var _a;
377
+ const response = await fetch(url, { ...init, signal });
378
+ if (!response.ok) {
379
+ return null;
380
+ }
381
+ return {
382
+ contentType: ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0].trim()) || 'text/turtle',
383
+ text: await response.text(),
384
+ };
385
+ }, { limit: options.maxConcurrentRequests, timeout: options.requestTimeout, priority });
386
+ if (!received) {
238
387
  return null;
239
388
  }
240
- }
241
- catch (_b) {
242
- return null;
243
- }
244
- const contentType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0].trim()) || 'text/turtle';
245
- const text = await response.text();
246
- try {
389
+ const { contentType, text } = received;
247
390
  if (N3_CONTENT_TYPES.has(contentType)) {
248
- return parseTurtle(text, baseIRI, contentType);
391
+ return await parseTurtle(text, baseIRI, contentType);
249
392
  }
250
393
  if (contentType === 'application/ld+json') {
251
- return parseJsonLd(text, baseIRI);
394
+ return await parseJsonLd(text, baseIRI);
252
395
  }
253
396
  if (contentType === 'application/rdf+xml') {
254
- return parseRdfXml(text, baseIRI);
397
+ return await parseRdfXml(text, baseIRI);
255
398
  }
256
399
  }
257
- catch (_c) {
400
+ catch (_a) {
258
401
  }
259
402
  return null;
260
403
  };
261
- const fetchAndParseDocument = (docUrl, fetchFn, baseIRI = docUrl) => {
404
+ const fetchAndParseDocument = (docUrl, options, baseIRI = docUrl) => {
262
405
  if (!(docUrl in requestCache)) {
263
- requestCache[docUrl] = fetchAndParse(fetchFn, baseIRI);
406
+ requestCache[docUrl] = fetchAndParse(docUrl, { headers: { 'Accept': ACCEPT_HEADER } }, baseIRI, options);
264
407
  }
265
408
  return requestCache[docUrl];
266
409
  };
@@ -287,17 +430,20 @@ const findResourceInStore = async (storePromise, uri, options) => {
287
430
  }
288
431
  return null;
289
432
  };
290
- const actualFetchResource = async (uri, options) => {
433
+ // Direct dereferencing and RAINBOW proxies: one request per URI (or per document)
434
+ const lookupByRequest = async (uri, options) => {
291
435
  const docUrl = uri.includes('#') ? uri.split('#')[0] : uri;
292
- // 1. Direct (cached by document URL so hash siblings share one request).
436
+ // 1. Direct, only for HTTP(S) URIs (cached by document URL so hash siblings share one request).
293
437
  // On an https:// page, an http:// URI is tried as https:// first (the http:// request would be blocked).
294
438
  let result = null;
295
- const httpsDocUrl = toHttpsIfMixedContent(docUrl);
296
- if (httpsDocUrl) {
297
- result = await findResourceInStore(fetchAndParseDocument(httpsDocUrl, () => fetch(httpsDocUrl, { headers: { 'Accept': ACCEPT_HEADER } }), docUrl), uri, options);
298
- }
299
- if (!result) {
300
- result = await findResourceInStore(fetchAndParseDocument(docUrl, () => fetch(docUrl, { headers: { 'Accept': ACCEPT_HEADER } })), uri, options);
439
+ if (/^https?:/i.test(uri)) {
440
+ const httpsDocUrl = toHttpsIfMixedContent(docUrl);
441
+ if (httpsDocUrl) {
442
+ result = await findResourceInStore(fetchAndParseDocument(httpsDocUrl, options, docUrl), uri, options);
443
+ }
444
+ if (!result) {
445
+ result = await findResourceInStore(fetchAndParseDocument(docUrl, options), uri, options);
446
+ }
301
447
  }
302
448
  // 2. Rainbow proxies (in order) — not supported for hash URIs
303
449
  const isHashUri = uri.includes('#');
@@ -307,20 +453,23 @@ const actualFetchResource = async (uri, options) => {
307
453
  }
308
454
  const rainbowURL = new URL(instance);
309
455
  rainbowURL.searchParams.set('uri', uri);
310
- const rainbowUrlStr = rainbowURL.toString();
311
- result = await findResourceInStore(fetchAndParseDocument(rainbowUrlStr, () => fetch(rainbowUrlStr, { headers: { 'Accept': ACCEPT_HEADER } })), uri, options);
456
+ result = await findResourceInStore(fetchAndParseDocument(rainbowURL.toString(), options), uri, options);
312
457
  }
313
- // 3. SPARQL endpoints (in order) — each DESCRIBE is unique per URI, no request cache
458
+ return result;
459
+ };
460
+ const sparqlQuery = (endpoint, options) => (query) => fetchAndParse(endpoint, {
461
+ method: 'POST',
462
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/turtle, application/n-triples' },
463
+ body: new URLSearchParams({ query }).toString(),
464
+ }, endpoint, options, true);
465
+ const actualFetchResource = async (uri, options) => {
466
+ let result = await trackLookup(() => lookupByRequest(uri, options));
467
+ // 3. SPARQL endpoints (in order), batching URIs into shared DESCRIBE queries
314
468
  for (const endpoint of [...toArray(options.fallbackSparqlEndpoints), ...toArray(options.fallbackSparqlEndpoint)]) {
315
- if (result) {
469
+ if (result || !isQueryableIri(uri)) {
316
470
  break;
317
471
  }
318
- const formBody = new URLSearchParams({ query: getSparqlQuery(uri) });
319
- result = await findResourceInStore(fetchAndParse(() => fetch(endpoint, {
320
- method: 'POST',
321
- headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/turtle, application/n-triples' },
322
- body: formBody.toString(),
323
- }), uri), uri, options);
472
+ result = await findResourceInStore(describeInBatch(endpoint, uri, options.sparqlBatchSize, sparqlQuery(endpoint, options)), uri, options);
324
473
  }
325
474
  if (!result) {
326
475
  throw new Error(`No label data found for <${uri}>`);
@@ -344,7 +493,7 @@ async function loadFeature(url) {
344
493
  throw new Error(`Could not load feature ${url}: ${response.status} - ${response.statusText}`);
345
494
  }
346
495
  const feature = await response.json();
347
- const context = await loadContext(feature);
496
+ const context = await loadContext(feature, { baseUrl: response.url || url });
348
497
  return {
349
498
  feature,
350
499
  context,
@@ -359,175 +508,241 @@ var resource = /*#__PURE__*/Object.freeze({
359
508
  loadFeature: loadFeature
360
509
  });
361
510
 
511
+ const has = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
512
+ function pushContext(stack, context) {
513
+ if (Array.isArray(context)) {
514
+ return context.reduce(pushContext, stack);
515
+ }
516
+ if (context === null) {
517
+ return [];
518
+ }
519
+ return typeof context === 'object' ? [...stack, context] : stack;
520
+ }
521
+ // Each @base is resolved against the previous one, starting at the document's base URL
522
+ function resolveBase(stack, baseUrl) {
523
+ return stack.reduce((base, context) => {
524
+ if (!has(context, '@base')) {
525
+ return base;
526
+ }
527
+ const value = context['@base'];
528
+ if (value === null) {
529
+ return null;
530
+ }
531
+ try {
532
+ return new URL(value, base !== null && base !== void 0 ? base : undefined).toString();
533
+ }
534
+ catch (_a) {
535
+ return null;
536
+ }
537
+ }, baseUrl);
538
+ }
539
+ // Innermost value of a context entry; undefined if no context in the stack declares it
540
+ function findEntry(stack, key) {
541
+ for (let i = stack.length - 1; i >= 0; i--) {
542
+ if (has(stack[i], key)) {
543
+ return stack[i][key];
544
+ }
545
+ }
546
+ return undefined;
547
+ }
548
+ /** Term definition in object form; null if the term is explicitly unmapped, undefined if unknown */
549
+ function findTerm(term, stack) {
550
+ const entry = findEntry(stack, term);
551
+ if (typeof entry === 'string') {
552
+ return { '@id': entry };
553
+ }
554
+ if (entry && typeof entry === 'object') {
555
+ return entry['@id'] === null ? null : entry;
556
+ }
557
+ return entry === null ? null : undefined;
558
+ }
559
+ /** The keyword (`@id`, `@type`...) that a key stands for, either directly or through an alias */
560
+ function asKeyword(key, stack) {
561
+ var _a;
562
+ if (key.startsWith('@')) {
563
+ return key;
564
+ }
565
+ const id = (_a = findTerm(key, stack)) === null || _a === void 0 ? void 0 : _a['@id'];
566
+ return (id === null || id === void 0 ? void 0 : id.startsWith('@')) ? id : null;
567
+ }
568
+ function expandIri(value, stack, options, seen = new Set()) {
569
+ var _a, _b, _c;
570
+ if (value.startsWith('@')) {
571
+ return value;
572
+ }
573
+ const expandTerm = (term) => expandIri(term, stack, { vocab: true }, seen);
574
+ if (options.vocab && !seen.has(value)) {
575
+ const definition = findTerm(value, stack);
576
+ if (definition === null) {
577
+ return null;
578
+ }
579
+ const id = (_a = definition === null || definition === void 0 ? void 0 : definition['@reverse']) !== null && _a !== void 0 ? _a : definition === null || definition === void 0 ? void 0 : definition['@id'];
580
+ if (id && id !== value) {
581
+ seen.add(value);
582
+ return expandTerm(id);
583
+ }
584
+ }
585
+ const colon = value.indexOf(':');
586
+ if (colon > -1) {
587
+ const prefix = value.substring(0, colon);
588
+ const localPart = value.substring(colon + 1);
589
+ if (prefix === '_') {
590
+ return null;
591
+ }
592
+ if (!localPart.startsWith('//') && !seen.has(prefix) && findTerm(prefix, stack)) {
593
+ const expandedPrefix = expandIri(prefix, stack, { vocab: true }, new Set(seen));
594
+ if (expandedPrefix) {
595
+ return `${expandedPrefix}${localPart}`;
596
+ }
597
+ }
598
+ if (/^[a-z][a-z0-9+.-]*:/i.test(value)) {
599
+ return value;
600
+ }
601
+ }
602
+ if (options.vocab) {
603
+ const vocab = findEntry(stack, '@vocab');
604
+ if (vocab) {
605
+ const expandedVocab = vocab.includes(':') ? vocab : ((_c = (_b = findTerm(vocab, stack)) === null || _b === void 0 ? void 0 : _b['@id']) !== null && _c !== void 0 ? _c : vocab);
606
+ return `${expandedVocab}${value}`;
607
+ }
608
+ }
609
+ if (options.base) {
610
+ const base = resolveBase(stack, options.baseUrl);
611
+ try {
612
+ return base ? new URL(value, base).toString() : null;
613
+ }
614
+ catch (_d) {
615
+ return null;
616
+ }
617
+ }
618
+ return null;
619
+ }
620
+
362
621
  const defaultAugmentOptions = {
363
622
  replaceElements: true,
364
623
  ...defaultFetchResourceOptions,
365
624
  };
366
- function createPropertiesTable(feature, container, options = {
625
+ const defaultTableOptions = {
367
626
  propertiesField: 'properties',
368
- }) {
369
- const createLevel = (parent, value, addHeaders = false) => {
370
- if (Array.isArray(value)) {
371
- for (const entry of value) {
372
- const newElem = createLevel(parent, entry);
373
- newElem.classList.add('array-entry');
627
+ maxDepth: 15,
628
+ maxElements: 100,
629
+ };
630
+ // Never cut by maxElements, since augment() needs them (e.g. for type-scoped contexts). Contexts are
631
+ // not known when rendering, so only the usual aliases of @id and @type can be recognized.
632
+ const ALWAYS_SHOWN = new Set(['@id', '@type', 'id', 'type']);
633
+ const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
634
+ const plural = (count, singular, pluralForm = `${singular}s`) => `${count} ${count === 1 ? singular : pluralForm}`;
635
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
636
+ // {"@list": [...]} and {"@set": [...]} are displayed as plain arrays
637
+ const unwrapContainer = (value) => {
638
+ if (isObject(value)) {
639
+ const keys = Object.keys(value);
640
+ if (keys.length === 1 && (keys[0] === '@list' || keys[0] === '@set')) {
641
+ return value[keys[0]];
642
+ }
643
+ }
644
+ return value;
645
+ };
646
+ const appendSpan = (parent, className, text) => {
647
+ const span = document.createElement('span');
648
+ span.classList.add(className);
649
+ span.textContent = text;
650
+ parent.appendChild(span);
651
+ return span;
652
+ };
653
+ // @context entries found in the data, kept out of the DOM for augment() to apply
654
+ const embeddedContexts = new WeakMap();
655
+ function createPropertiesTable(feature, container, options = {}) {
656
+ const { propertiesField, maxDepth, maxElements } = { ...defaultTableOptions, ...options };
657
+ const createLevel = (parent, rawValue, depth, addHeaders = false) => {
658
+ const value = unwrapContainer(rawValue);
659
+ if (isObject(value) && '@value' in value) {
660
+ // Value object: a single literal, plus its language or datatype
661
+ createLevel(parent, value['@value'], depth);
662
+ for (const [keyword, className] of [['@language', 'literal-language'], ['@type', 'literal-datatype']]) {
663
+ if (keyword in value) {
664
+ appendSpan(parent, className, String(value[keyword]));
665
+ }
374
666
  }
375
- return parent;
376
- }
377
- else if (value === null || typeof value === 'undefined' || typeof value !== 'object') {
378
- const span = document.createElement('span');
379
- span.classList.add('literal-value');
380
- span.textContent = '' + value;
381
- parent.appendChild(span);
382
- return span;
383
- }
384
- else {
385
- const table = document.createElement('table');
386
- table.classList.add('object-table');
387
- if (addHeaders) {
388
- table.innerHTML = '<thead><tr><th>Property</th><th>Value</th></tr></thead>';
667
+ return;
668
+ }
669
+ if (value === null || typeof value !== 'object') {
670
+ appendSpan(parent, 'literal-value', '' + value);
671
+ return;
672
+ }
673
+ const isArray = Array.isArray(value);
674
+ const entries = isArray
675
+ ? value.map((v, i) => [String(i), v])
676
+ : Object.entries(value).filter(([k]) => k !== '@context');
677
+ if (isArray && !entries.length) {
678
+ return;
679
+ }
680
+ if (depth > maxDepth && entries.length) {
681
+ appendSpan(parent, 'truncated-value', isArray ? plural(entries.length, 'item') : plural(entries.length, 'property', 'properties'));
682
+ return;
683
+ }
684
+ const table = document.createElement('table');
685
+ table.classList.add(isArray ? 'array-table' : 'object-table');
686
+ if (!isArray && '@context' in value) {
687
+ embeddedContexts.set(table, value['@context']);
688
+ }
689
+ if (addHeaders && !isArray) {
690
+ table.innerHTML = '<thead><tr><th>Property</th><th>Value</th></tr></thead>';
691
+ }
692
+ const tbody = document.createElement('tbody');
693
+ const addCell = (row, ...classNames) => {
694
+ const cell = document.createElement('td');
695
+ cell.classList.add(...classNames);
696
+ row.appendChild(cell);
697
+ return cell;
698
+ };
699
+ let remaining = maxElements - (isArray ? 0 : entries.filter(([k]) => ALWAYS_SHOWN.has(k)).length);
700
+ const shown = entries.filter(([k]) => (!isArray && ALWAYS_SHOWN.has(k)) || remaining-- > 0);
701
+ for (const [k, v] of shown) {
702
+ const row = document.createElement('tr');
703
+ if (isArray) {
704
+ createLevel(addCell(row, 'array-value', 'array-entry'), v, depth + 1);
389
705
  }
390
- const tbody = document.createElement('tbody');
391
- Object.entries(value).forEach(([k, v]) => {
392
- const row = document.createElement('tr');
393
- const keyCell = document.createElement('td');
394
- keyCell.classList.add('object-property');
706
+ else {
707
+ const keyCell = addCell(row, 'object-property');
395
708
  keyCell.setAttribute('data-property', k);
396
709
  keyCell.textContent = k;
397
- row.appendChild(keyCell);
398
- const valueCell = document.createElement('td');
399
- valueCell.classList.add('object-value');
400
- createLevel(valueCell, v);
401
- row.appendChild(valueCell);
402
- tbody.appendChild(row);
403
- });
404
- table.appendChild(tbody);
405
- parent.appendChild(table);
406
- return table;
710
+ createLevel(addCell(row, 'object-value'), v, depth + 1);
711
+ }
712
+ tbody.appendChild(row);
713
+ }
714
+ const hidden = entries.length - shown.length;
715
+ if (hidden) {
716
+ const row = document.createElement('tr');
717
+ const cell = addCell(row, isArray ? 'array-value' : 'truncated-cell');
718
+ if (!isArray) {
719
+ cell.colSpan = 2;
720
+ }
721
+ appendSpan(cell, 'truncated-value', isArray
722
+ ? plural(hidden, 'more item')
723
+ : plural(hidden, 'more property', 'more properties'));
724
+ tbody.appendChild(row);
407
725
  }
726
+ table.appendChild(tbody);
727
+ parent.appendChild(table);
408
728
  };
409
729
  const wrapper = document.createElement('div');
410
730
  wrapper.classList.add('object-properties');
411
731
  container.appendChild(wrapper);
412
- if (options.propertiesField) {
413
- createLevel(wrapper, feature[options.propertiesField], true);
414
- }
415
- else {
416
- createLevel(wrapper, feature, true);
417
- }
732
+ createLevel(wrapper, propertiesField ? feature[propertiesField] : feature, 1, true);
418
733
  }
419
734
  async function augment(rootElem, context, options = {}) {
420
735
  const mergedOptions = { ...defaultAugmentOptions, ...options };
421
- const resolveTerm = (term, contextStack, useVocab = true, useBase = false) => {
422
- if (term.indexOf('://') !== -1) {
423
- return { '@id': term };
424
- }
425
- let closestVocab = null;
426
- let closestBase = null;
427
- for (let i = contextStack.length - 1; i >= 0; i--) {
428
- if (term in contextStack[i]) {
429
- let resolvedTerm = contextStack[i][term];
430
- let resolvedId;
431
- if (resolvedTerm === null || typeof resolvedTerm === 'undefined' || typeof resolvedTerm === 'boolean'
432
- || Array.isArray(resolvedTerm)) {
433
- continue;
434
- }
435
- if (typeof resolvedTerm === 'string') {
436
- if (resolvedTerm === '@type') {
437
- return { '@id': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' };
438
- }
439
- resolvedId = resolvedTerm;
440
- resolvedTerm = { '@id': resolvedTerm };
441
- }
442
- else if (typeof resolvedTerm === 'object' && '@id' in resolvedTerm && typeof resolvedTerm['@id'] === 'string') {
443
- resolvedId = resolvedTerm['@id'];
444
- }
445
- else {
446
- continue;
447
- }
448
- const idx = resolvedId.indexOf(':');
449
- if (idx > -1) {
450
- const prefix = resolvedId.substring(0, idx);
451
- const localPart = resolvedId.substring(idx + 1);
452
- if (localPart.startsWith('//')) {
453
- // Full URI -> return
454
- return resolvedTerm;
455
- }
456
- const resolvedPrefix = resolveTerm(prefix, contextStack);
457
- if (resolvedPrefix !== null && '@id' in resolvedPrefix && typeof resolvedPrefix['@id'] === 'string') {
458
- // Prefix found and resolved
459
- resolvedTerm['@id'] = `${resolvedPrefix['@id']}${localPart}`;
460
- }
461
- return resolvedTerm;
462
- }
463
- }
464
- if (closestVocab === null && contextStack[i]['@vocab']) {
465
- closestVocab = contextStack[i]['@vocab'];
466
- }
467
- if (closestBase === null && contextStack[i]['@base']) {
468
- closestBase = contextStack[i]['@base'];
469
- }
470
- }
471
- if (term.indexOf(':') === -1) {
472
- if (useVocab && closestVocab) {
473
- return { '@id': `${closestVocab}${term}` };
474
- }
475
- if (useBase && closestBase) {
476
- return { '@id': `${closestBase}${term}` };
477
- }
478
- }
479
- else {
480
- const idx = term.indexOf(':');
481
- const prefix = term.substring(0, idx);
482
- const localPart = term.substring(idx + 1);
483
- if (!localPart.startsWith('//')) {
484
- const resolvedPrefix = resolveTerm(prefix, contextStack);
485
- if (resolvedPrefix !== null && '@id' in resolvedPrefix && typeof resolvedPrefix['@id'] === 'string') {
486
- return { '@id': `${resolvedPrefix['@id']}${localPart}` };
487
- }
488
- }
489
- }
490
- return null;
491
- };
492
- const findPropertyChildren = (elem) => {
493
- const walker = document.createTreeWalker(elem, NodeFilter.SHOW_ELEMENT, {
494
- acceptNode(node) {
495
- const nodeElem = node;
496
- if (node !== elem && nodeElem.classList.contains('object-value')) {
497
- return NodeFilter.FILTER_REJECT;
498
- }
499
- if (nodeElem.classList.contains('object-property')) {
500
- return NodeFilter.FILTER_ACCEPT;
501
- }
502
- return NodeFilter.FILTER_SKIP;
503
- },
504
- });
505
- const result = [];
506
- let cur;
507
- while ((cur = walker.nextNode())) {
508
- result.push(cur);
509
- }
510
- return result;
511
- };
512
- const findLiteralChildren = (elem) => {
513
- const result = [];
514
- const walker = document.createTreeWalker(elem, NodeFilter.SHOW_ELEMENT, {
515
- acceptNode(node) {
516
- const nodeElem = node;
517
- if (nodeElem.classList.contains('object-property') || nodeElem.classList.contains('object-value')) {
518
- return NodeFilter.FILTER_REJECT;
519
- }
520
- if (nodeElem.classList.contains('literal-value')) {
521
- result.push(nodeElem);
522
- return NodeFilter.FILTER_REJECT;
523
- }
524
- return NodeFilter.FILTER_SKIP;
525
- },
526
- });
527
- while (walker.nextNode()) {
736
+ const { baseUrl } = mergedOptions;
737
+ // Outermost object tables below an element (looking through arrays and wrappers)
738
+ const findTables = (elem) => Array.from(elem.children).flatMap(child => child.classList.contains('object-table') ? [child] : findTables(child));
739
+ // Literal values of a cell, not including those that belong to nested objects
740
+ const findLiterals = (elem) => Array.from(elem.children).flatMap(child => {
741
+ if (child.classList.contains('literal-value')) {
742
+ return [child];
528
743
  }
529
- return result;
530
- };
744
+ return child.classList.contains('object-table') ? [] : findLiterals(child);
745
+ });
531
746
  const updateElement = (elem, resourceUri, replaceElements = true) => {
532
747
  elem.setAttribute('data-uri', resourceUri);
533
748
  elem.classList.add('resource-loading');
@@ -566,41 +781,99 @@ async function augment(rootElem, context, options = {}) {
566
781
  elem.appendChild(link);
567
782
  }
568
783
  };
569
- const augmentInner = (elem, contextStack) => {
570
- var _a;
571
- const propElems = findPropertyChildren(elem);
572
- for (const propElem of propElems) {
573
- let propertyName = null;
574
- propertyName = propElem.getAttribute('data-property');
575
- if (!propertyName) {
576
- propertyName = propElem.textContent.trim();
784
+ const linkLiterals = (valueElem, stack, expandOptions) => {
785
+ for (const literalElem of findLiterals(valueElem)) {
786
+ const iri = expandIri(literalElem.textContent.trim(), stack, { ...expandOptions, baseUrl });
787
+ if (iri && !iri.startsWith('@')) {
788
+ updateElement(literalElem, iri, mergedOptions.replaceElements);
577
789
  }
578
- const resolvedProperty = resolveTerm(propertyName, contextStack);
579
- let newContextStack = contextStack;
580
- const valueElem = (_a = propElem.parentElement) === null || _a === void 0 ? void 0 : _a.querySelector('.object-value');
581
- if (resolvedProperty && '@id' in resolvedProperty && typeof resolvedProperty['@id'] === 'string') {
582
- const propertyUri = resolvedProperty['@id'];
583
- updateElement(propElem, propertyUri, mergedOptions.replaceElements);
584
- if ('@context' in resolvedProperty) {
585
- newContextStack = [...contextStack, resolvedProperty['@context']];
790
+ }
791
+ };
792
+ // The stack with the object's own context on top, if it has a loadable one
793
+ const pushEmbedded = async (stack, context) => {
794
+ try {
795
+ // Loading modifies the context, which belongs to the caller's data
796
+ const copy = JSON.parse(JSON.stringify(context));
797
+ const entries = await loadContextEntries(copy, { baseUrl, requestTimeout: mergedOptions.requestTimeout });
798
+ return entries.reduce(pushContext, stack);
799
+ }
800
+ catch (e) {
801
+ console.warn(`Error loading embedded context: ${e}`, { cause: e });
802
+ return stack;
803
+ }
804
+ };
805
+ const augmentNode = async (table, inheritedStack) => {
806
+ const embedded = embeddedContexts.get(table);
807
+ // Only wait when there is something to load
808
+ const stack = embedded === undefined ? inheritedStack : await pushEmbedded(inheritedStack, embedded);
809
+ const children = [];
810
+ const rows = Array.from(table.querySelectorAll(':scope > tbody > tr')).flatMap(row => {
811
+ const propElem = row.querySelector(':scope > .object-property');
812
+ if (!propElem) {
813
+ return [];
814
+ }
815
+ return [{
816
+ propElem,
817
+ valueElem: row.querySelector(':scope > .object-value'),
818
+ name: propElem.getAttribute('data-property') || propElem.textContent.trim(),
819
+ }];
820
+ });
821
+ // Type-scoped contexts apply to this node only, in lexicographical order of the types
822
+ const types = rows
823
+ .filter(({ name }) => asKeyword(name, stack) === '@type')
824
+ .flatMap(({ valueElem }) => valueElem ? findLiterals(valueElem) : [])
825
+ .map(elem => elem.textContent.trim())
826
+ .sort();
827
+ const nodeStack = types.reduce((result, type) => {
828
+ var _a;
829
+ const scoped = (_a = findTerm(type, stack)) === null || _a === void 0 ? void 0 : _a['@context'];
830
+ return scoped === undefined ? result : pushContext(result, scoped);
831
+ }, stack);
832
+ for (const { propElem, valueElem, name } of rows) {
833
+ const keyword = asKeyword(name, nodeStack);
834
+ let childStack = stack;
835
+ if (keyword === '@type') {
836
+ // Types are resolved before applying their scoped contexts
837
+ if (valueElem) {
838
+ linkLiterals(valueElem, stack, { vocab: true, base: true });
839
+ }
840
+ updateElement(propElem, RDF_TYPE, mergedOptions.replaceElements);
841
+ }
842
+ else if (keyword === '@id') {
843
+ if (valueElem) {
844
+ linkLiterals(valueElem, nodeStack, { base: true });
845
+ }
846
+ }
847
+ else if (keyword) {
848
+ // Other keywords (@graph, @reverse, @nest...) keep the current context
849
+ childStack = nodeStack;
850
+ }
851
+ else {
852
+ const definition = findTerm(name, nodeStack);
853
+ const propertyUri = expandIri(name, nodeStack, { vocab: true });
854
+ if (propertyUri) {
855
+ updateElement(propElem, propertyUri, mergedOptions.replaceElements);
856
+ }
857
+ if ((definition === null || definition === void 0 ? void 0 : definition['@context']) !== undefined) {
858
+ childStack = pushContext(stack, definition['@context']);
586
859
  }
587
- if (resolvedProperty['@type'] === '@id' && valueElem) {
588
- const literalElems = findLiteralChildren(valueElem);
589
- literalElems.forEach(literalElem => {
590
- const resolvedLiteral = resolveTerm(literalElem.textContent.trim(), newContextStack, false, true);
591
- if (resolvedLiteral && '@id' in resolvedLiteral && typeof resolvedLiteral['@id'] === 'string') {
592
- const resourceUri = resolvedLiteral['@id'];
593
- updateElement(literalElem, resourceUri, mergedOptions.replaceElements);
594
- }
595
- });
860
+ const coercion = definition === null || definition === void 0 ? void 0 : definition['@type'];
861
+ if (valueElem && (coercion === '@id' || coercion === '@vocab')) {
862
+ const valueStack = (definition === null || definition === void 0 ? void 0 : definition['@context']) === undefined
863
+ ? nodeStack : pushContext(nodeStack, definition['@context']);
864
+ linkLiterals(valueElem, valueStack, { vocab: coercion === '@vocab', base: true });
596
865
  }
597
866
  }
598
867
  if (valueElem) {
599
- augmentInner(valueElem, newContextStack);
868
+ children.push(...findTables(valueElem).map(child => augmentNode(child, childStack)));
600
869
  }
601
870
  }
871
+ await Promise.all(children);
602
872
  };
603
- augmentInner(rootElem, [context]);
873
+ const rootStack = pushContext([], context !== null && context !== void 0 ? context : {});
874
+ const rootTables = rootElem.classList.contains('object-table')
875
+ ? [rootElem] : findTables(rootElem);
876
+ await Promise.all(rootTables.map(table => augmentNode(table, rootStack)));
604
877
  }
605
878
 
606
879
  var augment$1 = /*#__PURE__*/Object.freeze({
@@ -622,5 +895,6 @@ exports.defaultFetchResourceOptions = defaultFetchResourceOptions;
622
895
  exports.fetchResource = fetchResource;
623
896
  exports.findInStore = findInStore;
624
897
  exports.loadContext = loadContext;
898
+ exports.loadContextEntries = loadContextEntries;
625
899
  exports.loadFeature = loadFeature;
626
900
  //# sourceMappingURL=index.cjs.js.map