eyemind 0.9.18 → 0.9.19

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/src/jsonld.js ADDED
@@ -0,0 +1,906 @@
1
+ // JSON-LD in eyemind, as the JSON-LD 1.2 Processing Algorithms and API
2
+ // define it: a document deserialized to RDF (context processing, expansion,
3
+ // node map generation and conversion to RDF), giving the same quads as the
4
+ // other RDF formats, and RDF serialized as JSON-LD. The processing mode is
5
+ // json-ld-1.2 unless json-ld-1.1 or json-ld-1.0 is asked for. Remote contexts
6
+ // come from a loader the caller supplies; eyemind itself never fetches one.
7
+ // Errors carry the code the specification names.
8
+ // https://w3c.github.io/json-ld-api/
9
+ import { resolveIriRef } from './rdf-prelude.js';
10
+
11
+ const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
12
+ const XSD = 'http://www.w3.org/2001/XMLSchema#';
13
+ const KEYWORDS = new Set(['@base', '@container', '@context', '@direction', '@graph', '@id', '@import', '@included', '@index',
14
+ '@json', '@language', '@list', '@nest', '@none', '@prefix', '@propagate', '@protected', '@reverse', '@set', '@type', '@value',
15
+ '@version', '@vocab']);
16
+ const CONTAINERS = ['@graph', '@id', '@index', '@language', '@list', '@set', '@type'];
17
+ const TERM_KEYS = new Set(['@id', '@reverse', '@container', '@context', '@direction', '@index', '@language', '@nest', '@prefix', '@protected', '@type']);
18
+ const MAX_REMOTE = 32;
19
+
20
+ class JsonLdError extends Error {
21
+ constructor(code, message = code) {
22
+ super(message === code ? code : `${code}: ${message}`);
23
+ this.code = code;
24
+ }
25
+ }
26
+
27
+ const fail = (code, message) => { throw new JsonLdError(code, message); };
28
+ const isKeyword = (v) => KEYWORDS.has(v);
29
+ const keywordLike = (v) => typeof v === 'string' && /^@[A-Za-z]+$/.test(v);
30
+ const isMap = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
31
+ const asArray = (v) => (Array.isArray(v) ? v : [v]);
32
+ const isScalar = (v) => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';
33
+ const absolute = (v) => typeof v === 'string' && /^[A-Za-z][A-Za-z0-9+.-]*:/.test(v);
34
+ const isBlank = (v) => typeof v === 'string' && v.startsWith('_:');
35
+ const isValue = (v) => isMap(v) && '@value' in v;
36
+ const isList = (v) => isMap(v) && '@list' in v;
37
+ const isGraph = (v) => isMap(v) && '@graph' in v && Object.keys(v).every((k) => k === '@graph' || k === '@id' || k === '@index');
38
+ const resolve = (ref, base) => (base == null ? ref : resolveIriRef(ref, base));
39
+ const sortedKeys = (map) => Object.keys(map).sort();
40
+
41
+ function newContext(base, mode) {
42
+ return { base, originalBase: base, vocab: null, language: null, direction: null, terms: new Map(), previous: null, mode };
43
+ }
44
+ const cloneContext = (c) => ({ ...c, terms: new Map(c.terms) });
45
+
46
+ // Options: base, processingMode, expandContext, loadDocument(url) returning
47
+ // { document, documentUrl }.
48
+ export function jsonLdToRdf(input, options = {}) {
49
+ const state = { options, contexts: new Map(), blanks: new Map(), counter: 0 };
50
+ const document = typeof input === 'string' ? parseJson(input) : input;
51
+ const base = options.base ?? null;
52
+ let active = newContext(base, options.processingMode ?? 'json-ld-1.2');
53
+ if (options.expandContext) {
54
+ let ctx = options.expandContext;
55
+ if (typeof ctx === 'string') ctx = load(state, resolve(ctx, base)).document;
56
+ if (isMap(ctx) && '@context' in ctx) ctx = ctx['@context'];
57
+ active = processContext(state, active, ctx, base);
58
+ }
59
+ let expanded = expand(state, active, null, document, base, false);
60
+ if (isMap(expanded) && Object.keys(expanded).length === 1 && '@graph' in expanded) expanded = expanded['@graph'];
61
+ expanded = expanded == null ? [] : asArray(expanded);
62
+ const nodeMap = { '@default': {} };
63
+ nodes(state, expanded, nodeMap, '@default');
64
+ return toRdf(state, nodeMap, options);
65
+ }
66
+
67
+ function parseJson(text) {
68
+ try {
69
+ return JSON.parse(text);
70
+ } catch (error) {
71
+ return fail('loading document failed', `the JSON is malformed: ${error.message}`);
72
+ }
73
+ }
74
+
75
+ function load(state, url) {
76
+ if (state.contexts.has(url)) return state.contexts.get(url);
77
+ if (!state.options.loadDocument) fail('loading remote context failed', `${url} is not available; eyemind reads no remote documents`);
78
+ let loaded;
79
+ try {
80
+ loaded = state.options.loadDocument(url);
81
+ } catch (error) {
82
+ return fail('loading remote context failed', `${url}: ${error.message}`);
83
+ }
84
+ const document = typeof loaded.document === 'string' ? (() => {
85
+ try { return JSON.parse(loaded.document); } catch { return fail('loading remote context failed', `${url} is not JSON`); }
86
+ })() : loaded.document;
87
+ const result = { document, documentUrl: loaded.documentUrl ?? url };
88
+ state.contexts.set(url, result);
89
+ return result;
90
+ }
91
+
92
+ // 4.1.2 Context Processing.
93
+ function processContext(state, active, local, baseUrl, remote = [], overrideProtected = false, propagate = true, validate = true) {
94
+ let result = cloneContext(active);
95
+ if (isMap(local) && '@propagate' in local) {
96
+ if (typeof local['@propagate'] !== 'boolean') fail('invalid @propagate value');
97
+ propagate = local['@propagate'];
98
+ }
99
+ if (!propagate && !result.previous) result.previous = active;
100
+ for (let context of asArray(local)) {
101
+ if (context === null) {
102
+ if (!overrideProtected && [...result.terms.values()].some((d) => d.protected)) fail('invalid context nullification');
103
+ const previous = result;
104
+ result = newContext(active.originalBase, active.mode);
105
+ if (!propagate) result.previous = previous;
106
+ continue;
107
+ }
108
+ if (typeof context === 'string') {
109
+ const url = resolve(context, baseUrl);
110
+ if (!validate && remote.includes(url)) continue;
111
+ if (remote.includes(url)) fail('recursive context inclusion', url);
112
+ if (remote.length > MAX_REMOTE) fail('context overflow');
113
+ const loaded = load(state, url);
114
+ if (!isMap(loaded.document) || !('@context' in loaded.document)) fail('invalid remote context', url);
115
+ result = processContext(state, result, loaded.document['@context'], loaded.documentUrl, [...remote, url], overrideProtected, true, validate);
116
+ continue;
117
+ }
118
+ if (!isMap(context)) fail('invalid local context');
119
+ context = { ...context };
120
+ if ('@version' in context) {
121
+ if (context['@version'] !== 1.1 && context['@version'] !== 1.2) fail('invalid @version value');
122
+ if (result.mode === 'json-ld-1.0') fail('processing mode conflict');
123
+ }
124
+ if ('@import' in context) {
125
+ if (result.mode === 'json-ld-1.0') fail('invalid context entry', '@import');
126
+ if (typeof context['@import'] !== 'string') fail('invalid @import value');
127
+ const loaded = load(state, resolve(context['@import'], baseUrl));
128
+ const imported = loaded.document?.['@context'];
129
+ if (!isMap(imported)) fail('invalid remote context', '@import needs a context map');
130
+ if ('@import' in imported) fail('invalid context entry', 'an imported context cannot import');
131
+ context = { ...imported, ...context };
132
+ }
133
+ if ('@base' in context && remote.length === 0) {
134
+ const value = context['@base'];
135
+ if (value === null) result.base = null;
136
+ else if (typeof value !== 'string') fail('invalid base IRI');
137
+ else if (absolute(value)) result.base = value;
138
+ else if (result.base != null) result.base = resolve(value, result.base);
139
+ else fail('invalid base IRI', value);
140
+ }
141
+ if ('@vocab' in context) {
142
+ const value = context['@vocab'];
143
+ if (value === null) result.vocab = null;
144
+ else if (typeof value !== 'string') fail('invalid vocab mapping');
145
+ else if (absolute(value) || isBlank(value) || result.mode !== 'json-ld-1.0') {
146
+ result.vocab = expandIri(state, result, value, true, true);
147
+ if (!absolute(result.vocab) && !isBlank(result.vocab) && result.vocab !== '') fail('invalid vocab mapping', value);
148
+ } else fail('invalid vocab mapping', value);
149
+ }
150
+ if ('@language' in context) {
151
+ const value = context['@language'];
152
+ if (value === null) result.language = null;
153
+ else if (typeof value !== 'string') fail('invalid default language');
154
+ else result.language = value.toLowerCase();
155
+ }
156
+ if ('@direction' in context) {
157
+ if (result.mode === 'json-ld-1.0') fail('invalid context entry', '@direction');
158
+ const value = context['@direction'];
159
+ if (value === null) result.direction = null;
160
+ else if (value !== 'ltr' && value !== 'rtl') fail('invalid base direction');
161
+ else result.direction = value;
162
+ }
163
+ if ('@propagate' in context && result.mode === 'json-ld-1.0') fail('invalid context entry', '@propagate');
164
+ const defined = new Map();
165
+ const protectedDefault = context['@protected'] ?? false;
166
+ for (const term of Object.keys(context)) {
167
+ if (['@base', '@direction', '@import', '@language', '@propagate', '@protected', '@version', '@vocab'].includes(term)) continue;
168
+ defineTerm(state, result, context, term, defined, baseUrl, protectedDefault, overrideProtected, remote, validate);
169
+ }
170
+ }
171
+ return result;
172
+ }
173
+
174
+ // 4.2.2 Create Term Definition.
175
+ function defineTerm(state, active, local, term, defined, baseUrl, protectedDefault = false, overrideProtected = false, remote = [], validate = true) {
176
+ if (defined.get(term) === true) return;
177
+ if (defined.get(term) === false) fail('cyclic IRI mapping', term);
178
+ if (term === '') fail('invalid term definition', 'the empty term');
179
+ defined.set(term, false);
180
+ let value = local[term];
181
+ if (term === '@type' && active.mode !== 'json-ld-1.0' && isMap(value) &&
182
+ Object.keys(value).length && Object.keys(value).every((k) => k === '@container' || k === '@protected') &&
183
+ (!('@container' in value) || value['@container'] === '@set')) {
184
+ // @type may be given a @set container and protection.
185
+ } else if (isKeyword(term)) fail('keyword redefinition', term);
186
+ else if (keywordLike(term)) { defined.set(term, true); return; }
187
+ const previous = active.terms.get(term);
188
+ active.terms.delete(term);
189
+ let simple = false;
190
+ if (value === null || typeof value === 'string') {
191
+ simple = typeof value === 'string';
192
+ value = { '@id': value };
193
+ } else if (!isMap(value)) fail('invalid term definition', term);
194
+ const definition = { prefix: false, protected: protectedDefault, reverse: false };
195
+ if ('@protected' in value) {
196
+ if (active.mode === 'json-ld-1.0') fail('invalid term definition', '@protected');
197
+ if (typeof value['@protected'] !== 'boolean') fail('invalid @protected value');
198
+ definition.protected = value['@protected'];
199
+ }
200
+ if ('@type' in value) {
201
+ let type = value['@type'];
202
+ if (typeof type !== 'string') fail('invalid type mapping', term);
203
+ type = expandIri(state, active, type, false, true, local, defined);
204
+ if ((type === '@json' || type === '@none') && active.mode === 'json-ld-1.0') fail('invalid type mapping', type);
205
+ if (!['@id', '@vocab', '@json', '@none'].includes(type) && !absolute(type)) fail('invalid type mapping', type);
206
+ definition.type = type;
207
+ }
208
+ if ('@reverse' in value) {
209
+ if ('@id' in value || '@nest' in value) fail('invalid reverse property', term);
210
+ if (typeof value['@reverse'] !== 'string') fail('invalid IRI mapping', term);
211
+ if (keywordLike(value['@reverse'])) { defined.set(term, true); return; }
212
+ definition.iri = expandIri(state, active, value['@reverse'], false, true, local, defined);
213
+ if (!definition.iri || !definition.iri.includes(':')) fail('invalid IRI mapping', term);
214
+ if ('@container' in value) {
215
+ if (![null, '@set', '@index'].includes(value['@container'])) fail('invalid reverse property', term);
216
+ if (value['@container'] !== null) definition.container = [value['@container']];
217
+ }
218
+ definition.reverse = true;
219
+ // Since the 2023 erratum, the other entries of a reverse definition are
220
+ // processed as those of any term definition.
221
+ } else if ('@id' in value && value['@id'] !== term) {
222
+ const id = value['@id'];
223
+ if (id === null) definition.iri = null;
224
+ else {
225
+ if (typeof id !== 'string') fail('invalid IRI mapping', term);
226
+ if (!isKeyword(id) && keywordLike(id)) { defined.set(term, true); return; }
227
+ definition.iri = expandIri(state, active, id, false, true, local, defined);
228
+ if (!isKeyword(definition.iri) && !absolute(definition.iri) && !isBlank(definition.iri)) fail('invalid IRI mapping', term);
229
+ if (definition.iri === '@context') fail('invalid keyword alias', term);
230
+ // JSON-LD 1.0 lets a term that looks like a compact IRI map elsewhere.
231
+ if (active.mode !== 'json-ld-1.0' && (term.slice(1, -1).includes(':') || term.includes('/'))) {
232
+ defined.set(term, true);
233
+ if (expandIri(state, active, term, false, true, local, defined) !== definition.iri) fail('invalid IRI mapping', term);
234
+ }
235
+ if (!term.includes(':') && !term.includes('/') && simple && (/[:/?#[\]@]$/.test(definition.iri) || isBlank(definition.iri))) {
236
+ definition.prefix = true;
237
+ }
238
+ }
239
+ } else if (term.slice(1).includes(':')) {
240
+ const colon = term.indexOf(':', 1);
241
+ const prefix = term.slice(0, colon), suffix = term.slice(colon + 1);
242
+ if (prefix in local) defineTerm(state, active, local, prefix, defined, baseUrl, protectedDefault, overrideProtected, remote, validate);
243
+ const prefixDefinition = active.terms.get(prefix);
244
+ definition.iri = prefixDefinition?.iri != null ? prefixDefinition.iri + suffix : term;
245
+ } else if (term.includes('/')) {
246
+ definition.iri = expandIri(state, active, term, false, true);
247
+ if (!absolute(definition.iri)) fail('invalid IRI mapping', term);
248
+ } else if (term === '@type') {
249
+ definition.iri = '@type';
250
+ } else {
251
+ if (active.vocab == null) fail('invalid IRI mapping', `${term} needs a vocabulary mapping`);
252
+ definition.iri = active.vocab + term;
253
+ }
254
+ if ('@container' in value && !definition.reverse) {
255
+ const container = value['@container'];
256
+ const items = asArray(container);
257
+ if (!items.every((c) => CONTAINERS.includes(c))) fail('invalid container mapping', term);
258
+ if (active.mode === 'json-ld-1.0' && (Array.isArray(container) || ['@graph', '@id', '@type'].includes(container))) fail('invalid container mapping', term);
259
+ const set = new Set(items);
260
+ const valid = items.length === 1 ||
261
+ (set.has('@graph') && (set.has('@id') || set.has('@index')) && items.length <= 3 && [...set].every((c) => ['@graph', '@id', '@index', '@set'].includes(c)) && !(set.has('@id') && set.has('@index'))) ||
262
+ (set.has('@set') && items.length === 2 && [...set].some((c) => ['@index', '@graph', '@id', '@type', '@language'].includes(c))) ||
263
+ (set.has('@set') && set.has('@graph') && items.length === 2);
264
+ if (!valid || set.has('@list') && items.length > 1) fail('invalid container mapping', term);
265
+ definition.container = items;
266
+ if (set.has('@type')) {
267
+ if (definition.type === undefined) definition.type = '@id';
268
+ if (!['@id', '@vocab'].includes(definition.type)) fail('invalid type mapping', term);
269
+ }
270
+ }
271
+ if ('@index' in value) {
272
+ if (active.mode === 'json-ld-1.0' || !definition.container?.includes('@index')) fail('invalid term definition', `${term} has @index without an index container`);
273
+ const index = value['@index'];
274
+ if (typeof index !== 'string' || isKeyword(expandIri(state, active, index, false, true))) fail('invalid term definition', `${term} has an invalid @index`);
275
+ definition.index = index;
276
+ }
277
+ if ('@context' in value) {
278
+ if (active.mode === 'json-ld-1.0') fail('invalid term definition', '@context');
279
+ try {
280
+ processContext(state, active, value['@context'], baseUrl, [...remote], true, true, false);
281
+ } catch (error) {
282
+ if (error instanceof JsonLdError) fail('invalid scoped context', `${term}: ${error.message}`);
283
+ throw error;
284
+ }
285
+ definition.context = value['@context'];
286
+ definition.baseUrl = baseUrl;
287
+ }
288
+ if ('@language' in value && !('@type' in value)) {
289
+ const language = value['@language'];
290
+ if (language !== null && typeof language !== 'string') fail('invalid language mapping', term);
291
+ definition.language = language === null ? null : language.toLowerCase();
292
+ }
293
+ if ('@direction' in value && !('@type' in value)) {
294
+ const direction = value['@direction'];
295
+ if (direction !== null && direction !== 'ltr' && direction !== 'rtl') fail('invalid base direction', term);
296
+ definition.direction = direction;
297
+ }
298
+ if ('@nest' in value) {
299
+ if (active.mode === 'json-ld-1.0') fail('invalid term definition', '@nest');
300
+ const nest = value['@nest'];
301
+ if (typeof nest !== 'string' || (isKeyword(nest) && nest !== '@nest')) fail('invalid @nest value', term);
302
+ definition.nest = nest;
303
+ }
304
+ if ('@prefix' in value) {
305
+ if (active.mode === 'json-ld-1.0' || term.includes(':') || term.includes('/')) fail('invalid term definition', `${term} cannot have @prefix`);
306
+ if (typeof value['@prefix'] !== 'boolean') fail('invalid @prefix value', term);
307
+ definition.prefix = value['@prefix'];
308
+ if (definition.prefix && isKeyword(definition.iri)) fail('invalid term definition', `${term} is a keyword alias`);
309
+ }
310
+ for (const key of Object.keys(value)) if (!TERM_KEYS.has(key)) fail('invalid term definition', `${term} has ${key}`);
311
+ if (!overrideProtected && previous?.protected) {
312
+ const same = (d) => JSON.stringify([d.iri, d.prefix, d.reverse, d.type, d.container, d.index, d.language, d.direction, d.nest, d.context]);
313
+ if (same(previous) !== same(definition)) fail('protected term redefinition', term);
314
+ active.terms.set(term, previous);
315
+ } else active.terms.set(term, definition);
316
+ defined.set(term, true);
317
+ }
318
+
319
+ // 5.2.2 IRI Expansion.
320
+ function expandIri(state, active, value, documentRelative = false, vocab = false, local = null, defined = null) {
321
+ if (value === null || isKeyword(value)) return value;
322
+ if (keywordLike(value)) return null;
323
+ if (local && value in local && defined?.get(value) !== true) defineTerm(state, active, local, value, defined);
324
+ const definition = active.terms.get(value);
325
+ if (definition && isKeyword(definition.iri)) return definition.iri;
326
+ if (vocab && active.terms.has(value)) return definition.iri ?? null;
327
+ const colon = value.indexOf(':', 1);
328
+ if (colon > 0) {
329
+ const prefix = value.slice(0, colon), suffix = value.slice(colon + 1);
330
+ if (prefix === '_' || suffix.startsWith('//')) return value;
331
+ if (local && prefix in local && defined?.get(prefix) !== true) defineTerm(state, active, local, prefix, defined);
332
+ const prefixDefinition = active.terms.get(prefix);
333
+ // JSON-LD 1.0 has no prefix flag: any term is a prefix.
334
+ if (prefixDefinition?.iri != null && (prefixDefinition.prefix || active.mode === 'json-ld-1.0')) return prefixDefinition.iri + suffix;
335
+ if (absolute(value)) return value;
336
+ }
337
+ if (vocab && active.vocab != null) return active.vocab + value;
338
+ if (documentRelative) return resolve(value, active.base);
339
+ return value;
340
+ }
341
+
342
+ // 5.3.2 Value Expansion.
343
+ function expandValue(state, active, property, value) {
344
+ const definition = active.terms.get(property);
345
+ if (definition?.type === '@id' && typeof value === 'string') return { '@id': expandIri(state, active, value, true, false) };
346
+ if (definition?.type === '@vocab' && typeof value === 'string') return { '@id': expandIri(state, active, value, true, true) };
347
+ const result = { '@value': value };
348
+ if (definition?.type !== undefined && !['@id', '@vocab', '@none'].includes(definition.type)) result['@type'] = definition.type;
349
+ else if (typeof value === 'string') {
350
+ const language = definition && 'language' in definition ? definition.language : active.language;
351
+ const direction = definition && 'direction' in definition ? definition.direction : active.direction;
352
+ if (language != null) result['@language'] = language;
353
+ if (direction != null) result['@direction'] = direction;
354
+ }
355
+ return result;
356
+ }
357
+
358
+ // 5.1.2 Expansion.
359
+ function expand(state, active, property, element, baseUrl, fromMap) {
360
+ if (element === null || element === undefined) return null;
361
+ const definition = property === null ? undefined : active.terms.get(property);
362
+ const scoped = definition && 'context' in definition ? definition : null;
363
+ if (isScalar(element)) {
364
+ if (property === null || property === '@graph') return null;
365
+ if (scoped) active = processContext(state, active, scoped.context, scoped.baseUrl);
366
+ return expandValue(state, active, property, element);
367
+ }
368
+ if (Array.isArray(element)) {
369
+ const result = [];
370
+ for (const item of element) {
371
+ let expanded = expand(state, active, property, item, baseUrl, fromMap);
372
+ const listed = definition?.container?.includes('@list');
373
+ if (active.mode === 'json-ld-1.0' && listed && (Array.isArray(expanded) || isList(expanded))) fail('list of lists');
374
+ if (listed && Array.isArray(expanded)) expanded = { '@list': expanded };
375
+ if (Array.isArray(expanded)) result.push(...expanded);
376
+ else if (expanded !== null) result.push(expanded);
377
+ }
378
+ return result;
379
+ }
380
+ if (!isMap(element)) return null;
381
+ if (active.previous && !fromMap) {
382
+ const keys = Object.keys(element).map((k) => expandIri(state, active, k, false, true));
383
+ if (!keys.includes('@value') && !(keys.length === 1 && keys[0] === '@id')) active = active.previous;
384
+ }
385
+ if (scoped) active = processContext(state, active, scoped.context, scoped.baseUrl, [], true);
386
+ if ('@context' in element) active = processContext(state, active, element['@context'], baseUrl);
387
+ const typeScoped = active;
388
+ let inputType = null;
389
+ for (const key of sortedKeys(element)) {
390
+ if (expandIri(state, active, key, false, true) !== '@type') continue;
391
+ const types = asArray(element[key]).filter((t) => typeof t === 'string').sort();
392
+ for (const type of types) {
393
+ const typeDefinition = typeScoped.terms.get(type);
394
+ if (typeDefinition && 'context' in typeDefinition) {
395
+ active = processContext(state, active, typeDefinition.context, typeDefinition.baseUrl, [], false, false);
396
+ }
397
+ }
398
+ if (types.length) inputType = expandIri(state, active, types.at(-1), false, true);
399
+ }
400
+ const result = {};
401
+ // A key aliasing @nest applies its scoped context to what it nests.
402
+ const nested = (keys, map, context) => {
403
+ for (const key of keys) {
404
+ const definition = context.terms.get(key);
405
+ const inner = definition && 'context' in definition ? processContext(state, context, definition.context, definition.baseUrl, [], true) : context;
406
+ for (const value of asArray(map[key] ?? [])) {
407
+ if (!isMap(value) || Object.keys(value).some((k) => expandIri(state, inner, k, false, true) === '@value')) fail('invalid @nest value');
408
+ const deeper = [];
409
+ entries(state, inner, typeScoped, property, value, baseUrl, inputType, result, deeper);
410
+ nested(deeper, value, inner);
411
+ }
412
+ }
413
+ };
414
+ const nests = [];
415
+ entries(state, active, typeScoped, property, element, baseUrl, inputType, result, nests);
416
+ nested(nests, element, active);
417
+ // A node whose @id is ignored, such as an unknown keyword, is dropped.
418
+ if (!('@id' in result) && Object.keys(element).some((k) => expandIri(state, active, k, false, true) === '@id')) return null;
419
+ if ('@value' in result) {
420
+ const keys = Object.keys(result);
421
+ if (keys.some((k) => !['@direction', '@index', '@language', '@type', '@value'].includes(k))) fail('invalid value object');
422
+ if ('@type' in result && ('@language' in result || '@direction' in result)) fail('invalid value object');
423
+ if (result['@type'] === '@json') return result;
424
+ if (result['@value'] === null) return null;
425
+ if ('@language' in result && typeof result['@value'] !== 'string') fail('invalid language-tagged value');
426
+ if ('@type' in result && (typeof result['@type'] !== 'string' || !absolute(result['@type']) || /\s/.test(result['@type']))) fail('invalid typed value');
427
+ if (!isScalar(result['@value'])) fail('invalid value object value');
428
+ return dropTop(result, property);
429
+ }
430
+ if ('@type' in result && !Array.isArray(result['@type'])) result['@type'] = [result['@type']];
431
+ if ('@set' in result || '@list' in result) {
432
+ if (Object.keys(result).some((k) => k !== '@set' && k !== '@list' && k !== '@index')) fail('invalid set or list object');
433
+ if ('@set' in result) return result['@set'];
434
+ }
435
+ if (Object.keys(result).length === 1 && '@language' in result) return null;
436
+ return dropTop(result, property);
437
+ }
438
+
439
+ function dropTop(result, property) {
440
+ if (property !== null && property !== '@graph') return result;
441
+ const keys = Object.keys(result);
442
+ if (keys.length === 0 || '@value' in result || '@list' in result) return null;
443
+ if (keys.length === 1 && keys[0] === '@id') return null;
444
+ return result;
445
+ }
446
+
447
+ // Step 13 of expansion: the entries of a map, and of the maps it nests.
448
+ function entries(state, active, typeScoped, property, element, baseUrl, inputType, result, nests) {
449
+ for (const key of sortedKeys(element)) {
450
+ const value = element[key];
451
+ if (key === '@context') continue;
452
+ const expandedProperty = expandIri(state, active, key, false, true);
453
+ if (expandedProperty === null || (!expandedProperty.includes(':') && !isKeyword(expandedProperty))) continue;
454
+ if (isKeyword(expandedProperty)) {
455
+ if (property === '@reverse') fail('invalid reverse property map');
456
+ if (expandedProperty in result && !(active.mode !== 'json-ld-1.0' && ['@included', '@type'].includes(expandedProperty))) fail('colliding keywords', expandedProperty);
457
+ let expanded;
458
+ switch (expandedProperty) {
459
+ case '@id':
460
+ if (typeof value !== 'string') fail('invalid @id value');
461
+ expanded = expandIri(state, active, value, true, false);
462
+ break;
463
+ case '@type':
464
+ if (!(typeof value === 'string' || (Array.isArray(value) && value.every((v) => typeof v === 'string')))) fail('invalid type value');
465
+ expanded = asArray(value).map((v) => expandIri(state, typeScoped, v, true, true));
466
+ if (!Array.isArray(value)) expanded = expanded[0];
467
+ if ('@type' in result) expanded = [...asArray(result['@type']), ...asArray(expanded)];
468
+ break;
469
+ case '@graph':
470
+ expanded = asArray(expand(state, active, '@graph', value, baseUrl, false) ?? []);
471
+ break;
472
+ case '@included': {
473
+ if (active.mode === 'json-ld-1.0') continue;
474
+ if (!asArray(value).every((v) => isMap(v) && !Object.keys(v).some((k) => ['@value', '@list'].includes(expandIri(state, active, k, false, true))))) {
475
+ fail('invalid @included value');
476
+ }
477
+ expanded = asArray(expand(state, active, null, value, baseUrl, false) ?? []);
478
+ if (!expanded.every((v) => isMap(v) && !isValue(v) && !isList(v) && !('@set' in v))) fail('invalid @included value');
479
+ if ('@included' in result) expanded = [...result['@included'], ...expanded];
480
+ break;
481
+ }
482
+ case '@value':
483
+ if (inputType === '@json') {
484
+ if (active.mode === 'json-ld-1.0') fail('invalid value object value');
485
+ expanded = value;
486
+ } else if (value !== null && !isScalar(value)) fail('invalid value object value');
487
+ else expanded = value;
488
+ result['@value'] = expanded;
489
+ continue;
490
+ case '@language':
491
+ if (typeof value !== 'string') fail('invalid language-tagged string');
492
+ expanded = value.toLowerCase();
493
+ break;
494
+ case '@direction':
495
+ if (active.mode === 'json-ld-1.0') continue;
496
+ if (value !== 'ltr' && value !== 'rtl') fail('invalid base direction');
497
+ expanded = value;
498
+ break;
499
+ case '@index':
500
+ if (typeof value !== 'string') fail('invalid @index value');
501
+ expanded = value;
502
+ break;
503
+ case '@list':
504
+ if (property === null || property === '@graph') continue;
505
+ expanded = asArray(expand(state, active, property, value, baseUrl, false) ?? []);
506
+ if (active.mode === 'json-ld-1.0' && expanded.some(isList)) fail('list of lists');
507
+ break;
508
+ case '@set':
509
+ expanded = expand(state, active, property, value, baseUrl, false);
510
+ break;
511
+ case '@reverse': {
512
+ if (!isMap(value)) fail('invalid @reverse value');
513
+ const inner = expand(state, active, '@reverse', value, baseUrl, false) ?? {};
514
+ if ('@reverse' in inner) for (const [p, items] of Object.entries(inner['@reverse'])) result[p] = [...(result[p] ?? []), ...asArray(items)];
515
+ const reverse = result['@reverse'] ?? {};
516
+ for (const [p, items] of Object.entries(inner)) {
517
+ if (p === '@reverse') continue;
518
+ for (const item of asArray(items)) {
519
+ if (isValue(item) || isList(item)) fail('invalid reverse property value');
520
+ (reverse[p] ??= []).push(item);
521
+ }
522
+ }
523
+ if (Object.keys(reverse).length) result['@reverse'] = reverse;
524
+ continue;
525
+ }
526
+ case '@nest':
527
+ nests.push(key);
528
+ continue;
529
+ default:
530
+ continue;
531
+ }
532
+ if (expanded !== null && expanded !== undefined) result[expandedProperty] = expanded;
533
+ continue;
534
+ }
535
+ const definition = active.terms.get(key);
536
+ const container = definition?.container ?? [];
537
+ let expanded;
538
+ if (definition?.type === '@json') {
539
+ expanded = { '@value': value, '@type': '@json' };
540
+ } else if (container.includes('@language') && isMap(value)) {
541
+ expanded = [];
542
+ const direction = definition && 'direction' in definition ? definition.direction : active.direction;
543
+ for (const language of sortedKeys(value)) {
544
+ for (const item of asArray(value[language])) {
545
+ if (item === null) continue;
546
+ if (typeof item !== 'string') fail('invalid language map value');
547
+ const v = { '@value': item };
548
+ if (expandIri(state, active, language, false, true) !== '@none') v['@language'] = language.toLowerCase();
549
+ if (direction != null) v['@direction'] = direction;
550
+ expanded.push(v);
551
+ }
552
+ }
553
+ } else if ((container.includes('@index') || container.includes('@type') || container.includes('@id')) && isMap(value)) {
554
+ expanded = [];
555
+ const indexKey = definition.index ?? '@index';
556
+ for (const index of sortedKeys(value)) {
557
+ let mapContext = (container.includes('@id') || container.includes('@type')) && active.previous ? active.previous : active;
558
+ const indexDefinition = active.terms.get(index);
559
+ if (container.includes('@type') && indexDefinition && 'context' in indexDefinition) {
560
+ mapContext = processContext(state, mapContext, indexDefinition.context, indexDefinition.baseUrl);
561
+ }
562
+ const expandedIndex = expandIri(state, active, index, false, true);
563
+ const items = asArray(expand(state, mapContext, key, asArray(value[index]), baseUrl, true) ?? []);
564
+ for (let item of items) {
565
+ if (container.includes('@graph') && !isGraph(item)) item = { '@graph': asArray(item) };
566
+ if (container.includes('@index') && indexKey !== '@index' && expandedIndex !== '@none') {
567
+ const reExpanded = expandValue(state, active, indexKey, index);
568
+ const property = expandIri(state, active, indexKey, false, true);
569
+ if (isValue(item)) fail('invalid value object', 'a property-valued index needs a node');
570
+ item[property] = [reExpanded, ...asArray(item[property] ?? [])];
571
+ } else if (container.includes('@index') && !('@index' in item) && expandedIndex !== '@none') {
572
+ item['@index'] = index;
573
+ } else if (container.includes('@id') && !('@id' in item) && expandedIndex !== '@none') {
574
+ item['@id'] = expandIri(state, active, index, true, false);
575
+ } else if (container.includes('@type') && expandedIndex !== '@none') {
576
+ item['@type'] = [expandedIndex, ...asArray(item['@type'] ?? [])];
577
+ }
578
+ expanded.push(item);
579
+ }
580
+ }
581
+ } else {
582
+ expanded = expand(state, active, key, value, baseUrl, false);
583
+ }
584
+ if (expanded === null || expanded === undefined) continue;
585
+ if (container.includes('@list') && !isList(expanded)) expanded = { '@list': asArray(expanded) };
586
+ if (container.includes('@graph') && !container.includes('@id') && !container.includes('@index')) {
587
+ expanded = asArray(expanded).map((v) => ({ '@graph': asArray(v) }));
588
+ }
589
+ if (definition?.reverse) {
590
+ const reverse = result['@reverse'] ??= {};
591
+ for (const item of asArray(expanded)) {
592
+ if (isValue(item) || isList(item)) fail('invalid reverse property value');
593
+ (reverse[expandedProperty] ??= []).push(item);
594
+ }
595
+ } else {
596
+ result[expandedProperty] = [...(result[expandedProperty] ?? []), ...asArray(expanded)];
597
+ }
598
+ }
599
+ }
600
+
601
+ function blank(state, id) {
602
+ if (id != null && state.blanks.has(id)) return state.blanks.get(id);
603
+ const label = `_:b${state.counter++}`;
604
+ if (id != null) state.blanks.set(id, label);
605
+ return label;
606
+ }
607
+
608
+ // 7.2.2 Node Map Generation.
609
+ function nodes(state, element, map, graphName, subject = null, property = null, list = null) {
610
+ if (Array.isArray(element)) {
611
+ for (const item of element) nodes(state, item, map, graphName, subject, property, list);
612
+ return;
613
+ }
614
+ const graph = map[graphName] ??= {};
615
+ const subjectNode = typeof subject === 'string' ? graph[subject] : null;
616
+ if (Array.isArray(element['@type'])) element['@type'] = element['@type'].map((t) => (isBlank(t) ? blank(state, t) : t));
617
+ if ('@value' in element) {
618
+ if (list === null) {
619
+ const values = subjectNode[property] ??= [];
620
+ if (!values.some((v) => JSON.stringify(v) === JSON.stringify(element))) values.push(element);
621
+ } else list['@list'].push(element);
622
+ return;
623
+ }
624
+ if ('@list' in element) {
625
+ const result = { '@list': [] };
626
+ nodes(state, element['@list'], map, graphName, subject, property, result);
627
+ if (list === null) (subjectNode[property] ??= []).push(result);
628
+ else list['@list'].push(result);
629
+ return;
630
+ }
631
+ let id = element['@id'];
632
+ if (id === undefined || id === null) id = blank(state, null);
633
+ else if (isBlank(id)) id = blank(state, id);
634
+ const node = graph[id] ??= { '@id': id };
635
+ if (isMap(subject)) {
636
+ const values = node[property] ??= [];
637
+ if (!values.some((v) => v['@id'] === subject['@id'])) values.push(subject);
638
+ } else if (property !== null) {
639
+ const reference = { '@id': id };
640
+ if (list === null) {
641
+ const values = subjectNode[property] ??= [];
642
+ if (!values.some((v) => v['@id'] === id)) values.push(reference);
643
+ } else list['@list'].push(reference);
644
+ }
645
+ if ('@type' in element) node['@type'] = [...new Set([...(node['@type'] ?? []), ...element['@type']])];
646
+ if ('@index' in element) {
647
+ if ('@index' in node && node['@index'] !== element['@index']) fail('conflicting indexes');
648
+ node['@index'] = element['@index'];
649
+ }
650
+ if ('@reverse' in element) {
651
+ const referenced = { '@id': id };
652
+ for (const [p, values] of Object.entries(element['@reverse'])) for (const value of values) nodes(state, value, map, graphName, referenced, p);
653
+ }
654
+ if ('@graph' in element) nodes(state, element['@graph'], map, id);
655
+ if ('@included' in element) nodes(state, element['@included'], map, graphName);
656
+ for (const p of sortedKeys(element)) {
657
+ if (['@id', '@type', '@index', '@reverse', '@graph', '@included'].includes(p)) continue;
658
+ const name = isBlank(p) ? blank(state, p) : p;
659
+ node[name] ??= [];
660
+ nodes(state, element[p], map, graphName, id, name);
661
+ }
662
+ }
663
+
664
+ const wellFormed = (v) => typeof v === 'string' && (isBlank(v) || (absolute(v) && !/[\s<>"{}|\\^`]/.test(v) && !/#.*#/.test(v)));
665
+ const wellFormedLanguage = (v) => /^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/.test(v);
666
+
667
+ // 8.1.2 Deserialize JSON-LD to RDF: [subject, predicate, object, graph] as
668
+ // { termType, value, datatype?, language?, direction? } objects.
669
+ function toRdf(state, map, { rdfDirection = null, produceGeneralizedRdf = false }) {
670
+ const quads = [];
671
+ const term = (v) => (isBlank(v) ? { termType: 'blank', value: v.slice(2) } : { termType: 'iri', value: v });
672
+ for (const graphName of sortedKeys(map)) {
673
+ if (graphName !== '@default' && !wellFormed(graphName)) continue;
674
+ const graph = graphName === '@default' ? null : term(graphName);
675
+ for (const subject of sortedKeys(map[graphName])) {
676
+ if (!wellFormed(subject)) continue;
677
+ const node = map[graphName][subject];
678
+ for (const property of sortedKeys(node)) {
679
+ if (property === '@type') {
680
+ for (const type of node['@type']) if (wellFormed(type)) quads.push([term(subject), term(`${RDF}type`), term(type), graph]);
681
+ continue;
682
+ }
683
+ if (isKeyword(property)) continue;
684
+ if (isBlank(property) && !produceGeneralizedRdf) continue;
685
+ if (!wellFormed(property)) continue;
686
+ for (const item of node[property]) {
687
+ const extra = [];
688
+ const object = objectToRdf(state, item, extra, rdfDirection, term);
689
+ if (object !== null) quads.push([term(subject), term(property), object, graph]);
690
+ for (const [s, p, o] of extra) quads.push([s, p, o, graph]);
691
+ }
692
+ }
693
+ }
694
+ }
695
+ return quads;
696
+ }
697
+
698
+ // 8.2.2 Object to RDF Conversion, and 8.3 List Conversion.
699
+ function objectToRdf(state, item, extra, rdfDirection, term) {
700
+ if (!isValue(item) && !isList(item)) return wellFormed(item['@id']) ? term(item['@id']) : null;
701
+ if (isList(item)) {
702
+ const items = item['@list'];
703
+ if (!items.length) return term(`${RDF}nil`);
704
+ const cells = items.map(() => blank(state, null));
705
+ items.forEach((value, i) => {
706
+ const object = objectToRdf(state, value, extra, rdfDirection, term);
707
+ if (object !== null) extra.push([term(cells[i]), term(`${RDF}first`), object]);
708
+ extra.push([term(cells[i]), term(`${RDF}rest`), term(cells[i + 1] ?? `${RDF}nil`)]);
709
+ });
710
+ return term(cells[0]);
711
+ }
712
+ let value = item['@value'];
713
+ let datatype = item['@type'] ?? null;
714
+ if (datatype !== null && datatype !== '@json' && !wellFormed(datatype)) return null;
715
+ if ('@language' in item && !wellFormedLanguage(item['@language'])) return null;
716
+ if (datatype === '@json') {
717
+ value = canonicalJson(value);
718
+ datatype = `${RDF}JSON`;
719
+ } else if (typeof value === 'boolean') {
720
+ value = String(value);
721
+ datatype ??= `${XSD}boolean`;
722
+ } else if (typeof value === 'number' && (!Number.isInteger(value) || Math.abs(value) >= 1e21 || datatype === `${XSD}double`)) {
723
+ value = canonicalDouble(value);
724
+ datatype ??= `${XSD}double`;
725
+ } else if (typeof value === 'number') {
726
+ value = BigInt(value).toString();
727
+ datatype ??= `${XSD}integer`;
728
+ } else if (datatype === null) {
729
+ datatype = '@language' in item ? `${RDF}langString` : `${XSD}string`;
730
+ }
731
+ if ('@direction' in item && rdfDirection !== null) {
732
+ const language = (item['@language'] ?? '').toLowerCase();
733
+ if (rdfDirection === 'i18n-datatype') {
734
+ return { termType: 'literal', value, datatype: `https://www.w3.org/ns/i18n#${language}_${item['@direction']}` };
735
+ }
736
+ if (rdfDirection === 'compound-literal') {
737
+ const node = term(blank(state, null));
738
+ extra.push([node, term(`${RDF}value`), { termType: 'literal', value, datatype: `${XSD}string` }]);
739
+ if ('@language' in item) extra.push([node, term(`${RDF}language`), { termType: 'literal', value: language, datatype: `${XSD}string` }]);
740
+ extra.push([node, term(`${RDF}direction`), { termType: 'literal', value: item['@direction'], datatype: `${XSD}string` }]);
741
+ return node;
742
+ }
743
+ }
744
+ if ('@language' in item) return { termType: 'literal', value, language: item['@language'].toLowerCase() };
745
+ return { termType: 'literal', value, datatype };
746
+ }
747
+
748
+ // XSD's canonical double: one digit before the point, at least one after.
749
+ function canonicalDouble(n) {
750
+ if (Number.isNaN(n)) return 'NaN';
751
+ if (!Number.isFinite(n)) return n > 0 ? 'INF' : '-INF';
752
+ let [mantissa, exponent] = n.toExponential().split('e');
753
+ if (!mantissa.includes('.')) mantissa += '.0';
754
+ return `${mantissa}E${Number(exponent)}`;
755
+ }
756
+
757
+ // The JSON Canonicalization Scheme (RFC 8785): sorted keys, ES numbers.
758
+ function canonicalJson(value) {
759
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
760
+ if (isMap(value)) return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`;
761
+ return JSON.stringify(value);
762
+ }
763
+
764
+ // 8.4 Serialize RDF as JSON-LD: [subject, predicate, object, graph] quads of
765
+ // { termType, value, datatype?, language?, direction? } terms, graph null for
766
+ // the default one, to expanded JSON-LD, with each named graph nested in its
767
+ // node. Options: useNativeTypes, useRdfType, rdfDirection, processingMode.
768
+ export function rdfToJsonLd(quads, { useNativeTypes = false, useRdfType = false, rdfDirection = null, processingMode = 'json-ld-1.2' } = {}) {
769
+ const id = (t) => (t.termType === 'blank' ? `_:${t.value}` : t.value);
770
+ const graphs = new Map([['@default', new Map()]]);
771
+ const once = new Map(), compound = new Map(), nil = new Map();
772
+ for (const [s, p, o, g] of quads) {
773
+ if (s.termType === 'triple' || o.termType === 'triple') fail('invalid RDF term', 'JSON-LD has no triple terms');
774
+ const name = g ? id(g) : '@default';
775
+ if (!graphs.has(name)) graphs.set(name, new Map());
776
+ if (name !== '@default' && !graphs.get('@default').has(name)) graphs.get('@default').set(name, { '@id': name });
777
+ const nodes = graphs.get(name);
778
+ const subject = id(s);
779
+ if (!nodes.has(subject)) nodes.set(subject, { '@id': subject });
780
+ const node = nodes.get(subject);
781
+ if (rdfDirection === 'compound-literal' && p.value === `${RDF}direction`) {
782
+ if (!compound.has(name)) compound.set(name, new Set());
783
+ compound.get(name).add(subject);
784
+ }
785
+ if (o.termType !== 'literal' && !nodes.has(id(o))) nodes.set(id(o), { '@id': id(o) });
786
+ if (p.value === `${RDF}type` && !useRdfType && o.termType !== 'literal') {
787
+ const types = node['@type'] ??= [];
788
+ if (!types.includes(id(o))) types.push(id(o));
789
+ continue;
790
+ }
791
+ const value = rdfToObject(o, { useNativeTypes, rdfDirection, processingMode, id });
792
+ const values = node[p.value] ??= [];
793
+ // A duplicate triple adds no value, and no second reference.
794
+ if (values.some((v) => JSON.stringify(v) === JSON.stringify(value))) continue;
795
+ values.push(value);
796
+ if (o.termType === 'iri' && o.value === `${RDF}nil`) {
797
+ if (!nil.has(name)) nil.set(name, []);
798
+ nil.get(name).push({ node, property: p.value, value });
799
+ } else if (o.termType !== 'literal') {
800
+ // A blank node referenced from more than one place, in any graph, is
801
+ // no list cell.
802
+ if (once.has(id(o))) once.set(id(o), false);
803
+ else if (o.termType === 'blank') once.set(id(o), { node, property: p.value, value });
804
+ }
805
+ }
806
+ for (const [name, nodes] of graphs) {
807
+ // Compound literals become value objects with a language and direction.
808
+ for (const subject of compound.get(name) ?? []) {
809
+ const usage = once.get(subject);
810
+ if (!usage) continue;
811
+ const literal = nodes.get(subject);
812
+ nodes.delete(subject);
813
+ for (const reference of usage.node[usage.property]) {
814
+ if (reference['@id'] !== subject) continue;
815
+ delete reference['@id'];
816
+ reference['@value'] = literal[`${RDF}value`]?.[0]?.['@value'];
817
+ const language = literal[`${RDF}language`]?.[0]?.['@value'];
818
+ if (language !== undefined) {
819
+ if (!wellFormedLanguage(language)) fail('invalid language-tagged string', language);
820
+ reference['@language'] = language;
821
+ }
822
+ const direction = literal[`${RDF}direction`]?.[0]?.['@value'];
823
+ if (direction !== undefined) {
824
+ if (direction !== 'ltr' && direction !== 'rtl') fail('invalid base direction', direction);
825
+ reference['@direction'] = direction;
826
+ }
827
+ }
828
+ }
829
+ // Well-formed rdf:first and rdf:rest chains of blank nodes become lists.
830
+ for (const usage of nil.get(name) ?? []) {
831
+ let { node, property, value: head } = usage;
832
+ const list = [], cells = [];
833
+ while (property === `${RDF}rest` && isBlank(node['@id'])) {
834
+ const listed = once.get(node['@id']);
835
+ const keys = Object.keys(node);
836
+ const first = node[`${RDF}first`], rest = node[`${RDF}rest`];
837
+ if (!isMap(listed) || first?.length !== 1 || rest?.length !== 1 ||
838
+ !keys.every((k) => ['@id', `${RDF}first`, `${RDF}rest`, '@type'].includes(k)) ||
839
+ ('@type' in node && !(node['@type'].length === 1 && node['@type'][0] === `${RDF}List`))) break;
840
+ list.push(first[0]);
841
+ cells.push(node['@id']);
842
+ ({ node, property, value: head } = listed);
843
+ if (!isBlank(node['@id'])) break;
844
+ }
845
+ // JSON-LD 1.0 keeps the head of a list that is an item of another list.
846
+ if (processingMode === 'json-ld-1.0' && property === `${RDF}first`) {
847
+ if (node['@id'] === `${RDF}nil`) continue;
848
+ head = nodes.get(head['@id'])[`${RDF}rest`][0];
849
+ list.pop();
850
+ cells.pop();
851
+ }
852
+ delete head['@id'];
853
+ head['@list'] = list.reverse();
854
+ for (const cell of cells) nodes.delete(cell);
855
+ }
856
+ }
857
+ const result = [];
858
+ const sorted = (map) => [...map.keys()].sort();
859
+ const defaults = graphs.get('@default');
860
+ for (const subject of sorted(defaults)) {
861
+ const node = defaults.get(subject);
862
+ if (graphs.has(subject) && subject !== '@default') {
863
+ const inner = graphs.get(subject);
864
+ node['@graph'] = sorted(inner).map((s) => inner.get(s)).filter((n) => Object.keys(n).length > 1);
865
+ }
866
+ if (Object.keys(node).length > 1) result.push(node);
867
+ }
868
+ return result;
869
+ }
870
+
871
+ // 8.5 RDF to Object Conversion.
872
+ function rdfToObject(o, { useNativeTypes, rdfDirection, processingMode, id }) {
873
+ if (o.termType !== 'literal') return { '@id': id(o) };
874
+ const result = {};
875
+ let value = o.value, type = null;
876
+ const datatype = o.datatype ?? (o.language ? `${RDF}langString` : `${XSD}string`);
877
+ if (useNativeTypes && datatype === `${XSD}string` && !o.language) {
878
+ // A plain string is a JSON string.
879
+ } else if (useNativeTypes && datatype === `${XSD}boolean` && ['true', 'false', '1', '0'].includes(value)) {
880
+ value = value === 'true' || value === '1';
881
+ } else if (useNativeTypes && datatype === `${XSD}integer` && /^[+-]?[0-9]+$/.test(value) && Number.isSafeInteger(Number(value))) {
882
+ value = Number(value);
883
+ } else if (useNativeTypes && datatype === `${XSD}double` && /^[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/.test(value) &&
884
+ Number.isFinite(Number(value))) {
885
+ value = Number(value);
886
+ } else if (processingMode !== 'json-ld-1.0' && datatype === `${RDF}JSON`) {
887
+ try {
888
+ value = JSON.parse(value);
889
+ } catch {
890
+ fail('invalid JSON literal', o.value);
891
+ }
892
+ type = '@json';
893
+ } else if (rdfDirection === 'i18n-datatype' && datatype.startsWith('https://www.w3.org/ns/i18n#')) {
894
+ const [language, direction] = datatype.slice('https://www.w3.org/ns/i18n#'.length).split('_');
895
+ if (language) result['@language'] = language;
896
+ if (direction) result['@direction'] = direction;
897
+ } else if (o.language) {
898
+ result['@language'] = o.language;
899
+ if (o.direction) result['@direction'] = o.direction;
900
+ } else if (datatype !== `${XSD}string`) {
901
+ type = datatype;
902
+ }
903
+ result['@value'] = value;
904
+ if (type !== null) result['@type'] = type;
905
+ return result;
906
+ }