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