eyemind 0.9.17 → 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/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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;');
269
+ const escapeAttr = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;')
270
+ .replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;');
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\r/g, '&#xD;');
308
+ if (attribute) out = out.replace(/"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;');
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
+ }
package/src/rdf.js CHANGED
@@ -1,8 +1,9 @@
1
- // RDF 1.2 in and out of eyemind: Turtle, TriG, N-Triples and N-Quads.
1
+ // RDF 1.2 in and out of eyemind: Turtle, TriG, N-Triples and N-Quads, and
2
+ // RDF/XML (rdf-xml.js) and JSON-LD (jsonld.js) in.
2
3
  //
3
4
  // Documents are read by the RDF lexer and parser (rdf-lexer.js,
4
- // rdf-parser.js, rdf-prelude.js and rdf-rules.js), with the RDF 1.2
5
- // surface checks below. Each quad becomes an eyemind term
5
+ // rdf-parser.js and rdf-prelude.js), with the RDF 1.2 surface checks
6
+ // below. Each quad becomes an eyemind term
6
7
  // rdf(Subject, Predicate, Object, Graph):
7
8
  //
8
9
  // IRI iri('https://example.org/a')
@@ -18,6 +19,8 @@
18
19
  import { lex } from './rdf-lexer.js';
19
20
  import { checkRdfSyntax } from './rdf-syntax.js';
20
21
  import { Parser } from './rdf-parser.js';
22
+ import { parseRdfXml, parseRdfXmlMessages, writeRdfXml } from './rdf-xml.js';
23
+ import { jsonLdToRdf, rdfToJsonLd } from './jsonld.js';
21
24
  import { Blank, GraphTerm, Iri, ListTerm, Literal, LOG_NS, RDF_NS, clearParserCaches, literalParts } from './rdf-prelude.js';
22
25
  import { EyemindError, Struct } from './terms.js';
23
26
  import { write } from './writer.js';
@@ -26,7 +29,8 @@ const XSD = 'http://www.w3.org/2001/XMLSchema#';
26
29
  const RDF_TYPE = `${RDF_NS}type`;
27
30
  export const DEFAULT_GRAPH = 'default_graph';
28
31
 
29
- const FORMATS = { ttl: 'turtle', turtle: 'turtle', trig: 'trig', nt: 'n-triples', ntriples: 'n-triples', nq: 'n-quads', nquads: 'n-quads' };
32
+ const FORMATS = { ttl: 'turtle', turtle: 'turtle', trig: 'trig', nt: 'n-triples', ntriples: 'n-triples', nq: 'n-quads', nquads: 'n-quads',
33
+ rdf: 'rdf-xml', rdfxml: 'rdf-xml', jsonld: 'json-ld', ndjson: 'ndjson-ld' };
30
34
 
31
35
  // The RDF format a file name names by its extension, or null.
