@opengeospatial/jsonld-ui-utils 0.4.12 → 0.5.1

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