eyemind 0.9.19 → 0.9.20

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/messages.js CHANGED
@@ -1,7 +1,8 @@
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, parseRdfXmlLog, writeRdf } from './rdf.js';
4
+ import { DEFAULT_GRAPH, neutralQuads, neutralToTerms, parseRdf, parseRdfXmlLog, writeRdf } from './rdf.js';
5
+ import { readJelly, writeJelly } from './jelly.js';
5
6
  import { readSources } from './n3.js';
6
7
  import { tripleToEyemind } from './n3-writer.js';
7
8
  import { EyemindError } from './terms.js';
@@ -33,7 +34,7 @@ function trivia(s, at, final) {
33
34
  // context are retained; onMessage runs before reading any further input.
34
35
  export class RdfMessageReader {
35
36
  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}`);
37
+ if (!['turtle', 'trig', 'n-triples', 'n-quads', 'rdf-xml', 'ndjson-ld', 'jelly'].includes(format)) throw new EyemindError(`RDF Messages do not support the format ${format}`);
37
38
  this.format = format;
38
39
  this.loadDocument = loadDocument;
39
40
  this.context = undefined;
@@ -59,9 +60,15 @@ export class RdfMessageReader {
59
60
 
60
61
  write(text) {
61
62
  if (this.stopped) return;
63
+ // Jelly is bytes, kept as one character per byte.
64
+ if (text instanceof Uint8Array) {
65
+ let chunk = '';
66
+ for (let i = 0; i < text.length; i += 0x8000) chunk += String.fromCharCode(...text.subarray(i, i + 0x8000));
67
+ text = chunk;
68
+ }
62
69
  this.buffer += text;
63
- // An RDF/XML log is one XML document, read when it is complete.
64
- if (this.format === 'rdf-xml') return;
70
+ // An RDF/XML log is one XML document, and a Jelly stream is read whole.
71
+ if (this.format === 'rdf-xml' || this.format === 'jelly') return;
65
72
  if (this.format === 'ndjson-ld') {
66
73
  for (let end = this.buffer.indexOf('\n'); end >= 0 && !this.stopped; end = this.buffer.indexOf('\n')) {
67
74
  const line = this.buffer.slice(0, end);
@@ -83,6 +90,22 @@ export class RdfMessageReader {
83
90
 
84
91
  finish() {
85
92
  if (this.stopped) { this.buffer = ''; return; }
93
+ if (this.format === 'jelly') {
94
+ try {
95
+ const read = readJelly(this.buffer);
96
+ if (!read.messages) throw new EyemindError('a Jelly stream of RDF Messages has the stream type MESSAGES');
97
+ for (const [i, statements] of read.messages.entries()) {
98
+ this.index = i + 1;
99
+ const message = { quads: neutralToTerms(statements, `${this.scope}#message${i + 1}`), prefixes: read.namespaces, base: this.base, index: i + 1 };
100
+ if (this.onMessage(message) === false) break;
101
+ }
102
+ } catch (error) {
103
+ throw new EyemindError(`RDF Message Log: ${error.message.replace(/^RDF Message Log: /, '')}`);
104
+ } finally {
105
+ this.buffer = '';
106
+ }
107
+ return;
108
+ }
86
109
  if (this.format === 'ndjson-ld') {
87
110
  if (this.buffer !== '') this.ndjsonLine(this.buffer.replace(/\r$/, ''));
88
111
  this.buffer = '';
@@ -289,7 +312,7 @@ export function isRdfMessageLog(text) {
289
312
  if (XML_LOG.test(text)) return true;
290
313
  const reader = new RdfMessageReader({ probe: true });
291
314
  try {
292
- reader.write(String(text));
315
+ reader.write(text instanceof Uint8Array ? text : String(text));
293
316
  reader.finish();
294
317
  } catch { /* The selected parser reports malformed inputs. */ }
295
318
  return reader.isLog;
@@ -328,17 +351,24 @@ export function replayMessages(messages, { scope = 'messages' } = {}) {
328
351
  export function parseRdfMessages(text, options = {}) {
329
352
  const messages = [];
330
353
  const reader = new RdfMessageReader({ ...options, onMessage: (m) => messages.push(m) });
331
- reader.write(String(text));
354
+ reader.write(text instanceof Uint8Array ? text : String(text));
332
355
  reader.finish();
333
356
  return { ...replayMessages(messages, options), messages };
334
357
  }
335
358
 
336
359
  // An RDF Message Log of messages, each its quads: VERSION "1.2-messages"
337
360
  // 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
361
+ // N-Quads, an rdf:RDF per message in RDF/XML, a line per message in
362
+ // NDJSON-LD, and message boundaries in Jelly, whose log is bytes. A final empty message needs one more delimiter, as a trailing
340
363
  // delimiter alone opens no message.
341
364
  export function writeRdfMessages(messages, { format = 'trig', prefixes = {} } = {}) {
365
+ if (format === 'jelly') {
366
+ try {
367
+ return writeJelly(messages.map((quads) => neutralQuads(quads)), { messages: true, namespaces: prefixes });
368
+ } catch (error) {
369
+ throw new EyemindError(error.message);
370
+ }
371
+ }
342
372
  if (format === 'ndjson-ld') {
343
373
  return messages.map((quads) => `${quads.length ? JSON.stringify({ '@graph': JSON.parse(writeRdf(quads, { format: 'json-ld' })) }) : '{}'}\n`).join('');
344
374
  }
@@ -1,10 +1,11 @@
1
1
  // Node's incremental RDF Message input. The shared CLI supplies the operation
2
2
  // to run for each message; this adapter owns only file/HTTP/stdin access.
3
- import { createReadStream } from 'node:fs';
3
+ import { createReadStream, readFileSync } from 'node:fs';
4
4
  import { pathToFileURL } from 'node:url';
5
5
  import { resolve } from 'node:path';
6
6
  import { rdfMessageFormat } from './formats.js';
7
7
  import { replayMessages, RdfMessageReader } from './messages.js';
8
+ import { isJellyMessages } from './jelly.js';
8
9
 
9
10
  const remote = (name) => /^https?:/.test(name);
10
11
 
@@ -12,6 +13,7 @@ async function messageFile(name) {
12
13
  if (name === '-' || remote(name)) return true;
13
14
  if (/\.js$/i.test(name)) return false;
14
15
  if (rdfMessageFormat(name) === 'ndjson-ld') return true;
16
+ if (rdfMessageFormat(name) === 'jelly') return isJellyMessages(readFileSync(name));
15
17
  const probe = new RdfMessageReader({ probe: true });
16
18
  for await (const text of createReadStream(name, { encoding: 'utf8' })) {
17
19
  probe.write(text);
@@ -27,7 +29,7 @@ async function openSource(name) {
27
29
  process.stdin.setEncoding('utf8');
28
30
  return { body: process.stdin, base: null };
29
31
  }
30
- if (!remote(name)) return { body: createReadStream(name, { encoding: 'utf8' }), base: pathToFileURL(resolve(name)).href };
32
+ if (!remote(name)) return { body: createReadStream(name, { encoding: /\.jelly$/i.test(name) ? 'latin1' : 'utf8' }), base: pathToFileURL(resolve(name)).href };
31
33
  const controller = new AbortController();
32
34
  const timer = setTimeout(() => controller.abort(), 10000);
33
35
  let response;
@@ -60,7 +62,7 @@ export async function streamMessages(request, io) {
60
62
  if (await messageFile(name)) logs.push({ name, index });
61
63
  else inputs.push([name, io.readFile(name)]);
62
64
  }
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)');
65
+ if (!logs.length) throw new Error('--stream-messages needs an RDF Message Log: VERSION "*-messages", an rdfm:MessageLog in RDF/XML, NDJSON-LD (.ndjson), or Jelly messages');
64
66
  for (const { name, index } of logs) {
65
67
  const source = await openSource(name);
66
68
  const scope = request.scope(name, index);
package/src/node.js CHANGED
@@ -8,7 +8,9 @@ import vm from 'node:vm';
8
8
  import { EyemindError } from './terms.js';
9
9
 
10
10
  export const nodeIO = {
11
- readFile: (path) => readFileSync(path, 'utf8'),
11
+ // A Jelly file is binary: read as one character per byte, which jelly.js
12
+ // takes back as bytes.
13
+ readFile: (path) => readFileSync(path, /\.jelly$/i.test(path) ? 'latin1' : 'utf8'),
12
14
  // The loader is synchronous. Fetch in a child before compilation, with
13
15
  // bounds on its time and output; no I/O happens during proof checking.
14
16
  readDocument(iri) {
package/src/rdf.js CHANGED
@@ -1,5 +1,5 @@
1
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
+ // RDF/XML (rdf-xml.js), JSON-LD (jsonld.js) and Jelly (jelly.js).
3
3
  //
4
4
  // Documents are read by the RDF lexer and parser (rdf-lexer.js,
5
5
  // rdf-parser.js and rdf-prelude.js), with the RDF 1.2 surface checks
@@ -21,6 +21,7 @@ import { checkRdfSyntax } from './rdf-syntax.js';
21
21
  import { Parser } from './rdf-parser.js';
22
22
  import { parseRdfXml, parseRdfXmlMessages, writeRdfXml } from './rdf-xml.js';
23
23
  import { jsonLdToRdf, rdfToJsonLd } from './jsonld.js';
24
+ import { readJelly, writeJelly } from './jelly.js';
24
25
  import { Blank, GraphTerm, Iri, ListTerm, Literal, LOG_NS, RDF_NS, clearParserCaches, literalParts } from './rdf-prelude.js';
25
26
  import { EyemindError, Struct } from './terms.js';
26
27
  import { write } from './writer.js';
@@ -30,7 +31,7 @@ const RDF_TYPE = `${RDF_NS}type`;
30
31
  export const DEFAULT_GRAPH = 'default_graph';
31
32
 
32
33
  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' };
34
+ rdf: 'rdf-xml', rdfxml: 'rdf-xml', jsonld: 'json-ld', ndjson: 'ndjson-ld', jelly: 'jelly' };
34
35
 
35
36
  // The RDF format a file name names by its extension, or null.
36
37
  export function rdfFormat(name) {
@@ -42,17 +43,23 @@ const st = (name, ...args) => new Struct(name, args);
42
43
  const iri = (v) => st('iri', v);
43
44
 
44
45
  // 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
+ // 'n-quads', 'rdf-xml', 'json-ld' or 'jelly'), base (IRI) and scope (for blank
47
+ // nodes); a Jelly stream is bytes, or a string of one character per byte;
46
48
  // JSON-LD also takes loadDocument(url), for remote contexts, and the
47
49
  // processingMode, expandContext and rdfDirection of the JSON-LD API. Returns { quads,
48
50
  // prefixes }: quads are [S, P, O, G] eyemind terms, prefixes maps names to
49
51
  // namespaces.
50
52
  export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf', ...jsonld } = {}) {
51
- text = String(text);
52
53
  try {
54
+ if (format === 'jelly') {
55
+ const read = readJelly(text);
56
+ if (read.messages) throw new SyntaxError('a Jelly stream of RDF Messages is read with parseRdfMessages, which keeps its messages apart');
57
+ return { quads: neutralToTerms(read.statements, scope), prefixes: read.namespaces, base: null };
58
+ }
59
+ text = String(text);
53
60
  if (format === 'rdf-xml') return parseRdfXml(text, { base, scope, graph: DEFAULT_GRAPH, literal: xmlLiteralTerm });
54
61
  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 };
62
+ if (format === 'json-ld') return { quads: neutralToTerms(jsonLdToRdf(text, { ...jsonld, base }), scope), prefixes: {}, base };
56
63
  checkRdfSyntax(text, format);
57
64
  assertRdf12SurfaceSyntax(text, format);
58
65
  const parser = new Parser(lex(text, { trig: format === 'trig' }));
@@ -154,11 +161,19 @@ function literalTerm(raw) {
154
161
  return literalOf(value, datatype ?? (quoted ? `${XSD}string` : bareDatatype(value)));
155
162
  }
156
163
 
157
- // eyemind quads as the neutral terms of the JSON-LD and RDF/XML writers:
164
+ function neutralWrite(write) {
165
+ try {
166
+ return write();
167
+ } catch (error) {
168
+ throw error instanceof SyntaxError ? new EyemindError(error.message) : error;
169
+ }
170
+ }
171
+
172
+ // eyemind quads as the neutral terms of the JSON-LD, RDF/XML and Jelly writers:
158
173
  // { termType, value, datatype?, language?, direction? }, or a triple term
159
174
  // { termType: 'triple', subject, predicate, object }; graph null for the
160
175
  // default one. A blank node keeps its label where that label is unique.
161
- function neutralQuads(quads, blankNodePrefix = '') {
176
+ export function neutralQuads(quads, blankNodePrefix = '') {
162
177
  const labels = new Map(), taken = new Set();
163
178
  const blank = (t) => {
164
179
  const key = write(t);
@@ -188,12 +203,13 @@ function neutralQuads(quads, blankNodePrefix = '') {
188
203
  return quads.map(([s, p, o, g]) => [term(s), term(p), term(o), g === DEFAULT_GRAPH ? null : term(g)]);
189
204
  }
190
205
 
191
- // The quads of jsonld.js as eyemind terms.
192
- function jsonLdQuads(quads, scope) {
206
+ // Neutral quads, of jsonld.js and jelly.js, as eyemind terms.
207
+ export function neutralToTerms(quads, scope) {
193
208
  const term = (t) => {
194
209
  if (t.termType === 'iri') return iri(t.value);
195
210
  if (t.termType === 'blank') return st('bnode', scope, t.value);
196
- if (t.language) return st('literal', t.value, st('lang', t.language));
211
+ if (t.termType === 'triple') return st('triple', term(t.subject), term(t.predicate), term(t.object));
212
+ if (t.language) return st('literal', t.value, t.direction ? st('lang', t.language, t.direction) : st('lang', t.language));
197
213
  return literalOf(t.value, t.datatype);
198
214
  };
199
215
  return quads.map(([s, p, o, g]) => [term(s), term(p), term(o), g ? term(g) : DEFAULT_GRAPH]);
@@ -415,13 +431,9 @@ function assertLineSyntax(text) {
415
431
  // in a named graph) with the prefixes it uses, or as N-Triples or N-Quads.
416
432
  export function writeRdf(quads, { format = 'turtle', prefixes = {}, blankNodePrefix = '', ...jsonld } = {}) {
417
433
  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
- }
434
+ // Jelly is bytes.
435
+ if (format === 'jelly') return neutralWrite(() => writeJelly(neutralQuads(quads, blankNodePrefix), { namespaces: prefixes, ...jsonld }));
436
+ if (format === 'rdf-xml') return neutralWrite(() => writeRdfXml(neutralQuads(quads, blankNodePrefix), prefixes));
425
437
  if ((format === 'turtle' || format === 'n-triples') && quads.some((q) => q[3] !== DEFAULT_GRAPH)) {
426
438
  throw new EyemindError(`${format} has no named graphs; write trig, n-quads or json-ld`);
427
439
  }
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.19';
2
+ export const VERSION = '0.9.20';