32
36
  export function rdfFormat(name) {
@@ -37,18 +41,22 @@ export function rdfFormat(name) {
37
41
  const st = (name, ...args) => new Struct(name, args);
38
42
  const iri = (v) => st('iri', v);
39
43
 
40
- // Read an RDF document. Options: format ('turtle', 'trig', 'n-triples' or
41
- // 'n-quads'), base (IRI) and scope (for blank nodes). Returns { quads,
44
+ // Read an RDF document. Options: format ('turtle', 'trig', 'n-triples',
45
+ // 'n-quads', 'rdf-xml' or 'json-ld'), base (IRI) and scope (for blank nodes);
46
+ // JSON-LD also takes loadDocument(url), for remote contexts, and the
47
+ // processingMode, expandContext and rdfDirection of the JSON-LD API. Returns { quads,
42
48
  // prefixes }: quads are [S, P, O, G] eyemind terms, prefixes maps names to
43
49
  // namespaces.
44
- export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf' } = {}) {
50
+ export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf', ...jsonld } = {}) {
45
51
  text = String(text);
46
52
  try {
53
+ if (format === 'rdf-xml') return parseRdfXml(text, { base, scope, graph: DEFAULT_GRAPH, literal: xmlLiteralTerm });
54
+ if (format === 'ndjson-ld') throw new SyntaxError('an NDJSON-LD log is read with parseRdfMessages, which keeps its messages apart');
55
+ if (format === 'json-ld') return { quads: jsonLdQuads(jsonLdToRdf(text, { ...jsonld, base }), scope), prefixes: {}, base };
47
56
  checkRdfSyntax(text, format);
48
57
  assertRdf12SurfaceSyntax(text, format);
49
- const parser = new Parser(lex(text, { rdf: true, trig: format === 'trig', messages: false }));
50
- // RDF declares every prefix it uses; N3's predeclared ones do not apply.
51
- parser.prefixes.map = {};
58
+ const parser = new Parser(lex(text, { trig: format === 'trig' }));
59
+ parser.verbatimIris = format === 'n-triples' || format === 'n-quads';
52
60
  if (base) parser.prefixes.setBase(base);
53
61
  const state = { scope, lists: 0, out: [] };
54
62
  if (format === 'n-quads') {
@@ -62,8 +70,7 @@ export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf' }
62
70
  quad(s, p, o, g, state);
63
71
  }
64
72
  } else {
65
- const [, triples, forward, backward, queries] = parser.parseDocument();
66
- if (forward.length || backward.length || queries.length) throw new SyntaxError('an RDF document has no rules');
73
+ const [, triples] = parser.parseDocument();
67
74
  for (const t of triples) {
68
75
  if (format === 'trig' && t.p instanceof Iri && t.p.value === `${LOG_NS}nameOf` && t.o instanceof GraphTerm) {
69
76
  const g = convert(t.s, 'graph', DEFAULT_GRAPH, state);
@@ -147,6 +154,71 @@ function literalTerm(raw) {
147
154
  return literalOf(value, datatype ?? (quoted ? `${XSD}string` : bareDatatype(value)));
148
155
  }
149
156
 
157
+ // eyemind quads as the neutral terms of the JSON-LD and RDF/XML writers:
158
+ // { termType, value, datatype?, language?, direction? }, or a triple term
159
+ // { termType: 'triple', subject, predicate, object }; graph null for the
160
+ // default one. A blank node keeps its label where that label is unique.
161
+ function neutralQuads(quads, blankNodePrefix = '') {
162
+ const labels = new Map(), taken = new Set();
163
+ const blank = (t) => {
164
+ const key = write(t);
165
+ if (!labels.has(key)) {
166
+ let label = t.name === 'bnode' && typeof t.args[1] === 'string' ? t.args[1] : '';
167
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(label) || taken.has(label)) label = `b${labels.size}`;
168
+ while (taken.has(label)) label += '_';
169
+ taken.add(label);
170
+ labels.set(key, blankNodePrefix + label);
171
+ }
172
+ return { termType: 'blank', value: labels.get(key) };
173
+ };
174
+ const term = (t) => {
175
+ if (typeof t === 'bigint') return { termType: 'literal', value: String(t), datatype: `${XSD}integer` };
176
+ if (typeof t === 'number') return { termType: 'literal', value: String(t), datatype: `${XSD}double` };
177
+ if (!(t instanceof Struct)) throw new EyemindError(`${write(t)} is not an RDF term`);
178
+ const [a, b, c] = t.args;
179
+ if (t.name === 'iri' && t.args.length === 1 && typeof a === 'string') return { termType: 'iri', value: a };
180
+ if ((t.name === 'bnode' && t.args.length === 2) || (t.name === 'skolem' && t.args.length === 3)) return blank(t);
181
+ if (t.name === 'literal' && t.args.length === 2 && typeof a === 'string' && b instanceof Struct) {
182
+ if (b.name === 'lang') return { termType: 'literal', value: a, language: b.args[0], direction: b.args[1] ?? null };
183
+ if (b.name === 'datatype') return { termType: 'literal', value: a, datatype: b.args[0] };
184
+ }
185
+ if (t.name === 'triple' && t.args.length === 3) return { termType: 'triple', subject: term(a), predicate: term(b), object: term(c) };
186
+ throw new EyemindError(`${write(t)} is not an RDF term`);
187
+ };
188
+ return quads.map(([s, p, o, g]) => [term(s), term(p), term(o), g === DEFAULT_GRAPH ? null : term(g)]);
189
+ }
190
+
191
+ // The quads of jsonld.js as eyemind terms.
192
+ function jsonLdQuads(quads, scope) {
193
+ const term = (t) => {
194
+ if (t.termType === 'iri') return iri(t.value);
195
+ if (t.termType === 'blank') return st('bnode', scope, t.value);
196
+ if (t.language) return st('literal', t.value, st('lang', t.language));
197
+ return literalOf(t.value, t.datatype);
198
+ };
199
+ return quads.map(([s, p, o, g]) => [term(s), term(p), term(o), g ? term(g) : DEFAULT_GRAPH]);
200
+ }
201
+
202
+ // The messages of an RDF/XML message log, for messages.js.
203
+ export function parseRdfXmlLog(text, { base = null, scope = 'messages' } = {}) {
204
+ try {
205
+ return parseRdfXmlMessages(String(text), { base, scope, graph: DEFAULT_GRAPH, literal: xmlLiteralTerm });
206
+ } catch (error) {
207
+ if (error instanceof EyemindError) throw error;
208
+ throw new EyemindError(`rdf-xml: ${error.message}`);
209
+ }
210
+ }
211
+
212
+ // A literal of RDF/XML: a language string, or a typed one, xsd:string when
213
+ // no datatype is given.
214
+ function xmlLiteralTerm(value, language, datatype) {
215
+ if (language) {
216
+ if (!/^[A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*$/.test(language.lang)) throw new SyntaxError(`invalid RDF 1.2 language tag ${language.lang}`);
217
+ return st('literal', value, language.dir ? st('lang', language.lang, language.dir) : st('lang', language.lang));
218
+ }
219
+ return literalOf(value, datatype ?? `${XSD}string`);
220
+ }
221
+
150
222
  function unquote(lexical) {
151
223
  try {
152
224
  return JSON.parse(lexical);
@@ -341,13 +413,23 @@ function assertLineSyntax(text) {
341
413
 
342
414
  // Write quads, [S, P, O, G] eyemind terms, as Turtle (or TriG when a quad is
343
415
  // in a named graph) with the prefixes it uses, or as N-Triples or N-Quads.
344
- export function writeRdf(quads, { format = 'turtle', prefixes = {}, blankNodePrefix = '' } = {}) {
416
+ export function writeRdf(quads, { format = 'turtle', prefixes = {}, blankNodePrefix = '', ...jsonld } = {}) {
417
+ if (format === 'json-ld') return `${JSON.stringify(rdfToJsonLd(neutralQuads(quads, blankNodePrefix), jsonld), null, 2)}\n`;
418
+ if (format === 'rdf-xml') {
419
+ try {
420
+ return writeRdfXml(neutralQuads(quads, blankNodePrefix), prefixes);
421
+ } catch (error) {
422
+ throw error instanceof SyntaxError ? new EyemindError(error.message) : error;
423
+ }
424
+ }
425
+ if ((format === 'turtle' || format === 'n-triples') && quads.some((q) => q[3] !== DEFAULT_GRAPH)) {
426
+ throw new EyemindError(`${format} has no named graphs; write trig, n-quads or json-ld`);
427
+ }
345
428
  const line = format === 'n-triples' || format === 'n-quads';
346
429
  const w = new RdfWriter(line ? {} : prefixes, line, blankNodePrefix);
347
430
  const body = [];
348
431
  if (line) {
349
432
  for (const [s, p, o, g] of quads) {
350
- if (format === 'n-triples' && g !== DEFAULT_GRAPH) continue;
351
433
  body.push(`${w.term(s)} ${w.term(p)} ${w.term(o)}${g === DEFAULT_GRAPH ? '' : ` ${w.term(g)}`} .`);
352
434
  }
353
435
  return body.map((l) => `${l}\n`).join('');
@@ -595,28 +595,6 @@ function boundVariables(clauses, initialBound = new Set()) {
595
595
  return vars;
596
596
  }
597
597
 
598
- function bodyVariables(clauses) {
599
- const vars = new Set();
600
- for (const clause of clauses) {
601
- if (clause.type === 'triple' || clause.type === 'path') collectTripleVars(clause.triple, vars);
602
- if ((clause.type === 'set' || clause.type === 'bind')) {
603
- vars.add(clause.variable);
604
- for (const v of expressionVariables(clause.expr)) vars.add(v);
605
- }
606
- if (clause.type === 'filter') for (const v of expressionVariables(clause.expr)) vars.add(v);
607
- if (clause.type === 'not') for (const v of bodyVariables(clause.body)) vars.add(v);
608
- if (clause.type === 'group') {
609
- for (const key of clause.keys) vars.add(key);
610
- for (const aggregation of clause.aggregations) {
611
- vars.add(aggregation.variable);
612
- if (aggregation.function.argument !== '*') vars.add(aggregation.function.argument);
613
- }
614
- for (const v of bodyVariables(clause.pattern)) vars.add(v);
615
- }
616
- }
617
- return vars;
618
- }
619
-
620
598
  function collectTripleVars(triple, vars) {
621
599
  for (const term of [triple.s, triple.p, triple.o]) collectTermVars(term, vars);
622
600
  }
package/src/srl-term.js CHANGED
@@ -5,7 +5,6 @@ const RDF_FIRST = `${RDF_NS}first`;
5
5
  const RDF_REST = `${RDF_NS}rest`;
6
6
  const RDF_NIL = `${RDF_NS}nil`;
7
7
  const RDF_REIFIES = `${RDF_NS}reifies`;
8
- const XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string';
9
8
  const XSD_BOOLEAN = 'http://www.w3.org/2001/XMLSchema#boolean';
10
9
  const XSD_INTEGER = 'http://www.w3.org/2001/XMLSchema#integer';
11
10
  const XSD_DECIMAL = 'http://www.w3.org/2001/XMLSchema#decimal';
@@ -64,21 +63,6 @@ function termKey(term) {
64
63
  return JSON.stringify(term);
65
64
  }
66
65
 
67
- function cloneTerm(term) {
68
- if (!term) return term;
69
- if (term.type === 'triple') return tripleTerm(cloneTerm(term.s), cloneTerm(term.p), cloneTerm(term.o));
70
- return { ...term };
71
- }
72
-
73
- function escapeString(value) {
74
- return String(value)
75
- .replace(/\\/g, '\\\\')
76
- .replace(/\n/g, '\\n')
77
- .replace(/\r/g, '\\r')
78
- .replace(/\t/g, '\\t')
79
- .replace(/"/g, '\\"');
80
- }
81
-
82
66
  function compactIRI(value, prefixes = {}) {
83
67
  if (value === RDF_TYPE) return 'a';
84
68
  const entries = Object.entries(prefixes)
@@ -94,42 +78,6 @@ function compactIRI(value, prefixes = {}) {
94
78
  return `<${value}>`;
95
79
  }
96
80
 
97
- // A number may drop its datatype only when the shorthand reads back as the
98
- // same datatype: an INTEGER carries neither `.` nor exponent, a DECIMAL a
99
- // `.`, a DOUBLE an exponent ([95]-[97]). `72` written bare for an
100
- // xsd:double would come back as an xsd:integer, so such a literal keeps
101
- // its datatype; a whole-numbered decimal gains the `.0` that makes it one.
102
- function numericShorthand(value, datatype) {
103
- const text = String(value);
104
- const hasExponent = /[eE]/.test(text);
105
- const hasDot = text.includes('.');
106
- if (!datatype || datatype === XSD_INTEGER) return !hasDot && !hasExponent ? text : null;
107
- if (datatype === XSD_DECIMAL) return hasExponent ? null : (hasDot ? text : `${text}.0`);
108
- if (datatype === XSD_DOUBLE) return hasExponent ? text : null;
109
- return null;
110
- }
111
-
112
- function formatTerm(term, prefixes = {}) {
113
- if (term.type === 'iri') return compactIRI(term.value, prefixes);
114
- if (term.type === 'blank') return `_:${term.value}`;
115
- if (term.type === 'var') return `?${term.value}`;
116
- if (term.type === 'triple') return `<<(${formatTerm(term.s, prefixes)} ${formatTerm(term.p, prefixes)} ${formatTerm(term.o, prefixes)})>>`;
117
- if (term.type === 'literal') {
118
- const v = term.value;
119
- if (typeof v === 'bigint' && !term.lang && (!term.datatype || term.datatype === XSD_INTEGER)) return String(v);
120
- if (typeof v === 'number' && Number.isFinite(v) && !term.lang) {
121
- const shorthand = numericShorthand(v, term.datatype);
122
- if (shorthand !== null) return shorthand;
123
- }
124
- if (typeof v === 'boolean' && !term.lang && (!term.datatype || term.datatype === XSD_BOOLEAN)) return v ? 'true' : 'false';
125
- const lexical = `"${escapeString(v)}"`;
126
- if (term.lang) return `${lexical}@${term.lang}${term.langDir ? `--${term.langDir}` : ''}`;
127
- if (term.datatype && term.datatype !== XSD_STRING) return `${lexical}^^${compactIRI(term.datatype, prefixes)}`;
128
- return lexical;
129
- }
130
- return String(term.value ?? term);
131
- }
132
-
133
81
  export {
134
82
  termKey,
135
83
  RDF_NS,
@@ -138,7 +86,6 @@ export {
138
86
  RDF_REST,
139
87
  RDF_NIL,
140
88
  RDF_REIFIES,
141
- XSD_STRING,
142
89
  XSD_BOOLEAN,
143
90
  XSD_INTEGER,
144
91
  XSD_DECIMAL,
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // The release this checkout is; ./release keeps it in step with package.json.
2
- export const VERSION = '0.9.17';
2
+ export const VERSION = '0.9.19';