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/LS-SPEC.md +1 -1
- package/README.md +25 -14
- package/package.json +1 -1
- package/src/cli.js +7 -7
- package/src/formats.js +18 -6
- package/src/index.js +1 -1
- package/src/jsonld.js +906 -0
- package/src/messages.js +103 -3
- package/src/node-messages.js +2 -1
- package/src/rdf-lexer.js +11 -4
- package/src/rdf-parser.js +3 -0
- package/src/rdf-xml.js +363 -0
- package/src/rdf.js +92 -7
- package/src/version.js +1 -1
- package/src/xml.js +174 -0
package/src/messages.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// RDF Message Logs: delimit datasets before parsing them, so blank nodes and
|
|
2
2
|
// assertions stay local to a message. The replay view is ordinary N3 data.
|
|
3
3
|
// See https://w3c-cg.github.io/rsp/spec/messages and its companion tests.
|
|
4
|
-
import { DEFAULT_GRAPH, parseRdf } from './rdf.js';
|
|
4
|
+
import { DEFAULT_GRAPH, parseRdf, parseRdfXmlLog, writeRdf } from './rdf.js';
|
|
5
5
|
import { readSources } from './n3.js';
|
|
6
6
|
import { tripleToEyemind } from './n3-writer.js';
|
|
7
7
|
import { EyemindError } from './terms.js';
|
|
@@ -15,6 +15,8 @@ const triple = (s, p, o) => ({ s, p: iri(p), o });
|
|
|
15
15
|
const int = (v) => ({ t: 'int', v: BigInt(v) });
|
|
16
16
|
const wordEnd = (c) => c === undefined || /[\s<>"'{}\[\]();,]/.test(c);
|
|
17
17
|
const iriText = (v) => v.replace(/[\u0000-\u0020<>"{}|^`\\]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
18
|
+
// The start of an RDF/XML message log: its rdfm:MessageLog root.
|
|
19
|
+
const XML_LOG = /^\s*(?:<\?xml[^>]*\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<(?:[\w.-]+:)?MessageLog[\s>/]/;
|
|
18
20
|
function trivia(s, at, final) {
|
|
19
21
|
while (at < s.length) {
|
|
20
22
|
if (/\s/.test(s[at])) at++;
|
|
@@ -30,9 +32,12 @@ function trivia(s, at, final) {
|
|
|
30
32
|
// Accept strings incrementally. Only the current message and active directive
|
|
31
33
|
// context are retained; onMessage runs before reading any further input.
|
|
32
34
|
export class RdfMessageReader {
|
|
33
|
-
constructor({ format = 'trig', base = null, scope = 'messages', onMessage = () => {}, probe = false } = {}) {
|
|
34
|
-
if (!['turtle', 'trig', 'n-triples', 'n-quads'].includes(format)) throw new EyemindError(`RDF Messages do not support the format ${format}`);
|
|
35
|
+
constructor({ format = 'trig', base = null, scope = 'messages', onMessage = () => {}, probe = false, loadDocument = null } = {}) {
|
|
36
|
+
if (!['turtle', 'trig', 'n-triples', 'n-quads', 'rdf-xml', 'ndjson-ld'].includes(format)) throw new EyemindError(`RDF Messages do not support the format ${format}`);
|
|
35
37
|
this.format = format;
|
|
38
|
+
this.loadDocument = loadDocument;
|
|
39
|
+
this.context = undefined;
|
|
40
|
+
this.line = 0;
|
|
36
41
|
this.base = base;
|
|
37
42
|
this.scope = scope;
|
|
38
43
|
this.onMessage = onMessage;
|
|
@@ -55,6 +60,20 @@ export class RdfMessageReader {
|
|
|
55
60
|
write(text) {
|
|
56
61
|
if (this.stopped) return;
|
|
57
62
|
this.buffer += text;
|
|
63
|
+
// An RDF/XML log is one XML document, read when it is complete.
|
|
64
|
+
if (this.format === 'rdf-xml') return;
|
|
65
|
+
if (this.format === 'ndjson-ld') {
|
|
66
|
+
for (let end = this.buffer.indexOf('\n'); end >= 0 && !this.stopped; end = this.buffer.indexOf('\n')) {
|
|
67
|
+
const line = this.buffer.slice(0, end);
|
|
68
|
+
this.buffer = this.buffer.slice(end + 1);
|
|
69
|
+
this.ndjsonLine(line.replace(/\r$/, ''));
|
|
70
|
+
}
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (this.probe && XML_LOG.test(this.buffer)) {
|
|
74
|
+
this.isLog = true;
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
58
77
|
this.scan(false);
|
|
59
78
|
if (this.probe) {
|
|
60
79
|
this.buffer = this.buffer.slice(this.at);
|
|
@@ -64,6 +83,24 @@ export class RdfMessageReader {
|
|
|
64
83
|
|
|
65
84
|
finish() {
|
|
66
85
|
if (this.stopped) { this.buffer = ''; return; }
|
|
86
|
+
if (this.format === 'ndjson-ld') {
|
|
87
|
+
if (this.buffer !== '') this.ndjsonLine(this.buffer.replace(/\r$/, ''));
|
|
88
|
+
this.buffer = '';
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
if (this.format === 'rdf-xml') {
|
|
92
|
+
try {
|
|
93
|
+
for (const message of parseRdfXmlLog(this.buffer, { base: this.base, scope: this.scope })) {
|
|
94
|
+
this.index = message.index;
|
|
95
|
+
if (this.onMessage(message) === false) break;
|
|
96
|
+
}
|
|
97
|
+
} catch (error) {
|
|
98
|
+
throw new EyemindError(`RDF Message Log: ${error.message}`);
|
|
99
|
+
} finally {
|
|
100
|
+
this.buffer = '';
|
|
101
|
+
}
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
67
104
|
this.scan(true);
|
|
68
105
|
if (!this.probe) {
|
|
69
106
|
if (!this.isLog) throw new EyemindError('RDF Message Log needs a VERSION "*-messages" directive');
|
|
@@ -72,6 +109,39 @@ export class RdfMessageReader {
|
|
|
72
109
|
this.buffer = '';
|
|
73
110
|
}
|
|
74
111
|
|
|
112
|
+
// A line of an NDJSON-LD log: a context message, whose @context is the
|
|
113
|
+
// active context for the messages that follow, an empty message {}, or a
|
|
114
|
+
// data message, read as the document {"@context": C, "@graph": message}.
|
|
115
|
+
// https://w3c-cg.github.io/rsp/spec/messages#ndjson-ld
|
|
116
|
+
ndjsonLine(line) {
|
|
117
|
+
this.line++;
|
|
118
|
+
let object;
|
|
119
|
+
try {
|
|
120
|
+
object = JSON.parse(line);
|
|
121
|
+
} catch {
|
|
122
|
+
object = null;
|
|
123
|
+
}
|
|
124
|
+
if (line.trim() === '') throw new EyemindError(`RDF Message Log line ${this.line}: NDJSON-LD allows no blank lines`);
|
|
125
|
+
if (object === null || typeof object !== 'object' || Array.isArray(object)) {
|
|
126
|
+
throw new EyemindError(`RDF Message Log line ${this.line}: each line of NDJSON-LD is one JSON object`);
|
|
127
|
+
}
|
|
128
|
+
const keys = Object.keys(object);
|
|
129
|
+
if (keys.length === 1 && keys[0] === '@context') {
|
|
130
|
+
this.context = object['@context'];
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const document = keys.length === 0 ? null : this.context === undefined ? object : { '@context': this.context, '@graph': object };
|
|
134
|
+
const number = this.index + 1;
|
|
135
|
+
let quads = [];
|
|
136
|
+
try {
|
|
137
|
+
if (document) quads = parseRdf(JSON.stringify(document), { format: 'json-ld', base: this.base, scope: `${this.scope}#message${number}`, loadDocument: this.loadDocument }).quads;
|
|
138
|
+
} catch (error) {
|
|
139
|
+
throw new EyemindError(`RDF Message Log message ${number}: ${error.message}`);
|
|
140
|
+
}
|
|
141
|
+
this.isLog = true;
|
|
142
|
+
this.stopped = this.onMessage({ quads, prefixes: {}, base: this.base, index: ++this.index }) === false;
|
|
143
|
+
}
|
|
144
|
+
|
|
75
145
|
emit(text, boundary) {
|
|
76
146
|
if (this.probe) return;
|
|
77
147
|
const line = this.format === 'n-triples' || this.format === 'n-quads';
|
|
@@ -216,6 +286,7 @@ export class RdfMessageReader {
|
|
|
216
286
|
}
|
|
217
287
|
|
|
218
288
|
export function isRdfMessageLog(text) {
|
|
289
|
+
if (XML_LOG.test(text)) return true;
|
|
219
290
|
const reader = new RdfMessageReader({ probe: true });
|
|
220
291
|
try {
|
|
221
292
|
reader.write(String(text));
|
|
@@ -261,3 +332,32 @@ export function parseRdfMessages(text, options = {}) {
|
|
|
261
332
|
reader.finish();
|
|
262
333
|
return { ...replayMessages(messages, options), messages };
|
|
263
334
|
}
|
|
335
|
+
|
|
336
|
+
// An RDF Message Log of messages, each its quads: VERSION "1.2-messages"
|
|
337
|
+
// and a MESSAGE delimiter between messages in Turtle, TriG, N-Triples and
|
|
338
|
+
// N-Quads, an rdf:RDF per message in RDF/XML, and a line per message in
|
|
339
|
+
// NDJSON-LD. A final empty message needs one more delimiter, as a trailing
|
|
340
|
+
// delimiter alone opens no message.
|
|
341
|
+
export function writeRdfMessages(messages, { format = 'trig', prefixes = {} } = {}) {
|
|
342
|
+
if (format === 'ndjson-ld') {
|
|
343
|
+
return messages.map((quads) => `${quads.length ? JSON.stringify({ '@graph': JSON.parse(writeRdf(quads, { format: 'json-ld' })) }) : '{}'}\n`).join('');
|
|
344
|
+
}
|
|
345
|
+
if (format === 'rdf-xml') {
|
|
346
|
+
let version = '1.0';
|
|
347
|
+
const parts = messages.map((quads) => {
|
|
348
|
+
const text = writeRdf(quads, { format: 'rdf-xml', prefixes });
|
|
349
|
+
if (text.startsWith('<?xml version="1.1"')) version = '1.1';
|
|
350
|
+
return text.replace(/^<\?xml[^>]*\?>\n/, '').replace(/^/gm, ' ').trimEnd();
|
|
351
|
+
});
|
|
352
|
+
return `<?xml version="${version}" encoding="utf-8"?>\n<rdfm:MessageLog xmlns:rdfm="https://w3c-cg.github.io/rsp/spec/messages#">\n` +
|
|
353
|
+
parts.map((p) => `${p}\n`).join('') + '</rdfm:MessageLog>\n';
|
|
354
|
+
}
|
|
355
|
+
if (!['turtle', 'trig', 'n-triples', 'n-quads'].includes(format)) throw new EyemindError(`RDF Messages do not support the format ${format}`);
|
|
356
|
+
const out = ['VERSION "1.2-messages"\n'];
|
|
357
|
+
messages.forEach((quads, i) => {
|
|
358
|
+
if (i > 0) out.push('MESSAGE\n');
|
|
359
|
+
out.push(writeRdf(quads, { format, prefixes }));
|
|
360
|
+
});
|
|
361
|
+
if (messages.length && !messages.at(-1).length) out.push('MESSAGE\n');
|
|
362
|
+
return out.join('');
|
|
363
|
+
}
|
package/src/node-messages.js
CHANGED
|
@@ -11,6 +11,7 @@ const remote = (name) => /^https?:/.test(name);
|
|
|
11
11
|
async function messageFile(name) {
|
|
12
12
|
if (name === '-' || remote(name)) return true;
|
|
13
13
|
if (/\.js$/i.test(name)) return false;
|
|
14
|
+
if (rdfMessageFormat(name) === 'ndjson-ld') return true;
|
|
14
15
|
const probe = new RdfMessageReader({ probe: true });
|
|
15
16
|
for await (const text of createReadStream(name, { encoding: 'utf8' })) {
|
|
16
17
|
probe.write(text);
|
|
@@ -59,7 +60,7 @@ export async function streamMessages(request, io) {
|
|
|
59
60
|
if (await messageFile(name)) logs.push({ name, index });
|
|
60
61
|
else inputs.push([name, io.readFile(name)]);
|
|
61
62
|
}
|
|
62
|
-
if (!logs.length) throw new Error('--stream-messages needs an RDF Message Log
|
|
63
|
+
if (!logs.length) throw new Error('--stream-messages needs an RDF Message Log: VERSION "*-messages", an rdfm:MessageLog in RDF/XML, or NDJSON-LD (.ndjson)');
|
|
63
64
|
for (const { name, index } of logs) {
|
|
64
65
|
const source = await openSource(name);
|
|
65
66
|
const scope = request.scope(name, index);
|
package/src/rdf-lexer.js
CHANGED
|
@@ -259,9 +259,11 @@ function decodeIriRefEscapes(s, offset = null) {
|
|
|
259
259
|
for (let i = 0; i < s.length; i++) {
|
|
260
260
|
const c = s[i];
|
|
261
261
|
if (c !== '\\') {
|
|
262
|
-
|
|
262
|
+
// eyemind: by code point, so a character beyond U+FFFF is no lone surrogate.
|
|
263
|
+
const cp = s.codePointAt(i);
|
|
263
264
|
assertValidIriRefCodePoint(cp, offset);
|
|
264
|
-
out +=
|
|
265
|
+
out += String.fromCodePoint(cp);
|
|
266
|
+
if (cp > 0xffff) i++;
|
|
265
267
|
continue;
|
|
266
268
|
}
|
|
267
269
|
|
|
@@ -869,11 +871,16 @@ function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
|
|
|
869
871
|
}
|
|
870
872
|
}
|
|
871
873
|
|
|
872
|
-
// Not TriG named-graph syntax after all; copy the
|
|
873
|
-
// continue as ordinary N3.
|
|
874
|
+
// Not TriG named-graph syntax after all; copy the term, or else the
|
|
875
|
+
// first character, and continue as ordinary N3.
|
|
876
|
+
// eyemind: the whole term, so a # in its IRI is no comment.
|
|
874
877
|
if (graphKeyword) {
|
|
875
878
|
out += 'GRAPH ';
|
|
876
879
|
statementStart = false;
|
|
880
|
+
} else if (term && term.end > i) {
|
|
881
|
+
out += s.slice(i, term.end);
|
|
882
|
+
i = term.end;
|
|
883
|
+
statementStart = false;
|
|
877
884
|
} else if (i < s.length) {
|
|
878
885
|
const copied = s[i++];
|
|
879
886
|
out += copied;
|
package/src/rdf-parser.js
CHANGED
|
@@ -274,6 +274,9 @@ class Parser {
|
|
|
274
274
|
if (typ === 'LtLt') return this.parseReifiedTriple();
|
|
275
275
|
|
|
276
276
|
if (typ === 'IriRef') {
|
|
277
|
+
// eyemind: N-Triples and N-Quads take an IRI as written; Turtle and
|
|
278
|
+
// TriG resolve every IRI reference (RFC 3986, 5.2).
|
|
279
|
+
if (this.verbatimIris) return internIri(val || '');
|
|
277
280
|
const base = this.prefixes.baseIri || '';
|
|
278
281
|
return internIri(resolveIriRef(val || '', base));
|
|
279
282
|
}
|
package/src/rdf-xml.js
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
// RDF/XML in eyemind: the grammar of RDF 1.2 XML Syntax read from an XML
|
|
2
|
+
// tree, giving the same quads as the other RDF formats, and those quads
|
|
3
|
+
// written as RDF/XML. Where the RDF 1.2
|
|
4
|
+
// draft disagrees with itself, the W3C RDF/XML tests decide: a triple term
|
|
5
|
+
// (rdf:parseType="Triple") holds one node element with one property, and
|
|
6
|
+
// rdf:annotation or rdf:annotationNodeID names a reifier of its triple.
|
|
7
|
+
// https://www.w3.org/TR/rdf12-xml/#section-Infoset-Grammar
|
|
8
|
+
import { resolveIriRef } from './rdf-prelude.js';
|
|
9
|
+
import { Struct } from './terms.js';
|
|
10
|
+
import { isNcName, isXmlContent, parseXml } from './xml.js';
|
|
11
|
+
|
|
12
|
+
const RDF = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
|
|
13
|
+
const XML = 'http://www.w3.org/XML/1998/namespace';
|
|
14
|
+
const ITS = 'http://www.w3.org/2005/11/its';
|
|
15
|
+
|
|
16
|
+
// The names the grammar reserves (RDF 1.2 XML Syntax, 6.2.2 to 6.2.4).
|
|
17
|
+
const CORE = new Set(['RDF', 'ID', 'about', 'parseType', 'resource', 'nodeID', 'datatype', 'version', 'annotation', 'annotationNodeID']);
|
|
18
|
+
const OLD = new Set(['aboutEach', 'aboutEachPrefix', 'bagID']);
|
|
19
|
+
// Unqualified attributes that older documents use for their RDF names.
|
|
20
|
+
const UNQUALIFIED = new Set(['ID', 'about', 'resource', 'parseType', 'type', 'version']);
|
|
21
|
+
|
|
22
|
+
const st = (name, ...args) => new Struct(name, args);
|
|
23
|
+
const iri = (v) => st('iri', v);
|
|
24
|
+
// Whether an RDF version of 1.2 or later, such as 1.2-basic, is in scope.
|
|
25
|
+
const rdf12 = (context) => /^(?:1\.(?:[2-9]|[1-9][0-9]+)|[2-9]\.)/.test(context.version ?? '');
|
|
26
|
+
|
|
27
|
+
// Read an RDF/XML document into [S, P, O, G] quads of the default graph.
|
|
28
|
+
// The caller supplies the terms for literals, so they match the other formats.
|
|
29
|
+
export function parseRdfXml(source, options) {
|
|
30
|
+
const root = parseXml(source);
|
|
31
|
+
const top = { base: options.base ? options.base.replace(/#.*$/, '') : null, lang: '', dir: '', version: '' };
|
|
32
|
+
return { ...reader(options).document(root, top), prefixes: prefixesOf(root), base: top.base };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// The messages of an RDF Message Log in RDF/XML: an rdfm:MessageLog root
|
|
36
|
+
// whose rdf:RDF children are the messages, each with its own blank nodes.
|
|
37
|
+
// Namespaces, base, language and direction on the log apply to them all.
|
|
38
|
+
// https://w3c-cg.github.io/rsp/spec/messages#rdf-xml
|
|
39
|
+
const RDFM = 'https://w3c-cg.github.io/rsp/spec/messages#';
|
|
40
|
+
export function parseRdfXmlMessages(source, options) {
|
|
41
|
+
const root = parseXml(source);
|
|
42
|
+
if (root.ns !== RDFM || root.local !== 'MessageLog') throw new SyntaxError('an RDF/XML message log has an rdfm:MessageLog root');
|
|
43
|
+
const top = { base: options.base ? options.base.replace(/#.*$/, '') : null, lang: '', dir: '', version: '' };
|
|
44
|
+
const { context } = reader(options).contextOf(root, top);
|
|
45
|
+
const messages = [];
|
|
46
|
+
for (const child of root.children) {
|
|
47
|
+
if (child.type === 'text' && /\S/.test(child.value)) throw new SyntaxError('an RDF/XML message log holds only rdf:RDF elements');
|
|
48
|
+
if (child.type !== 'element') continue;
|
|
49
|
+
if (child.ns !== RDF || child.local !== 'RDF') throw new SyntaxError(`an RDF/XML message log holds rdf:RDF elements, not <${child.name}>`);
|
|
50
|
+
const scope = `${options.scope ?? 'messages'}#message${messages.length + 1}`;
|
|
51
|
+
messages.push({ ...reader({ ...options, scope }).document(child, context), prefixes: prefixesOf(root), base: context.base, index: messages.length + 1 });
|
|
52
|
+
}
|
|
53
|
+
return messages;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function reader({ scope = 'rdf', graph, literal }) {
|
|
57
|
+
const out = [];
|
|
58
|
+
const ids = new Set();
|
|
59
|
+
let blanks = 0;
|
|
60
|
+
const fail = (message) => { throw new SyntaxError(message); };
|
|
61
|
+
const fresh = () => st('bnode', scope, String(++blanks));
|
|
62
|
+
const node = (id) => {
|
|
63
|
+
if (!isNcName(id)) fail(`rdf:nodeID "${id}" is not an XML name`);
|
|
64
|
+
return st('bnode', scope, id);
|
|
65
|
+
};
|
|
66
|
+
const resolve = (ref, context) => iri(resolveIriRef(ref, context.base ?? ''));
|
|
67
|
+
const emit = (s, p, o, target = out) => target.push([s, p, o, graph]);
|
|
68
|
+
const rdf = (local) => iri(RDF + local);
|
|
69
|
+
|
|
70
|
+
// An element's context: base, language, direction and RDF version,
|
|
71
|
+
// inherited, and its attributes without the XML and ITS ones. Text
|
|
72
|
+
// direction (its:dir) needs an RDF version of 1.2 or later in scope.
|
|
73
|
+
const contextOf = (element, parent) => {
|
|
74
|
+
const context = { base: parent.base, lang: parent.lang, dir: parent.dir, version: parent.version };
|
|
75
|
+
const attrs = new Map();
|
|
76
|
+
const version = element.attrs.find((a) => a.local === 'version' && (a.ns === RDF || !a.ns));
|
|
77
|
+
if (version) context.version = version.value;
|
|
78
|
+
for (const a of element.attrs) {
|
|
79
|
+
if (a.ns === XML) {
|
|
80
|
+
if (a.local === 'base') context.base = resolveIriRef(a.value, parent.base ?? '').replace(/#.*$/, '');
|
|
81
|
+
else if (a.local === 'lang') context.lang = a.value.toLowerCase();
|
|
82
|
+
} else if (a.ns === ITS) {
|
|
83
|
+
if (a.local === 'dir' && rdf12(context)) {
|
|
84
|
+
if (!['ltr', 'rtl', ''].includes(a.value)) fail(`its:dir is ltr or rtl, not "${a.value}"`);
|
|
85
|
+
context.dir = a.value;
|
|
86
|
+
}
|
|
87
|
+
} else if (!a.ns && /^xml/i.test(a.local)) {
|
|
88
|
+
// Names starting with xml are reserved by XML and ignored here.
|
|
89
|
+
} else if (!a.ns) {
|
|
90
|
+
if (!UNQUALIFIED.has(a.local)) fail(`the attribute ${a.name} has no namespace`);
|
|
91
|
+
attrs.set(RDF + a.local, a.value);
|
|
92
|
+
} else attrs.set(a.ns + a.local, a.value);
|
|
93
|
+
}
|
|
94
|
+
attrs.delete(`${RDF}version`);
|
|
95
|
+
return { context, attrs };
|
|
96
|
+
};
|
|
97
|
+
const textOf = (element) => element.children.filter((c) => c.type === 'text').map((c) => c.value).join('');
|
|
98
|
+
const elements = (element) => {
|
|
99
|
+
const found = element.children.filter((c) => c.type === 'element');
|
|
100
|
+
if (found.length && /\S/.test(textOf(element))) fail(`<${element.name}> mixes text and elements`);
|
|
101
|
+
return found;
|
|
102
|
+
};
|
|
103
|
+
const plain = (value, context) => literal(value, context.lang ? { lang: context.lang, dir: context.dir } : null, null);
|
|
104
|
+
const idOf = (value, context) => {
|
|
105
|
+
if (!isNcName(value)) fail(`rdf:ID "${value}" is not an XML name`);
|
|
106
|
+
const id = resolveIriRef(`#${value}`, context.base ?? '');
|
|
107
|
+
if (ids.has(id)) fail(`rdf:ID "${value}" is used twice with one base`);
|
|
108
|
+
ids.add(id);
|
|
109
|
+
return iri(id);
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// A node element: its subject, type and property attributes, then its
|
|
113
|
+
// property elements. Returns the subject.
|
|
114
|
+
const nodeElement = (element, parent, target = out) => {
|
|
115
|
+
const name = element.ns + element.local;
|
|
116
|
+
if (name.startsWith(RDF) && (CORE.has(element.local) || OLD.has(element.local) || element.local === 'li')) {
|
|
117
|
+
fail(`rdf:${element.local} cannot name a node element`);
|
|
118
|
+
}
|
|
119
|
+
const { context, attrs } = contextOf(element, parent);
|
|
120
|
+
const ways = [`${RDF}ID`, `${RDF}about`, `${RDF}nodeID`].filter((k) => attrs.has(k));
|
|
121
|
+
if (ways.length > 1) fail(`<${element.name}> has more than one of rdf:ID, rdf:about and rdf:nodeID`);
|
|
122
|
+
let subject;
|
|
123
|
+
if (attrs.has(`${RDF}ID`)) subject = idOf(attrs.get(`${RDF}ID`), context);
|
|
124
|
+
else if (attrs.has(`${RDF}about`)) subject = resolve(attrs.get(`${RDF}about`), context);
|
|
125
|
+
else if (attrs.has(`${RDF}nodeID`)) subject = node(attrs.get(`${RDF}nodeID`));
|
|
126
|
+
else subject = fresh();
|
|
127
|
+
for (const k of ways) attrs.delete(k);
|
|
128
|
+
if (name !== `${RDF}Description`) emit(subject, rdf('type'), iri(name), target);
|
|
129
|
+
propertyAttributes(subject, attrs, context, target);
|
|
130
|
+
let li = 0;
|
|
131
|
+
for (const child of elements(element)) li = propertyElement(child, subject, context, li, target);
|
|
132
|
+
if (/\S/.test(textOf(element))) fail(`<${element.name}> has text, not property elements`);
|
|
133
|
+
return subject;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
// Property attributes of a node, or of the node an empty property element
|
|
137
|
+
// makes: each is a triple with a literal object, rdf:type an IRI one.
|
|
138
|
+
const propertyAttributes = (subject, attrs, context, target) => {
|
|
139
|
+
for (const [name, value] of attrs) {
|
|
140
|
+
if (name.startsWith(RDF) && (CORE.has(name.slice(RDF.length)) || OLD.has(name.slice(RDF.length)) || ['li', 'Description'].includes(name.slice(RDF.length)))) {
|
|
141
|
+
fail(`rdf:${name.slice(RDF.length)} cannot be a property attribute here`);
|
|
142
|
+
}
|
|
143
|
+
if (name === `${RDF}type`) emit(subject, rdf('type'), resolve(value, context), target);
|
|
144
|
+
else emit(subject, iri(name), plain(value, context), target);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
// The triples that an rdf:ID on a property element (reification) and an
|
|
149
|
+
// annotation (a reifier of a triple term) add.
|
|
150
|
+
const decorate = (s, p, o, attrs, context, target) => {
|
|
151
|
+
if (attrs.has(`${RDF}ID`)) {
|
|
152
|
+
const r = idOf(attrs.get(`${RDF}ID`), context);
|
|
153
|
+
emit(r, rdf('type'), rdf('Statement'), target);
|
|
154
|
+
emit(r, rdf('subject'), s, target);
|
|
155
|
+
emit(r, rdf('predicate'), p, target);
|
|
156
|
+
emit(r, rdf('object'), o, target);
|
|
157
|
+
}
|
|
158
|
+
if (attrs.has(`${RDF}annotation`) && attrs.has(`${RDF}annotationNodeID`)) fail('rdf:annotation and rdf:annotationNodeID cannot be used together');
|
|
159
|
+
const reifier = attrs.has(`${RDF}annotation`) ? resolve(attrs.get(`${RDF}annotation`), context)
|
|
160
|
+
: attrs.has(`${RDF}annotationNodeID`) ? node(attrs.get(`${RDF}annotationNodeID`)) : null;
|
|
161
|
+
if (reifier) emit(reifier, rdf('reifies'), st('triple', s, p, o), target);
|
|
162
|
+
};
|
|
163
|
+
const only = (attrs, allowed, element) => {
|
|
164
|
+
for (const name of attrs.keys()) {
|
|
165
|
+
if (!name.startsWith(RDF) || !allowed.includes(name.slice(RDF.length))) fail(`<${element.name}> cannot have the attribute ${name.startsWith(RDF) ? `rdf:${name.slice(RDF.length)}` : name}`);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
// A property element of subject: one triple, and those of its object.
|
|
170
|
+
// Returns the rdf:li counter of the subject's node element.
|
|
171
|
+
const propertyElement = (element, subject, parent, li, target) => {
|
|
172
|
+
let name = element.ns + element.local;
|
|
173
|
+
if (name === `${RDF}li`) name = `${RDF}_${++li}`;
|
|
174
|
+
else if (name.startsWith(RDF) && (CORE.has(element.local) || OLD.has(element.local) || element.local === 'Description')) {
|
|
175
|
+
fail(`rdf:${element.local} cannot name a property element`);
|
|
176
|
+
}
|
|
177
|
+
const p = iri(name);
|
|
178
|
+
const { context, attrs } = contextOf(element, parent);
|
|
179
|
+
const children = elements(element);
|
|
180
|
+
const decorations = ['ID', 'annotation', 'annotationNodeID'];
|
|
181
|
+
const link = (object) => {
|
|
182
|
+
emit(subject, p, object, target);
|
|
183
|
+
decorate(subject, p, object, attrs, context, target);
|
|
184
|
+
return li;
|
|
185
|
+
};
|
|
186
|
+
if (attrs.has(`${RDF}parseType`)) {
|
|
187
|
+
const kind = attrs.get(`${RDF}parseType`);
|
|
188
|
+
attrs.delete(`${RDF}parseType`);
|
|
189
|
+
only(attrs, decorations, element);
|
|
190
|
+
if (kind === 'Resource') {
|
|
191
|
+
const object = fresh();
|
|
192
|
+
link(object);
|
|
193
|
+
let inner = 0;
|
|
194
|
+
for (const child of children) inner = propertyElement(child, object, context, inner, target);
|
|
195
|
+
return li;
|
|
196
|
+
}
|
|
197
|
+
if (kind === 'Collection') {
|
|
198
|
+
const items = children.map((child) => nodeElement(child, context, target));
|
|
199
|
+
const cells = items.map(() => fresh());
|
|
200
|
+
items.forEach((item, i) => {
|
|
201
|
+
emit(cells[i], rdf('first'), item, target);
|
|
202
|
+
emit(cells[i], rdf('rest'), cells[i + 1] ?? rdf('nil'), target);
|
|
203
|
+
});
|
|
204
|
+
return link(cells[0] ?? rdf('nil'));
|
|
205
|
+
}
|
|
206
|
+
if (kind === 'Triple') {
|
|
207
|
+
// Before RDF 1.2, a triple term is ignored.
|
|
208
|
+
if (!rdf12(context)) return li;
|
|
209
|
+
if (children.length !== 1) fail('rdf:parseType="Triple" holds one node element');
|
|
210
|
+
const inner = [];
|
|
211
|
+
nodeElement(children[0], context, inner);
|
|
212
|
+
if (inner.length !== 1) fail('rdf:parseType="Triple" describes exactly one triple');
|
|
213
|
+
return link(st('triple', ...inner[0].slice(0, 3)));
|
|
214
|
+
}
|
|
215
|
+
// Literal, and any other parse type, is an XML literal of the content.
|
|
216
|
+
return link(literal(xmlLiteral(element), null, `${RDF}XMLLiteral`));
|
|
217
|
+
}
|
|
218
|
+
if (children.length) {
|
|
219
|
+
if (children.length > 1) fail(`<${element.name}> holds more than one node element`);
|
|
220
|
+
only(attrs, decorations, element);
|
|
221
|
+
return link(nodeElement(children[0], context, target));
|
|
222
|
+
}
|
|
223
|
+
// A literal: text, or an empty element with only a datatype.
|
|
224
|
+
const rest = new Map([...attrs].filter(([k]) => !(k.startsWith(RDF) && decorations.includes(k.slice(RDF.length)))));
|
|
225
|
+
const value = textOf(element);
|
|
226
|
+
if (value !== '' || (rest.size === 1 && rest.has(`${RDF}datatype`))) {
|
|
227
|
+
only(attrs, [...decorations, 'datatype'], element);
|
|
228
|
+
return link(attrs.has(`${RDF}datatype`) ? literal(value, null, resolveIriRef(attrs.get(`${RDF}datatype`), context.base ?? '')) : plain(value, context));
|
|
229
|
+
}
|
|
230
|
+
// An empty property element: an empty literal, or a resource that the
|
|
231
|
+
// remaining attributes describe.
|
|
232
|
+
if (rest.size === 0) return link(plain('', context));
|
|
233
|
+
if (rest.has(`${RDF}resource`) && rest.has(`${RDF}nodeID`)) fail(`<${element.name}> has both rdf:resource and rdf:nodeID`);
|
|
234
|
+
if (rest.has(`${RDF}datatype`)) fail(`<${element.name}> has rdf:datatype and resource attributes`);
|
|
235
|
+
const object = rest.has(`${RDF}resource`) ? resolve(rest.get(`${RDF}resource`), context)
|
|
236
|
+
: rest.has(`${RDF}nodeID`) ? node(rest.get(`${RDF}nodeID`)) : fresh();
|
|
237
|
+
rest.delete(`${RDF}resource`);
|
|
238
|
+
rest.delete(`${RDF}nodeID`);
|
|
239
|
+
link(object);
|
|
240
|
+
propertyAttributes(object, rest, context, target);
|
|
241
|
+
return li;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
// A document element: rdf:RDF with node elements, or one node element.
|
|
245
|
+
const document = (root, top) => {
|
|
246
|
+
if (root.ns === RDF && root.local === 'RDF') {
|
|
247
|
+
const { context, attrs } = contextOf(root, top);
|
|
248
|
+
if (attrs.size) fail(`rdf:RDF cannot have the attribute ${[...attrs.keys()][0]}`);
|
|
249
|
+
for (const child of elements(root)) nodeElement(child, context);
|
|
250
|
+
if (/\S/.test(textOf(root))) fail('rdf:RDF holds node elements, not text');
|
|
251
|
+
} else nodeElement(root, top);
|
|
252
|
+
return { quads: out };
|
|
253
|
+
};
|
|
254
|
+
return { document, contextOf };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function prefixesOf(root) {
|
|
258
|
+
const out = {};
|
|
259
|
+
for (const [name, ns] of Object.entries(root.declared)) if (name) out[name] = ns;
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// The content of an rdf:parseType="Literal" element in exclusive XML
|
|
264
|
+
// canonical form, with comments: each element declares the namespaces it and
|
|
265
|
+
// its attributes use that no output ancestor has declared alike.
|
|
266
|
+
// https://www.w3.org/TR/xml-exc-c14n/
|
|
267
|
+
function xmlLiteral(element) {
|
|
268
|
+
const escapeText = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\r/g, '
');
|
|
269
|
+
const escapeAttr = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"')
|
|
270
|
+
.replace(/\t/g, '	').replace(/\n/g, '
').replace(/\r/g, '
');
|
|
271
|
+
const prefixOf = (name) => (name.includes(':') ? name.slice(0, name.indexOf(':')) : '');
|
|
272
|
+
const write = (node, rendered) => {
|
|
273
|
+
if (node.type === 'text') return escapeText(node.value);
|
|
274
|
+
if (node.type === 'comment') return `<!--${node.value}-->`;
|
|
275
|
+
if (node.type === 'pi') return `<?${node.target}${node.value ? ` ${node.value}` : ''}?>`;
|
|
276
|
+
const used = new Map([[prefixOf(node.name), node.ns]]);
|
|
277
|
+
for (const a of node.attrs) if (a.name.includes(':')) used.set(prefixOf(a.name), a.ns);
|
|
278
|
+
const declarations = [];
|
|
279
|
+
const inScope = new Map(rendered);
|
|
280
|
+
for (const [prefix, ns] of used) {
|
|
281
|
+
if (prefix === 'xml') continue;
|
|
282
|
+
if ((rendered.get(prefix) ?? '') === ns && (prefix === '' ? true : rendered.has(prefix))) continue;
|
|
283
|
+
if (prefix === '' && ns === '' && !rendered.get('')) continue;
|
|
284
|
+
declarations.push([prefix, ns]);
|
|
285
|
+
inScope.set(prefix, ns);
|
|
286
|
+
}
|
|
287
|
+
declarations.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
288
|
+
const attrs = [...node.attrs].sort((a, b) => (a.ns === b.ns ? (a.local < b.local ? -1 : 1) : a.ns < b.ns ? -1 : 1));
|
|
289
|
+
const open = `<${node.name}${declarations.map(([prefix, ns]) => ` ${prefix ? `xmlns:${prefix}` : 'xmlns'}="${escapeAttr(ns)}"`).join('')}` +
|
|
290
|
+
`${attrs.map((a) => ` ${a.name}="${escapeAttr(a.value)}"`).join('')}>`;
|
|
291
|
+
return open + node.children.map((child) => write(child, inScope)).join('') + `</${node.name}>`;
|
|
292
|
+
};
|
|
293
|
+
return element.children.map((child) => write(child, new Map())).join('');
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// RDF/XML out: neutral quads (rdf.js) of the default graph as one rdf:RDF
|
|
297
|
+
// document, a node element per subject. RDF/XML has no named graphs and no
|
|
298
|
+
// triple term subjects; a predicate must end in an XML name to be written.
|
|
299
|
+
// A triple term object needs rdf:version="1.2", a text direction its:dir.
|
|
300
|
+
export function writeRdfXml(quads, prefixes = {}) {
|
|
301
|
+
// Control characters are character references, which XML 1.1 allows.
|
|
302
|
+
let xml11 = false;
|
|
303
|
+
const escape = (s, attribute) => {
|
|
304
|
+
if (/[\u0000\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(s)) {
|
|
305
|
+
throw new SyntaxError('RDF/XML cannot write U+0000, U+FFFE, U+FFFF or a lone surrogate');
|
|
306
|
+
}
|
|
307
|
+
let out = s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\r/g, '
');
|
|
308
|
+
if (attribute) out = out.replace(/"/g, '"').replace(/\t/g, '	').replace(/\n/g, '
');
|
|
309
|
+
return out.replace(/[\u0001-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F]/g, (c) => {
|
|
310
|
+
xml11 ||= c < ' ';
|
|
311
|
+
return `&#x${c.charCodeAt(0).toString(16).toUpperCase()};`;
|
|
312
|
+
});
|
|
313
|
+
};
|
|
314
|
+
const namespaces = new Map([['rdf', RDF]]);
|
|
315
|
+
for (const [name, ns] of Object.entries(prefixes)) if (/^[A-Za-z_][\w.-]*$/.test(name) && !/^xml/i.test(name) && name !== 'rdf') namespaces.set(name, ns);
|
|
316
|
+
let rdf12 = false, its = false;
|
|
317
|
+
const qname = (iri) => {
|
|
318
|
+
for (const [name, ns] of namespaces) if (iri.startsWith(ns) && isNcName(iri.slice(ns.length))) return `${name}:${iri.slice(ns.length)}`;
|
|
319
|
+
const m = /^(.*?)([A-Z_a-zÀ-�][\w.·À-�-]*)$/u.exec(iri);
|
|
320
|
+
if (!m || !m[1] || !isNcName(m[2])) throw new SyntaxError(`RDF/XML cannot write the predicate ${iri}, which does not end in an XML name`);
|
|
321
|
+
let name = `ns${namespaces.size}`;
|
|
322
|
+
while (namespaces.has(name)) name += '_';
|
|
323
|
+
namespaces.set(name, m[1]);
|
|
324
|
+
return `${name}:${m[2]}`;
|
|
325
|
+
};
|
|
326
|
+
const subjectAttribute = (t) => (t.termType === 'blank' ? `rdf:nodeID="${escape(t.value, true)}"` : `rdf:about="${escape(t.value, true)}"`);
|
|
327
|
+
const property = (p, o, indent) => {
|
|
328
|
+
const name = qname(p.value);
|
|
329
|
+
if (o.termType === 'iri') return `${indent}<${name} rdf:resource="${escape(o.value, true)}"/>`;
|
|
330
|
+
if (o.termType === 'blank') return `${indent}<${name} rdf:nodeID="${escape(o.value, true)}"/>`;
|
|
331
|
+
if (o.termType === 'triple') {
|
|
332
|
+
rdf12 = true;
|
|
333
|
+
if (o.subject.termType === 'triple') throw new SyntaxError('RDF/XML cannot write a triple term as a subject');
|
|
334
|
+
return [`${indent}<${name} rdf:parseType="Triple">`, `${indent} <rdf:Description ${subjectAttribute(o.subject)}>`,
|
|
335
|
+
property(o.predicate, o.object, `${indent} `), `${indent} </rdf:Description>`, `${indent}</${name}>`].join('\n');
|
|
336
|
+
}
|
|
337
|
+
if (o.datatype === `${RDF}XMLLiteral` && isXmlContent(o.value)) return `${indent}<${name} rdf:parseType="Literal">${o.value}</${name}>`;
|
|
338
|
+
let attributes = '';
|
|
339
|
+
if (o.language) {
|
|
340
|
+
attributes = ` xml:lang="${escape(o.language, true)}"`;
|
|
341
|
+
if (o.direction) {
|
|
342
|
+
rdf12 = its = true;
|
|
343
|
+
attributes += ` its:dir="${o.direction}"`;
|
|
344
|
+
}
|
|
345
|
+
} else if (o.datatype && o.datatype !== 'http://www.w3.org/2001/XMLSchema#string') {
|
|
346
|
+
attributes = ` rdf:datatype="${escape(o.datatype, true)}"`;
|
|
347
|
+
}
|
|
348
|
+
return `${indent}<${name}${attributes}>${escape(o.value, false)}</${name}>`;
|
|
349
|
+
};
|
|
350
|
+
const subjects = new Map();
|
|
351
|
+
for (const [s, p, o, g] of quads) {
|
|
352
|
+
if (g) throw new SyntaxError('RDF/XML has no named graphs; write TriG, N-Quads or JSON-LD');
|
|
353
|
+
if (s.termType === 'triple') throw new SyntaxError('RDF/XML cannot write a triple term as a subject');
|
|
354
|
+
const key = `${s.termType} ${s.value}`;
|
|
355
|
+
if (!subjects.has(key)) subjects.set(key, [s, []]);
|
|
356
|
+
subjects.get(key)[1].push(property(p, o, ' '));
|
|
357
|
+
}
|
|
358
|
+
const body = [...subjects.values()].map(([s, lines]) => [` <rdf:Description ${subjectAttribute(s)}>`, ...lines, ' </rdf:Description>'].join('\n'));
|
|
359
|
+
const declarations = [...namespaces].map(([name, ns]) => `xmlns:${name}="${escape(ns, true)}"`);
|
|
360
|
+
if (its) declarations.push(`xmlns:its="${ITS}"`, 'its:version="2.0"');
|
|
361
|
+
if (rdf12) declarations.push('rdf:version="1.2"');
|
|
362
|
+
return `<?xml version="${xml11 ? '1.1' : '1.0'}" encoding="utf-8"?>\n<rdf:RDF ${declarations.join('\n ')}>\n${body.map((b) => `${b}\n`).join('')}</rdf:RDF>\n`;
|
|
363
|
+
}
|