eyemind 0.5.5 → 0.5.7

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/README.md CHANGED
@@ -7,7 +7,7 @@ eyemind is a **JavaScript rule language** with forward and backward reasoning an
7
7
 
8
8
  [Playground](https://eyereasoner.github.io/eyemind/playground/) · [Specification](https://eyereasoner.github.io/eyemind/SPEC) · [Conformance](https://eyereasoner.github.io/eyemind/conformance/) · [Examples](https://eyereasoner.github.io/eyemind/examples/)
9
9
 
10
- The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 99 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1353 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
10
+ The playground runs programs in your browser; the specification defines the language, its canonical text, the proof format and the C1–C10 checks. The examples are 118 runnable programs, each with a card deck and saved conclusions, proofs and check reports. The conformance suite has 1353 cases that test any implementation of the specification through its command line; run it [in your browser](https://eyereasoner.github.io/eyemind/playground/conformance).
11
11
 
12
12
  ## Contents
13
13
 
@@ -20,6 +20,7 @@ The playground runs programs in your browser; the specification defines the lang
20
20
  - [Inspecting rules](#inspecting-rules)
21
21
  - [RDF 1.2](#rdf-12)
22
22
  - [Notation3](#notation3)
23
+ - [RDF Messages](#rdf-messages)
23
24
  - [SPARQL 1.2 RL](#sparql-12-rl)
24
25
  - [How eyemind reasons](#how-eyemind-reasons)
25
26
  - [Proofs, and what checking one means](#proofs-and-what-checking-one-means)
@@ -191,33 +192,113 @@ eyemind --to trig rules.js data.trig # the conclusions as TriG
191
192
  | Triple term | `triple(S, P, O)`, which may nest |
192
193
  | Default graph, named graph | `'default_graph'`, `iri(Name)` |
193
194
 
194
- A reified triple `<< s p o >>` and an annotation `{| ... |}` become their reifier and its `rdf:reifies` triple, as RDF 1.2 defines. A Skolem term is written as a blank node, the same one for the same rule firing. The `rdf12-*` examples load Turtle or TriG data alongside eyemind rule scripts. They show triple terms, annotations, directional strings, typed numbers and named graphs. The W3C RDF test suites run in `npm test` from the mirror in `test/w3c/rdf-tests`: all 1055 tests of N-Triples, N-Quads, Turtle and TriG, in RDF 1.1 and 1.2, pass.
195
+ A reified triple `<< s p o >>` and an annotation `{| ... |}` become their reifier and its `rdf:reifies` triple, as RDF 1.2 defines. A Skolem term is written as a blank node, the same one for the same rule firing. The RDF examples load Turtle or TriG files from `examples/data/` alongside companion rules in `examples/`. They show triple terms, annotations, directional strings, typed numbers and named graphs. The W3C RDF test suites run in `npm test` from the mirror in `test/w3c/rdf-tests`: all 1055 tests of N-Triples, N-Quads, Turtle and TriG, in RDF 1.1 and 1.2, pass.
195
196
 
196
197
  ### Notation3
197
198
 
198
- A file ending in `.n3` is Notation3: eyemind compiles its facts and rules into a program, with the N3 built-ins it uses written as eyemind rules, and writes the conclusions back as N3. RDF data files join the N3 document as triples:
199
+ A file ending in `.n3` is Notation3: eyemind compiles its facts and rules into a program, with the N3 built-ins it uses written as eyemind rules, and writes the conclusions back as N3. RDF default-graph data joins the N3 document as triples:
199
200
 
200
201
  ```sh
201
- eyemind examples/n3-family.n3 # the derived triples as N3
202
- eyemind --program examples/n3-family.n3 > /tmp/family.js # the compiled program, to inspect
203
- eyemind -c examples/n3-family.n3 # a proof of it, checked
202
+ eyemind examples/family.n3 # the derived triples as N3
203
+ eyemind --program examples/family.n3 > /tmp/family.js # the compiled program, to inspect
204
+ eyemind -c examples/family.n3 # a proof of it, checked
204
205
  ```
205
206
 
206
207
  Triples are `rdf(Subject, Predicate, Object)`, with IRIs, blank nodes and literals written as in the RDF table above. N3 integers and decimals become eyemind numbers; float and double literals retain their RDF datatype, including numbers written with an exponent. Decimals use binary64 storage; `math:sum` adds their canonical decimal values before rounding its result. `=>` becomes `implies`, `<=` becomes `implied_by`, `{ ... } => false` becomes `contradiction`, and scoped negation and collection become `not` and `findall`, so an N3 run has a proof that eyemind checks like any other. Derived rules can trigger inference fuses too.
207
208
 
208
- Scoped calls can use formulas supplied by the document's stated lists, including RDF collections written with `rdf:first` and `rdf:rest`. These calls are specialized before reasoning so their dependencies remain available for stratification and proof checking; formulas constructed only during reasoning are not supported by this compilation.
209
+ N3 has no named-graph syntax. When RDF data joins an N3 run, eyemind represents
210
+ each named graph as a quoted formula through `graph:content`, where `graph:`
211
+ is `https://eyereasoner.github.io/eyemind/graph#`:
212
+
213
+ ```n3
214
+ @prefix : <https://example.org/> .
215
+ @prefix graph: <https://eyereasoner.github.io/eyemind/graph#> .
216
+
217
+ :family graph:content { :alice :parent :bob . :bob :parent :carol } .
218
+ ```
219
+
220
+ Default-graph triples remain ordinary assertions. Named-graph triples stay
221
+ inside their formulas; `?g graph:content ?data` and
222
+ `?data log:includes { ... }` inspect them. Contents with the same graph name
223
+ from several RDF inputs are combined, while blank nodes keep their source
224
+ scopes. Conclusions can attach further formulas to that name; the output
225
+ writes these as N3 formulas. See the [named graph example](https://eyereasoner.github.io/eyemind/examples/deck/trig-named-graph).
226
+
227
+ Scoped calls can use formulas supplied by the document's stated lists, including RDF collections written with `rdf:first` and `rdf:rest`, and the named-graph formulas loaded from RDF. These calls are specialized before reasoning so their dependencies remain available for stratification and proof checking; formulas constructed only during reasoning are not supported by this compilation.
209
228
 
210
229
  The documents `log:semantics`, `log:semanticsOrError` and `log:content` name are read before compiling. The command reads local files and HTTP(S) documents, with a ten-second fetch timeout and a 16 MiB response limit. The library uses the host callbacks `readFile(path)` and `readDocument(iri)`; without them it does not read external documents. Their contents become facts of the compiled program, which can be saved with `--program` for later proof checking.
211
230
 
212
- Five examples run directly from their N3 source in the playground and on the command line.
213
- [family queries](https://eyereasoner.github.io/eyemind/examples/deck/n3-family),
214
- [scoped negation](https://eyereasoner.github.io/eyemind/examples/deck/n3-scoped-negation),
215
- [invoice collection](https://eyereasoner.github.io/eyemind/examples/deck/n3-invoice),
216
- [French cities](https://eyereasoner.github.io/eyemind/examples/deck/n3-french-cities), and
217
- [existential witnesses](https://eyereasoner.github.io/eyemind/examples/deck/n3-witnesses).
231
+ Examples run directly from their N3 source in the playground and on the command line:
232
+ [family queries](https://eyereasoner.github.io/eyemind/examples/deck/family),
233
+ [scoped negation](https://eyereasoner.github.io/eyemind/examples/deck/scoped-negation),
234
+ [invoice collection](https://eyereasoner.github.io/eyemind/examples/deck/invoice),
235
+ [French cities](https://eyereasoner.github.io/eyemind/examples/deck/french-cities), and
236
+ [existential witnesses](https://eyereasoner.github.io/eyemind/examples/deck/witnesses-n3).
218
237
  Each deck shows the N3 result and what its saved proof establishes, including
219
238
  any remaining obligations.
220
239
 
240
+ ### RDF Messages
241
+
242
+ eyemind reads the [RDF Messages living draft](https://w3c-cg.github.io/rsp/spec/messages)
243
+ in Turtle, TriG, N-Triples and N-Quads. A version such as
244
+ `VERSION "1.2-messages"` enables `MESSAGE` boundaries; Turtle and TriG also
245
+ accept `@version "1.2-messages" .` and `@message .`. Empty messages are
246
+ preserved, a final delimiter adds no extra message, and blank nodes belong
247
+ to their message. Prefix and base changes apply to subsequent data.
248
+
249
+ Whole-log replay gives N3 or JavaScript rules an ordered view of the messages:
250
+
251
+ ```sh
252
+ eyemind examples/message-boundaries.n3 examples/data/message-boundaries.trig
253
+ eyemind --proof examples/message-boundaries.n3 examples/data/message-boundaries.trig
254
+ eyemind --check-proof examples/proof/message-boundaries.js examples/message-boundaries.n3 examples/data/message-boundaries.trig
255
+ ```
256
+
257
+ The replay vocabulary is `eymsg:`, with namespace
258
+ `https://eyereasoner.github.io/eyeling/vocab/message#`. A stream has
259
+ `messageCount`, `orderedEnvelopes`, `firstEnvelope`, `lastEnvelope` and
260
+ `envelope` links. Each envelope has a one-based `offset`, a `payloadKind`
261
+ of `empty` or `nonEmpty`, and, when nonempty, a `payloadGraph` link.
262
+ `nextEnvelope` preserves order. Stream and envelope IRIs are deterministic
263
+ from the input's scope; they are application replay identifiers, not syntax
264
+ from the draft.
265
+
266
+ `?payload log:nameOf ?data` exposes a quoted payload formula, inspected with
267
+ `?data log:includes { ... }`. A named graph inside a message is another
268
+ `log:nameOf` formula inside that payload. Message triples stay inside their
269
+ contexts; rules can deliberately join envelopes when replaying a whole log.
270
+ JavaScript rules see the replay facts as `rdf(S, P, O, 'default_graph')`
271
+ with `graph(...)` terms for payload formulas.
272
+
273
+ For independent processing, run the rules once per message:
274
+
275
+ ```sh
276
+ eyemind --stream-messages examples/message-alerts.n3 examples/data/message-alerts.nt
277
+ ```
278
+
279
+ The Node command incrementally reads files, standard input (`-`) or HTTP(S)
280
+ message logs and writes each result when its message closes. It reads static
281
+ inputs once and discards each run's derived facts before the next message.
282
+ Memory retains the current message, active prefix/base context and static
283
+ inputs. An inference fuse stops the stream with exit code 65. Output uses
284
+ the ordinary N3, RDF or term format selected for the run.
285
+
286
+ The playground's **Independent RDF Messages** mode processes its loaded
287
+ text with the same boundaries. Whole-log replay supports proofs;
288
+ `--stream-messages` rejects proof, proof-checking, compiled-program and
289
+ unused-clause modes. The [message-boundaries](https://eyereasoner.github.io/eyemind/examples/deck/message-boundaries),
290
+ [message-alerts](https://eyereasoner.github.io/eyemind/examples/deck/message-alerts)
291
+ and [message-provenance](https://eyereasoner.github.io/eyemind/examples/deck/message-provenance)
292
+ decks show the outputs and remaining proof obligations.
293
+
294
+ Library hosts can import `RdfMessageReader` and `parseRdfMessages` from
295
+ `eyemind`. The former accepts text chunks through `write(text)` and
296
+ `finish()`, calling `onMessage({ index, quads, prefixes, base })` for each
297
+ dataset; returning `false` stops it. The latter reads a complete string and
298
+ returns `messages` plus its replay representation. Both take `format`,
299
+ `base` and `scope` options. `parseRdf` reads ordinary RDF documents; use
300
+ `parseRdfMessages` to retain message boundaries.
301
+
221
302
  ### SPARQL 1.2 RL
222
303
 
223
304
  A file ending in `.srl` is a [SPARQL 1.2 RL](https://www.w3.org/TR/sparql12-rl/) rule set: eyemind parses and analyzes it, then compiles it into a program, with the SPARQL functions and aggregates it uses written as eyemind rules, and RDF data files given with it are its base graph. The result is the inference graph, as Turtle:
@@ -230,6 +311,11 @@ eyemind -c rules.srl facts.ttl # a proof of it, checked
230
311
 
231
312
  Triples are `rdf(Subject, Predicate, Object)`, with `base/3` marking the base graph and `inf/3` the inference graph. A rule becomes `implies`, `NOT` becomes `not` of a helper, `GROUP` becomes `findall`, a blank node in a rule head becomes the Skolem term of its firing, and a SPARQL error is a goal that fails, so `FILTER` rejects the solution and `SET` drops it. The W3C SPARQL 1.2 RL test suite runs in `npm test` from the mirror in `test/w3c/sparql-rl`: all 241 tests pass. `NOW`, `UUID` and `STRUUID` are not supported, as eyemind has no clock or randomness; decimals and doubles are computed as binary64 floats.
232
313
 
314
+ The [example catalog](https://eyereasoner.github.io/eyemind/examples/) includes
315
+ SRL programs for deployment dependencies, route distances, ancestry, inventory,
316
+ invoices, provenance and Unicode strings. Each has saved Turtle output, a
317
+ proof, a check report and a deck, and runs in the playground.
318
+
233
319
  ## How eyemind reasons
234
320
 
235
321
  The statement chooses the direction:
@@ -346,6 +432,7 @@ eyemind [OPTION ...] [FILE ...]
346
432
  | `--goal GOAL` | Ask `GOAL` after forward reasoning; may be repeated. |
347
433
  | `--strict-proof` | With a checking mode, reject proofs with any obligation. |
348
434
  | `--unused` | List the clauses that make no difference to the conclusions. |
435
+ | `--stream-messages` | Read an RDF Message Log and run the rules independently per message; Node reads files, stdin and HTTP(S) incrementally. |
349
436
  | `--stats` | Print reasoning statistics as JSON to standard error. |
350
437
  | `--max-depth N`, `--max-iterations N`, `--max-inferences N` | Bound backward depth (1000000), forward rounds per stratum (1000) and goals started (1000000); a compiled N3 or SRL program has 1000000, 100000 and 1000000000. |
351
438
  | `--to FORMAT` | Write the conclusions as `turtle`, `trig`, `n-triples`, `n-quads`, `n3` or `eyemind`; by default N3 for N3, Turtle for SRL, eyemind otherwise. |
package/SPEC.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ```text
4
4
  Title: The eyemind Rule Language and Proof Format
5
- Version: eyemind 0.5.5
5
+ Version: eyemind 0.5.7
6
6
  ```
7
7
 
8
8
  This document specifies the syntax and meaning of eyemind programs and data
@@ -2149,6 +2149,14 @@ describes the mappings. Such formats are outside conformance: a conforming
2149
2149
  implementation need not read them, and the suite does not test them. The
2150
2150
  proofs and checks of a compiled program are those of any program.
2151
2151
 
2152
+ eyemind also reads RDF Message Logs in these four RDF syntaxes, announced by
2153
+ a `*-messages` version. Replay supplies ordered envelopes and quoted payloads
2154
+ to N3 or JavaScript rules; `--stream-messages` evaluates each message
2155
+ independently and supports incremental Node input. Replay can produce and
2156
+ check ordinary eyemind proofs. The streaming mode rejects proof generation,
2157
+ proof checking, `--program` and `--unused`. These mappings and this option
2158
+ are also outside conformance; the README describes their supported behavior.
2159
+
2152
2160
  | Exit code | Meaning |
2153
2161
  | --- | --- |
2154
2162
  | 0 | Success, including a check that found the proof valid. |
package/bin/eyemind.js CHANGED
@@ -3,6 +3,7 @@
3
3
  import { readFileSync, writeSync } from 'node:fs';
4
4
  import { main } from '../src/cli.js';
5
5
  import { nodeIO } from '../src/node.js';
6
+ import { streamMessages } from '../src/node-messages.js';
6
7
 
7
8
  function write(fd, text) {
8
9
  // Written synchronously, so a large proof is complete before the exit.
@@ -19,8 +20,9 @@ function write(fd, text) {
19
20
  }
20
21
  }
21
22
 
22
- const code = main(process.argv.slice(2), {
23
+ const code = await main(process.argv.slice(2), {
23
24
  ...nodeIO,
25
+ streamMessages,
24
26
  stdout: (text) => write(1, text),
25
27
  stderr: (text) => write(2, text),
26
28
  stdin: () => readFileSync(0, 'utf8'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eyemind",
3
- "version": "0.5.5",
3
+ "version": "0.5.7",
4
4
  "description": "A dependency-free JavaScript rule language with forward and backward reasoning and checkable proofs.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // The eyemind command line.
2
2
  import { run, unusedClauses } from './engine.js';
3
- import { OUTPUT_FORMATS, defaultFormat, loadInputs, writeConclusions } from './formats.js';
3
+ import { OUTPUT_FORMATS, defaultFormat, loadInputs, rdfMessageFormat, scopeOf, writeConclusions } from './formats.js';
4
+ import { isRdfMessageLog, replayMessages, RdfMessageReader } from './messages.js';
4
5
  import { checkProof, checkReport, publicReport } from './proof.js';
5
6
  import { EyemindError } from './terms.js';
6
7
  import { VERSION } from './version.js';
@@ -27,6 +28,7 @@ and .srl as a SPARQL 1.2 RL rule set, both compiled to an eyemind program.
27
28
  --all With RDF output, write the given data too
28
29
  --program Print the program the inputs compile to
29
30
  --base IRI Resolve relative IRIs of the inputs against IRI
31
+ --stream-messages Run the rules independently for each RDF Message
30
32
  -v, --version Print the version
31
33
  -h, --help Print this help
32
34
  Source defaults to stdin; multiple files form one program.
@@ -62,6 +64,8 @@ export function main(argv, io) {
62
64
  let all = false;
63
65
  let printProgram = false;
64
66
  let base = null;
67
+ let streamMessages = false;
68
+ const filePositions = new Set();
65
69
  for (let i = 0; i < argv.length; i++) {
66
70
  const arg = argv[i];
67
71
  if (arg === '--help' || arg === '-h') {
@@ -88,6 +92,8 @@ export function main(argv, io) {
88
92
  all = true;
89
93
  } else if (arg === '--program') {
90
94
  printProgram = true;
95
+ } else if (arg === '--stream-messages') {
96
+ streamMessages = true;
91
97
  } else if (arg === '--check-proof' || arg === '--goal' || arg === '--to' || arg === '--base' || Object.hasOwn(LIMITS, arg)) {
92
98
  i++;
93
99
  if (i >= argv.length) throw new UsageError(`${arg} needs a value`);
@@ -116,6 +122,7 @@ export function main(argv, io) {
116
122
  throw new UsageError(`unknown option ${arg}`);
117
123
  } else {
118
124
  files.push(arg);
125
+ filePositions.add(i);
119
126
  }
120
127
  }
121
128
  if (asJson && proofFile === null && !proveAndCheck) throw new UsageError('--json requires --check-proof or --prove-and-check');
@@ -132,7 +139,46 @@ export function main(argv, io) {
132
139
  }
133
140
  if (!files.length) files.push('-');
134
141
  if (files.filter((file) => file === '-').length > 1) throw new UsageError('stdin can only be read once');
135
- const loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io, { base });
142
+ if (streamMessages) {
143
+ if (proofFile !== null || options.proof || proveAndCheck || printProgram || unused) {
144
+ throw new UsageError('--stream-messages cannot be combined with --proof, --check-proof, --prove-and-check, --program or --unused; replay the whole log to prove its conclusions');
145
+ }
146
+ const args = argv.filter((arg, i) => arg !== '--stream-messages' && !filePositions.has(i));
147
+ let messageNumber = 0;
148
+ const request = {
149
+ files, base,
150
+ scope: (name, index = files.indexOf(name)) => scopeOf(files.map((f) => ['', f]), name, index),
151
+ run: (inputs, name, replay) => main([...args, ...inputs.map(([path]) => path), name], {
152
+ ...io,
153
+ // Each result is serialized separately; keep its blank labels
154
+ // distinct without retaining nodes from previous messages.
155
+ blankNodePrefix: `m${++messageNumber}_`,
156
+ messageInputs: new Map([[name === '-' ? '<stdin>' : name, replay]]),
157
+ readFile: (path) => path === name ? '' : inputs.find(([p]) => p === path)?.[1] ?? io.readFile(path),
158
+ stdin: () => name === '-' ? '' : io.stdin(),
159
+ }),
160
+ };
161
+ if (io.streamMessages) return io.streamMessages(request, io);
162
+ // Hosts such as the playground already hold their inputs as text.
163
+ // Node supplies the incremental file/HTTP implementation instead.
164
+ const sources = files.map((name, index) => ({ name, index, text: readSource(name, io) }));
165
+ const logs = sources.filter(({ text }) => isRdfMessageLog(text));
166
+ if (!logs.length) throw new UsageError('--stream-messages needs an RDF Message Log with VERSION "*-messages"');
167
+ const inputs = sources.filter((source) => !logs.includes(source)).map(({ name, text }) => [name, text]);
168
+ for (const { name, text, index } of logs) {
169
+ let code = 0;
170
+ const scope = request.scope(name, index);
171
+ const reader = new RdfMessageReader({ format: rdfMessageFormat(name), base: base ?? io.fileIri?.(name), scope, onMessage: (message) => {
172
+ code = request.run(inputs, name, replayMessages([message], { scope }));
173
+ return code === 0;
174
+ } });
175
+ reader.write(text);
176
+ reader.finish();
177
+ if (code) return code;
178
+ }
179
+ return 0;
180
+ }
181
+ const loaded = loadInputs(files.map((file) => [readSource(file, io), file === '-' ? '<stdin>' : file]), io, { base, messageInputs: io.messageInputs });
136
182
  const program = loaded.program;
137
183
  if (printProgram) {
138
184
  stdout(loaded.text);
@@ -161,7 +207,9 @@ export function main(argv, io) {
161
207
  return report.valid ? result.haltCode || 0 : 2;
162
208
  }
163
209
  // Answers to goals are eyemind terms unless an output format is asked.
164
- const written = options.proof ? null : writeConclusions(loaded, result, { format: format ?? (goals.length ? 'eyemind' : defaultFormat(loaded.kind)), all });
210
+ const written = options.proof ? null : writeConclusions(loaded, result, {
211
+ format: format ?? (goals.length ? 'eyemind' : defaultFormat(loaded.kind)), all, blankNodePrefix: io.blankNodePrefix,
212
+ });
165
213
  stdout(written ?? result.stdout);
166
214
  if (stats) stderr(`${JSON.stringify(result.stats)}\n`);
167
215
  return result.haltCode || 0;
package/src/formats.js CHANGED
@@ -5,7 +5,8 @@
5
5
  //
6
6
  // .js and standard input an eyemind program
7
7
  // .ttl .trig .nt .nq RDF 1.2 data: with a program, rdf(S, P, O, G)
8
- // facts; with an N3 document, its triples; with a
8
+ // facts; with an N3 document, default triples and
9
+ // graph:content formulas for named graphs; with a
9
10
  // rule set, its base graph
10
11
  // .n3 Notation3, compiled to an eyemind program
11
12
  // .srl a SPARQL 1.2 RL rule set, compiled to one
@@ -20,6 +21,7 @@ import { DEFAULT_GRAPH, parseRdf, rdfDocument, rdfFormat, writeRdf } from './rdf
20
21
  import { answersToN3, compileSources } from './n3.js';
21
22
  import { compileSrl, srlQuads } from './srl.js';
22
23
  import { write } from './writer.js';
24
+ import { isRdfMessageLog, parseRdfMessages } from './messages.js';
23
25
 
24
26
  export const OUTPUT_FORMATS = ['eyemind', 'turtle', 'trig', 'n-triples', 'n-quads', 'n3'];
25
27
 
@@ -31,6 +33,11 @@ export function inputKind(name) {
31
33
  return 'js';
32
34
  }
33
35
 
36
+ export function rdfMessageFormat(name) {
37
+ const path = /^https?:/.test(name) ? new URL(name).pathname : name;
38
+ return rdfFormat(path) ?? 'trig';
39
+ }
40
+
34
41
  // Load inputs, given as [text, name] pairs, as one program. io may supply
35
42
  // readFile, for the documents N3 and IMPORTS name, and fileIri(name), the
36
43
  // base IRI of a file. Returns { kind, program, text, prefixes, compiled }:
@@ -46,17 +53,26 @@ export function loadInputs(inputs, io = null, options = {}) {
46
53
  }
47
54
  }
48
55
 
49
- function load(inputs, io, { base = null }) {
50
- const kinds = inputs.map(([, name]) => inputKind(name));
56
+ function load(inputs, io, { base = null, messageInputs = null }) {
57
+ const kinds = inputs.map(([text, name]) => messageInputs?.has(name) ||
58
+ (inputKind(name) === 'n3' && isRdfMessageLog(text)) ? 'rdf' : inputKind(name));
51
59
  const baseOf = (name) => base ?? io?.fileIri?.(name) ?? null;
52
- const rdf = (text, name, k) => parseRdf(text, { format: rdfFormat(name), base: baseOf(name), scope: scopeOf(inputs, name, k) });
60
+ const rdf = (text, name, k) => messageInputs?.get(name) ??
61
+ (isRdfMessageLog(text) ? parseRdfMessages : parseRdf)(text, {
62
+ format: rdfFormat(name) ?? 'trig', base: baseOf(name), scope: scopeOf(inputs, name, k),
63
+ });
53
64
  if (kinds.includes('srl')) {
54
65
  const others = kinds.filter((k) => k !== 'srl' && k !== 'rdf');
55
66
  if (kinds.filter((k) => k === 'srl').length > 1 || others.length) {
56
67
  throw new EyemindError('a SPARQL 1.2 RL run takes one .srl rule set, and RDF data for its base graph');
57
68
  }
58
69
  const [text, name] = inputs[kinds.indexOf('srl')];
59
- const data = inputs.flatMap(([t, n], k) => (kinds[k] === 'rdf' ? rdf(t, n, k).quads : []));
70
+ const data = inputs.flatMap(([t, n], k) => {
71
+ if (kinds[k] !== 'rdf') return [];
72
+ const parsed = rdf(t, n, k);
73
+ if (parsed.triples) throw new EyemindError('RDF Message Log replay needs N3 or JavaScript rules; a SPARQL rule set takes an RDF base graph');
74
+ return parsed.quads;
75
+ });
60
76
  const compiled = compileSrl(text, { base: baseOf(name), filename: name, resolve: importResolver(io), data });
61
77
  for (const warning of compiled.warnings) io?.stderr?.(`eyemind: warning: ${warning}\n`);
62
78
  return { kind: 'srl', program: loadSources([[compiled.program, name]], io), text: compiled.program, prefixes: compiled.prefixes, compiled };
@@ -81,7 +97,7 @@ function load(inputs, io, { base = null }) {
81
97
  }
82
98
 
83
99
  // A blank-node scope per data file: its name, numbered when names repeat.
84
- function scopeOf(inputs, name, k) {
100
+ export function scopeOf(inputs, name, k) {
85
101
  const base = String(name).replace(/^.*[\\/]/, '');
86
102
  const same = inputs.filter(([, n]) => String(n).replace(/^.*[\\/]/, '') === base);
87
103
  return same.length > 1 ? `${base}#${inputs.slice(0, k).filter(([, n]) => String(n).replace(/^.*[\\/]/, '') === base).length + 1}` : base;
@@ -106,17 +122,17 @@ export const defaultFormat = (kind) => ({ n3: 'n3', srl: 'turtle' })[kind] ?? 'e
106
122
 
107
123
  // The conclusions of a run in an output format; null for eyemind's own text.
108
124
  // all also writes the given data. Throws when a conclusion is no triple.
109
- export function writeConclusions(loaded, result, { format, all = false } = {}) {
125
+ export function writeConclusions(loaded, result, { format, all = false, blankNodePrefix = '' } = {}) {
110
126
  if (format === 'eyemind') return null;
111
127
  const answers = result.answers;
112
128
  if (format === 'n3') {
113
129
  if (loaded.kind !== 'n3') throw new EyemindError('--to n3 writes the conclusions of an N3 run');
114
- return answersToN3(loaded.compiled.doc, answers, { mode: all ? 'all' : 'new' }).n3;
130
+ return answersToN3(loaded.compiled.doc, answers, { mode: all ? 'all' : 'new', blankNodePrefix }).n3;
115
131
  }
116
132
  let quads;
117
133
  if (loaded.kind === 'srl') quads = srlQuads(loaded.text, answers, { all });
118
134
  else quads = conclusionQuads(answers, all ? loaded.text : null);
119
- return writeRdf(quads, { format, prefixes: loaded.kind === 'n3' ? Object.fromEntries(loaded.prefixes) : loaded.prefixes });
135
+ return writeRdf(quads, { format, prefixes: loaded.kind === 'n3' ? Object.fromEntries(loaded.prefixes) : loaded.prefixes, blankNodePrefix });
120
136
  }
121
137
 
122
138
  // Conclusions that are triples, rdf/3 or result/3, or quads, rdf/4 or
package/src/index.js CHANGED
@@ -13,3 +13,4 @@ export { checkProof, checkReport, publicReport, strict, verdictText } from './pr
13
13
  export { readTerm, readTerms } from './reader.js';
14
14
  export { EyemindError, Struct, Var } from './terms.js';
15
15
  export { write } from './writer.js';
16
+ export { RdfMessageReader, parseRdfMessages } from './messages.js';
@@ -0,0 +1,263 @@
1
+ // RDF Message Logs: delimit datasets before parsing them, so blank nodes and
2
+ // assertions stay local to a message. The replay view is ordinary N3 data.
3
+ // See https://w3c-cg.github.io/rsp/spec/messages and its companion tests.
4
+ import { DEFAULT_GRAPH, parseRdf } from './rdf.js';
5
+ import { readSources } from './n3.js';
6
+ import { tripleToEyemind } from './n3-writer.js';
7
+ import { EyemindError } from './terms.js';
8
+
9
+ export const MESSAGE_NS = 'https://eyereasoner.github.io/eyeling/vocab/message#';
10
+ const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
11
+ const LOG_NAME = 'http://www.w3.org/2000/10/swap/log#nameOf';
12
+ const GRAPH_CONTENT = 'https://eyereasoner.github.io/eyemind/graph#content';
13
+ const iri = (v) => ({ t: 'iri', v });
14
+ const triple = (s, p, o) => ({ s, p: iri(p), o });
15
+ const int = (v) => ({ t: 'int', v: BigInt(v) });
16
+ const wordEnd = (c) => c === undefined || /[\s<>"'{}\[\]();,]/.test(c);
17
+ const iriText = (v) => v.replace(/[\u0000-\u0020<>"{}|^`\\]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, '0')}`);
18
+ function trivia(s, at, final) {
19
+ while (at < s.length) {
20
+ if (/\s/.test(s[at])) at++;
21
+ else if (s[at] === '#') {
22
+ const end = s.slice(at).search(/[\r\n]/);
23
+ if (end < 0) return final ? s.length : null;
24
+ at += end;
25
+ } else break;
26
+ }
27
+ return at;
28
+ }
29
+
30
+ // Accept strings incrementally. Only the current message and active directive
31
+ // context are retained; onMessage runs before reading any further input.
32
+ 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
+ this.format = format;
36
+ this.base = base;
37
+ this.scope = scope;
38
+ this.onMessage = onMessage;
39
+ this.probe = probe;
40
+ this.buffer = '';
41
+ this.at = 0;
42
+ this.quote = null;
43
+ this.comment = false;
44
+ this.inIri = false;
45
+ this.stack = [];
46
+ this.prefixes = {};
47
+ this.index = 0;
48
+ this.version = null;
49
+ this.isLog = false;
50
+ this.stopped = false;
51
+ this.hasPayload = false;
52
+ this.directive = false;
53
+ }
54
+
55
+ write(text) {
56
+ if (this.stopped) return;
57
+ this.buffer += text;
58
+ this.scan(false);
59
+ if (this.probe) {
60
+ this.buffer = this.buffer.slice(this.at);
61
+ this.at = 0;
62
+ }
63
+ }
64
+
65
+ finish() {
66
+ if (this.stopped) { this.buffer = ''; return; }
67
+ this.scan(true);
68
+ if (!this.probe) {
69
+ if (!this.isLog) throw new EyemindError('RDF Message Log needs a VERSION "*-messages" directive');
70
+ this.emit(this.buffer, false);
71
+ }
72
+ this.buffer = '';
73
+ }
74
+
75
+ emit(text, boundary) {
76
+ if (this.probe) return;
77
+ const line = this.format === 'n-triples' || this.format === 'n-quads';
78
+ const context = line ? '' : Object.entries(this.prefixes).map(([name, ns]) => `PREFIX ${name}: <${iriText(ns)}>\n`).join('');
79
+ const number = this.index + 1;
80
+ try {
81
+ const parsed = parseRdf(`${context}${text}`, { format: this.format, base: this.base, scope: `${this.scope}#message${this.index + 1}` });
82
+ this.base = parsed.base;
83
+ this.prefixes = parsed.prefixes;
84
+ // A delimiter closes even an empty message. EOF opens no new message
85
+ // for a trailing delimiter, comments or directives alone.
86
+ if (boundary || parsed.quads.length) this.stopped = this.onMessage({ ...parsed, index: ++this.index }) === false;
87
+ } catch (error) {
88
+ throw new EyemindError(`RDF Message Log message ${number}: ${error.message}`);
89
+ }
90
+ }
91
+
92
+ scan(final) {
93
+ while (!this.stopped && this.at < this.buffer.length) {
94
+ const s = this.buffer;
95
+ const i = this.at;
96
+ const c = s[i];
97
+ if (this.comment) {
98
+ if (c === '\n' || c === '\r') this.comment = false;
99
+ this.at++;
100
+ } else if (this.quote) {
101
+ if (c === '\\') {
102
+ if (i + 1 === s.length && !final) break;
103
+ this.at += 2;
104
+ } else if (c === this.quote[0]) {
105
+ if (i + this.quote.length > s.length && !final) break;
106
+ if (s.startsWith(this.quote, i)) {
107
+ this.at += this.quote.length;
108
+ this.quote = null;
109
+ } else this.at++;
110
+ } else this.at++;
111
+ } else if (this.inIri) {
112
+ this.at++;
113
+ if (c === '>') {
114
+ this.inIri = false;
115
+ this.directive = false;
116
+ }
117
+ } else if (/\s|\uFEFF/.test(c)) this.at++;
118
+ else if (c === '#') {
119
+ this.comment = true;
120
+ this.at++;
121
+ } else if (c === '"' || c === "'") {
122
+ if (i + 3 > s.length && !final) break;
123
+ this.quote = s.startsWith(c.repeat(3), i) ? c.repeat(3) : c;
124
+ if (!this.directive) this.hasPayload = true;
125
+ this.at += this.quote.length;
126
+ } else if (c === '<') {
127
+ if (i + 1 === s.length && !final) break;
128
+ if (s[i + 1] === '<') {
129
+ if (!this.probe && this.version !== '1.2') throw new EyemindError('triple terms require VERSION "1.2-messages"');
130
+ this.stack.push('>>');
131
+ this.at += 2;
132
+ } else {
133
+ if (!this.directive) this.hasPayload = true;
134
+ this.inIri = true;
135
+ this.at++;
136
+ }
137
+ } else if (c === '>' && i + 1 === s.length && !final) break;
138
+ else if (s.startsWith('>>', i)) {
139
+ if (this.stack.at(-1) === '>>') this.stack.pop();
140
+ this.at += 2;
141
+ } else if ('{[('.includes(c)) {
142
+ if (c === '{' && i + 1 === s.length && !final) break;
143
+ if (!this.probe && c === '{' && s[i + 1] === '|' && this.version !== '1.2') {
144
+ throw new EyemindError('annotations require VERSION "1.2-messages"');
145
+ }
146
+ this.hasPayload = true;
147
+ this.stack.push({ '{': '}', '[': ']', '(': ')' }[c]);
148
+ this.at++;
149
+ } else if ('}])'.includes(c)) {
150
+ if (this.stack.at(-1) === c) this.stack.pop();
151
+ this.at++;
152
+ } else if (';,'.includes(c) || c === '>') this.at++;
153
+ else {
154
+ let end = i;
155
+ while (end < s.length && !wordEnd(s[end])) end += s[end] === '\\' ? 2 : 1;
156
+ if (end >= s.length && !final) break;
157
+ const word = s.slice(i, end);
158
+ if (word.toUpperCase() === 'VERSION' || word === '@version') {
159
+ const rest = s.slice(end);
160
+ const match = /^\s+(["'])([^"'\r\n]*)\1/.exec(rest);
161
+ if (!match) {
162
+ if (!final && /^\s*(?:["'][^"'\r\n]*)?$/.test(rest)) break;
163
+ throw new EyemindError(`${word} needs a short quoted version label`);
164
+ }
165
+ if (this.stack.length) throw new EyemindError('VERSION is only allowed between statements');
166
+ const label = match[2];
167
+ this.isLog ||= label.endsWith('-messages');
168
+ const version = label.replace(/-messages$/, '');
169
+ if (!this.probe && (!this.isLog || !['1.1', '1.2-basic', '1.2'].includes(version))) {
170
+ throw new EyemindError(`unsupported RDF Message Log version: ${label}`);
171
+ }
172
+ this.version = version;
173
+ // Keep the underlying directive for the strict RDF parser to check
174
+ // its spelling, placement and punctuation in the selected format.
175
+ const valueStart = end + match[0].indexOf(match[1]);
176
+ const valueEnd = end + match[0].length;
177
+ this.buffer = `${s.slice(0, valueStart)}${match[1]}${version}${match[1]}${s.slice(valueEnd)}`;
178
+ this.at = valueStart + version.length + 2;
179
+ } else if (word.toUpperCase() === 'MESSAGE' || /^@message(?:\.|$)/.test(word)) {
180
+ if (!this.isLog && !this.probe) throw new EyemindError('MESSAGE needs a VERSION "*-messages" directive');
181
+ if (this.stack.length) throw new EyemindError('MESSAGE is only allowed between top-level statements');
182
+ if (word.toUpperCase() !== 'MESSAGE') {
183
+ const dot = trivia(s, i + 8, final);
184
+ if (dot === null || (dot === s.length && !final)) break;
185
+ if (s[dot] !== '.') {
186
+ throw new EyemindError('@message ends with a dot');
187
+ }
188
+ if (this.format === 'n-triples' || this.format === 'n-quads') throw new EyemindError('@message is not allowed in N-Triples or N-Quads; write MESSAGE');
189
+ end = dot + 1;
190
+ }
191
+ if (this.format === 'n-triples' || this.format === 'n-quads') {
192
+ if (word !== 'MESSAGE') throw new EyemindError('MESSAGE is case-sensitive in N-Triples and N-Quads');
193
+ const start = Math.max(s.lastIndexOf('\n', i - 1), s.lastIndexOf('\r', i - 1)) + 1;
194
+ const newline = s.slice(end).search(/[\r\n]/);
195
+ if (newline < 0 && !final) break;
196
+ const rest = s.slice(end, newline < 0 ? s.length : end + newline).replace(/#.*$/, '');
197
+ if (s.slice(start, i).trim() || rest.trim()) throw new EyemindError('MESSAGE must be on its own line in N-Triples and N-Quads');
198
+ }
199
+ this.emit(s.slice(0, i), true);
200
+ this.buffer = s.slice(end);
201
+ this.at = 0;
202
+ } else {
203
+ if (!this.probe && this.version === '1.1' && /^@[A-Za-z].*--(?:ltr|rtl)(?:\.|$)/.test(word)) {
204
+ throw new EyemindError('directional language strings require RDF 1.2 Messages');
205
+ }
206
+ if (!this.probe && this.version !== '1.2' && /(^|[^\\])~/.test(word)) {
207
+ throw new EyemindError('reification syntax requires VERSION "1.2-messages"');
208
+ }
209
+ if (['PREFIX', 'BASE'].includes(word.toUpperCase()) || ['@prefix', '@base'].includes(word)) this.directive = true;
210
+ else if (word !== '.' && !this.directive) this.hasPayload = true;
211
+ this.at = end;
212
+ }
213
+ }
214
+ }
215
+ }
216
+ }
217
+
218
+ export function isRdfMessageLog(text) {
219
+ const reader = new RdfMessageReader({ probe: true });
220
+ try {
221
+ reader.write(String(text));
222
+ reader.finish();
223
+ } catch { /* The selected parser reports malformed inputs. */ }
224
+ return reader.isLog;
225
+ }
226
+
227
+ // Materialize the application's replay vocabulary. Neither envelope links nor
228
+ // log:nameOf assert the payload's triples in the surrounding default graph.
229
+ export function replayMessages(messages, { scope = 'messages' } = {}) {
230
+ const root = `urn:eyemind:message-log:${encodeURIComponent(scope)}`;
231
+ const stream = iri(`${root}#stream`);
232
+ const envelopes = messages.map((m) => iri(`${root}#message${m.index}`));
233
+ const triples = [triple(stream, RDF_TYPE, iri(`${MESSAGE_NS}RDFMessageStream`)),
234
+ triple(stream, `${MESSAGE_NS}messageCount`, int(messages.length)),
235
+ triple(stream, `${MESSAGE_NS}orderedEnvelopes`, { t: 'list', items: envelopes })];
236
+ if (envelopes.length) triples.push(triple(stream, `${MESSAGE_NS}firstEnvelope`, envelopes[0]),
237
+ triple(stream, `${MESSAGE_NS}lastEnvelope`, envelopes.at(-1)));
238
+ const prefixes = { eymsg: MESSAGE_NS };
239
+ messages.forEach((message, i) => {
240
+ Object.assign(prefixes, message.prefixes);
241
+ const envelope = envelopes[i];
242
+ triples.push(triple(stream, `${MESSAGE_NS}envelope`, envelope),
243
+ triple(envelope, RDF_TYPE, iri(`${MESSAGE_NS}MessageEnvelope`)),
244
+ triple(envelope, `${MESSAGE_NS}offset`, int(message.index)),
245
+ triple(envelope, `${MESSAGE_NS}payloadKind`, iri(`${MESSAGE_NS}${message.quads.length ? 'nonEmpty' : 'empty'}`)));
246
+ if (envelopes[i + 1]) triples.push(triple(envelope, `${MESSAGE_NS}nextEnvelope`, envelopes[i + 1]));
247
+ if (message.quads.length) {
248
+ const payload = iri(`${envelope.v}/payload`);
249
+ const contents = readSources([message]).triples.map((t) => t.p.v === GRAPH_CONTENT && t.o.t === 'graph' ? { ...t, p: iri(LOG_NAME) } : t);
250
+ triples.push(triple(envelope, `${MESSAGE_NS}payloadGraph`, payload),
251
+ triple(payload, LOG_NAME, { t: 'graph', triples: contents, scope: 0 }));
252
+ }
253
+ });
254
+ return { triples, prefixes, quads: triples.map((t) => [...tripleToEyemind(t), DEFAULT_GRAPH]) };
255
+ }
256
+
257
+ export function parseRdfMessages(text, options = {}) {
258
+ const messages = [];
259
+ const reader = new RdfMessageReader({ ...options, onMessage: (m) => messages.push(m) });
260
+ reader.write(String(text));
261
+ reader.finish();
262
+ return { ...replayMessages(messages, options), messages };
263
+ }
package/src/n3-writer.js CHANGED
@@ -38,8 +38,8 @@ function tripleTerm(term) {
38
38
  // N3 text for triples given as [S, P, O] eyemind terms. With strings
39
39
  // 'auto', a result that has log:outputString triples is written as their
40
40
  // strings, ordered by subject, as N3 reasoners do.
41
- export function writeN3(triples, { prefixes = new Map(), strings = 'auto' } = {}) {
42
- const w = new Writer(prefixes);
41
+ export function writeN3(triples, { prefixes = new Map(), strings = 'auto', blankNodePrefix = '' } = {}) {
42
+ const w = new Writer(prefixes, blankNodePrefix);
43
43
  const outputs = triples.filter(([, p]) => isIri(p, `${LOG}outputString`));
44
44
  if (strings === true || (strings === 'auto' && outputs.length > 0)) {
45
45
  const keyed = outputs.map(([s, , o], i) => ({ s, o, i }));
@@ -99,10 +99,11 @@ function compareKeys(a, b) {
99
99
  const PN_LOCAL = /^(?:[A-Za-z_0-9À-�]|:)(?:[A-Za-z_0-9·À-�.:-]*[A-Za-z_0-9·À-�:-])?$/u;
100
100
 
101
101
  class Writer {
102
- constructor(prefixes) {
102
+ constructor(prefixes, blankNodePrefix) {
103
103
  this.prefixes = [...prefixes].sort((a, b) => b[1].length - a[1].length);
104
104
  this.used = new Set();
105
105
  this.bnodes = new Map();
106
+ this.blankNodePrefix = blankNodePrefix;
106
107
  }
107
108
 
108
109
  iri(v) {
@@ -126,7 +127,7 @@ class Writer {
126
127
  }
127
128
 
128
129
  bnode(key) {
129
- if (!this.bnodes.has(key)) this.bnodes.set(key, `_:b${this.bnodes.size}`);
130
+ if (!this.bnodes.has(key)) this.bnodes.set(key, `_:${this.blankNodePrefix}b${this.bnodes.size}`);
130
131
  return this.bnodes.get(key);
131
132
  }
132
133
 
package/src/n3.js CHANGED
@@ -23,6 +23,7 @@ import { documentIris, readDocuments } from './n3-documents.js';
23
23
  const MATH = 'http://www.w3.org/2000/10/swap/math#';
24
24
  const STRING = 'http://www.w3.org/2000/10/swap/string#';
25
25
  const LIST = 'http://www.w3.org/2000/10/swap/list#';
26
+ const GRAPH_CONTENT = 'https://eyereasoner.github.io/eyemind/graph#content';
26
27
  import { BUILTINS, HELPERS, UNSUPPORTED } from './n3-builtins.js';
27
28
 
28
29
  export class N3CompileError extends Error {}
@@ -797,15 +798,29 @@ function shortName(iri) {
797
798
 
798
799
  // N3 sources, given as [text, name] pairs, read as one document: { triples,
799
800
  // prefixes }. base resolves relative IRIs; blank-node labels are local to
800
- // each source. RDF sources, given as { quads, prefixes }, join as triples.
801
+ // each source. RDF sources, given as { quads, prefixes }, join as triples;
802
+ // named graphs become graph:content formulas, keeping their contents quoted.
801
803
  export function readSources(sources, { base = '', baseOf = () => '' } = {}) {
802
804
  if (typeof sources === 'string') sources = [[sources, 'input']];
803
805
  const docs = sources.map((source) => (Array.isArray(source)
804
806
  ? parseN3(source[0], { base: base || baseOf(source[1]) })
805
- : { triples: source.quads.map(rdfQuadToN3), prefixes: new Map(Object.entries(source.prefixes ?? {})) }));
807
+ : { triples: source.triples ?? rdfQuadsToN3(source.quads), prefixes: new Map(Object.entries(source.prefixes ?? {})) }));
806
808
  const doc = { triples: [], prefixes: new Map() };
809
+ const graphs = new Map();
807
810
  docs.forEach((d, k) => {
808
- doc.triples.push(...(docs.length > 1 ? relabel(d.triples, `s${k}.`) : d.triples));
811
+ for (const triple of docs.length > 1 ? relabel(d.triples, `s${k}.`) : d.triples) {
812
+ // The same graph can be supplied by several RDF files. Merge after
813
+ // relabelling so their blank nodes keep their own source scopes.
814
+ if (!Array.isArray(sources[k]) && triple.p.v === GRAPH_CONTENT && triple.o.t === 'graph') {
815
+ const key = `${triple.s.t}:${triple.s.v}`;
816
+ if (graphs.has(key)) {
817
+ graphs.get(key).triples.push(...triple.o.triples);
818
+ continue;
819
+ }
820
+ graphs.set(key, triple.o);
821
+ }
822
+ doc.triples.push(triple);
823
+ }
809
824
  for (const [name, ns] of d.prefixes) if (!doc.prefixes.has(name)) doc.prefixes.set(name, ns);
810
825
  });
811
826
  return doc;
@@ -825,12 +840,12 @@ const sourceNames = (sources) => (typeof sources === 'string' ? 'input' : source
825
840
  // The triples of eyemind answers as N3: the derived ones, every triple with
826
841
  // mode 'all', and the document's own log:outputString strings when the
827
842
  // result writes strings.
828
- export function answersToN3(doc, answers, { mode = 'new', strings = 'auto' } = {}) {
843
+ export function answersToN3(doc, answers, { mode = 'new', strings = 'auto', blankNodePrefix = '' } = {}) {
829
844
  let { triples, contradiction } = triplesFromEyemind(answers.join('\n'));
830
845
  const given = doc.triples.filter((x) => !isRule(x)).map(tripleToEyemind);
831
846
  if (mode === 'all') triples = [...given, ...triples];
832
847
  else if (strings !== false && triples.some(isOutputString)) triples = [...given.filter(isOutputString), ...triples];
833
- return { n3: writeN3(triples, { prefixes: doc.prefixes, strings }), triples, contradiction };
848
+ return { n3: writeN3(triples, { prefixes: doc.prefixes, strings, blankNodePrefix }), triples, contradiction };
834
849
  }
835
850
 
836
851
  // Generous bounds: N3 programs often run longer than eyemind's defaults.
@@ -861,21 +876,37 @@ function relabel(triples, prefix) {
861
876
  return triples.map(triple);
862
877
  }
863
878
 
864
- // An RDF quad, read by rdf.js, as an N3 triple; N3 has no named graphs.
865
- function rdfQuadToN3([s, p, o, g]) {
866
- if (g !== 'default_graph') throw new N3CompileError('N3 has no named graphs; give the data as Turtle or N-Triples');
867
- const term = (t) => {
868
- if (typeof t === 'bigint') return { t: 'int', v: t };
869
- const [a, b, c] = t.args;
870
- switch (t.name) {
871
- case 'iri': return { t: 'iri', v: a };
872
- case 'bnode': return { t: 'bnode', v: `${a}.${b}`, scope: 0 };
873
- case 'triple': return { t: 'triple', s: term(a), p: term(b), o: term(c) };
874
- case 'literal':
875
- if (b.name === 'lang') return { t: 'literal', v: a, lang: b.args[0], dir: b.args[1] ?? null, dt: `${RDF_NS}langString` };
876
- return typedLiteral(a, b.args[0]);
877
- default: throw new N3CompileError(`${write(t)} is no RDF term`);
879
+ // N3 has no dataset syntax. A named graph's name points to its formula;
880
+ // the formula's triples remain separate from default-graph assertions.
881
+ function rdfQuadsToN3(quads) {
882
+ const triples = [];
883
+ const graphs = new Map();
884
+ for (const [s, p, o, g] of quads) {
885
+ const triple = { s: rdfTermToN3(s), p: rdfTermToN3(p), o: rdfTermToN3(o) };
886
+ if (g === 'default_graph') triples.push(triple);
887
+ else {
888
+ const key = write(g);
889
+ if (!graphs.has(key)) {
890
+ const formula = { t: 'graph', triples: [], scope: 0 };
891
+ graphs.set(key, formula);
892
+ triples.push({ s: rdfTermToN3(g), p: { t: 'iri', v: GRAPH_CONTENT }, o: formula });
893
+ }
894
+ graphs.get(key).triples.push(triple);
878
895
  }
879
- };
880
- return { s: term(s), p: term(p), o: term(o) };
896
+ }
897
+ return triples;
898
+ }
899
+
900
+ function rdfTermToN3(t) {
901
+ if (typeof t === 'bigint') return { t: 'int', v: t };
902
+ const [a, b, c] = t.args;
903
+ switch (t.name) {
904
+ case 'iri': return { t: 'iri', v: a };
905
+ case 'bnode': return { t: 'bnode', v: `${a}.${b}`, scope: 0 };
906
+ case 'triple': return { t: 'triple', s: rdfTermToN3(a), p: rdfTermToN3(b), o: rdfTermToN3(c) };
907
+ case 'literal':
908
+ if (b.name === 'lang') return { t: 'literal', v: a, lang: b.args[0], dir: b.args[1] ?? null, dt: `${RDF_NS}langString` };
909
+ return typedLiteral(a, b.args[0]);
910
+ default: throw new N3CompileError(`${write(t)} is no RDF term`);
911
+ }
881
912
  }
@@ -0,0 +1,84 @@
1
+ // Node's incremental RDF Message input. The shared CLI supplies the operation
2
+ // to run for each message; this adapter owns only file/HTTP/stdin access.
3
+ import { createReadStream } from 'node:fs';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { resolve } from 'node:path';
6
+ import { rdfMessageFormat } from './formats.js';
7
+ import { replayMessages, RdfMessageReader } from './messages.js';
8
+
9
+ const remote = (name) => /^https?:/.test(name);
10
+
11
+ async function messageFile(name) {
12
+ if (name === '-' || remote(name)) return true;
13
+ if (/\.js$/i.test(name)) return false;
14
+ const probe = new RdfMessageReader({ probe: true });
15
+ for await (const text of createReadStream(name, { encoding: 'utf8' })) {
16
+ probe.write(text);
17
+ if (probe.isLog) return true;
18
+ if (probe.version || probe.hasPayload) return false;
19
+ }
20
+ probe.finish();
21
+ return probe.isLog;
22
+ }
23
+
24
+ async function openSource(name) {
25
+ if (name === '-') {
26
+ process.stdin.setEncoding('utf8');
27
+ return { body: process.stdin, base: null };
28
+ }
29
+ if (!remote(name)) return { body: createReadStream(name, { encoding: 'utf8' }), base: pathToFileURL(resolve(name)).href };
30
+ const controller = new AbortController();
31
+ const timer = setTimeout(() => controller.abort(), 10000);
32
+ let response;
33
+ try {
34
+ response = await fetch(name, { signal: controller.signal });
35
+ } finally {
36
+ clearTimeout(timer);
37
+ }
38
+ if (!response.ok) {
39
+ await response.body?.cancel();
40
+ throw new Error(`${name}: HTTP ${response.status}`);
41
+ }
42
+ const decoder = new TextDecoder();
43
+ async function* text() {
44
+ if (response.body) for await (const bytes of response.body) yield decoder.decode(bytes, { stream: true });
45
+ const tail = decoder.decode();
46
+ if (tail) yield tail;
47
+ }
48
+ const mediaType = response.headers.get('content-type')?.split(';')[0].trim();
49
+ const format = { 'application/n-triples': 'n-triples', 'application/n-quads': 'n-quads',
50
+ 'text/turtle': 'turtle', 'application/trig': 'trig' }[mediaType] ?? rdfMessageFormat(response.url);
51
+ return { body: text(), base: response.url, format };
52
+ }
53
+
54
+ export async function streamMessages(request, io) {
55
+ try {
56
+ const inputs = [];
57
+ const logs = [];
58
+ for (const [index, name] of request.files.entries()) {
59
+ if (await messageFile(name)) logs.push({ name, index });
60
+ else inputs.push([name, io.readFile(name)]);
61
+ }
62
+ if (!logs.length) throw new Error('--stream-messages needs an RDF Message Log with VERSION "*-messages"');
63
+ for (const { name, index } of logs) {
64
+ const source = await openSource(name);
65
+ const scope = request.scope(name, index);
66
+ let code = 0;
67
+ const reader = new RdfMessageReader({ format: source.format ?? rdfMessageFormat(name), base: request.base ?? source.base, scope,
68
+ onMessage: (message) => {
69
+ code = request.run(inputs, name, replayMessages([message], { scope }));
70
+ return code === 0;
71
+ } });
72
+ for await (const text of source.body) {
73
+ reader.write(text);
74
+ if (reader.stopped) break;
75
+ }
76
+ reader.finish();
77
+ if (code) return code;
78
+ }
79
+ return 0;
80
+ } catch (error) {
81
+ io.stderr(`eyemind: ${error.message}\n`);
82
+ return 1;
83
+ }
84
+ }
package/src/rdf-lexer.js CHANGED
@@ -385,7 +385,7 @@ const EYMSG = Object.freeze({
385
385
  nonEmpty: `<${EYMSG_NS}nonEmpty>`,
386
386
  });
387
387
 
388
- function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
388
+ function normalizeRdfCompatibility(inputText, { trig = false, messages = true } = {}) {
389
389
  let text = String(inputText ?? '');
390
390
 
391
391
  // eyemind: ordinary N3 input does not need RDF/TriG
@@ -394,7 +394,7 @@ function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
394
394
  // plausible top-level TriG named graph block.
395
395
  const hasTripleTerms = text.includes('<<');
396
396
  const hasVersionDirective = /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)\1\s*\.?\s*(?:#.*)?$/im.test(text);
397
- const hasMessageVersionDirective = /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)-messages\1\s*\.?\s*(?:#.*)?$/im.test(text);
397
+ const hasMessageVersionDirective = messages && /^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)-messages\1\s*\.?\s*(?:#.*)?$/im.test(text);
398
398
  const hasNamedGraphCandidate = /(?:^|[.\r\n])\s*(?:GRAPH\s+)?(?:<[^>\r\n]*>|_:[A-Za-z][A-Za-z0-9_-]*|[A-Za-z][A-Za-z0-9_-]*:[^\s{};,.()[\]]*|:[^\s{};,.()[\]]+)\s*\{/m.test(text);
399
399
  const hasAnnotationSyntax = /(?:^|\s)~|\{\|/.test(text);
400
400
 
@@ -865,7 +865,38 @@ function normalizeRdfCompatibility(inputText, { trig = false } = {}) {
865
865
  }
866
866
 
867
867
  function stripVersionDirectives(s) {
868
- return s.replace(/^\s*(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)(?:-messages)?\1\s*\.?\s*(?:#.*)?$/gim, '');
868
+ // eyemind: a line in a long literal can look exactly like a directive.
869
+ // Only strip tokens outside literals, IRIs and comments.
870
+ let out = '';
871
+ let i = 0;
872
+ while (i < s.length) {
873
+ if (s[i] === '"' || s[i] === "'") {
874
+ const token = readStringAt(s, i);
875
+ out += token.text;
876
+ i = token.end;
877
+ } else if (s[i] === '<' && !s.startsWith('<<', i)) {
878
+ const token = readIriAt(s, i);
879
+ out += token.text;
880
+ i = token.end;
881
+ } else if (s[i] === '#') {
882
+ const end = s.slice(i).search(/[\r\n]/);
883
+ const stop = end < 0 ? s.length : i + end + 1;
884
+ out += s.slice(i, stop);
885
+ i = stop;
886
+ } else {
887
+ const match = /^(?:@version|VERSION)\s+(["'])(?:1\.1|1\.2|1\.2-basic)(?:-messages)?\1/i.exec(s.slice(i));
888
+ if (match && (i === 0 || !isWordChar(s[i - 1]))) {
889
+ let end = i + match[0].length;
890
+ if (s.slice(i, i + 8).toLowerCase() === '@version') {
891
+ end = skipWsAndComments(s, end);
892
+ if (s[end] === '.') end++;
893
+ }
894
+ out += s.slice(i, end).replace(/[^\r\n]/g, ' ');
895
+ i = end;
896
+ } else out += s[i++];
897
+ }
898
+ }
899
+ return out;
869
900
  }
870
901
 
871
902
  function skipWsAndComments(s, at) {
@@ -1392,7 +1423,7 @@ function isNumericLikeIdentifier(word) {
1392
1423
 
1393
1424
  function lex(inputText, opts = {}) {
1394
1425
  const rdf = !!(opts && opts.rdf);
1395
- if (rdf) inputText = normalizeRdfCompatibility(inputText, { trig: !!opts.trig });
1426
+ if (rdf) inputText = normalizeRdfCompatibility(inputText, { trig: !!opts.trig, messages: opts.messages !== false });
1396
1427
  // Avoid copying large ASCII/BMP inputs into an Array. Array.from() is
1397
1428
  // only needed when the text contains surrogate pairs and we want the old
1398
1429
  // code-point iteration behavior for non-BMP characters.
@@ -471,6 +471,13 @@ class DerivedFact {
471
471
  const __iriIntern = new Map();
472
472
  const __literalIntern = new Map();
473
473
 
474
+ // eyemind: conversion produces independent eyemind terms. Keeping parser
475
+ // intern tables after that would retain every term in an unbounded log.
476
+ function clearParserCaches() {
477
+ for (const cache of [__literalPartsCache, __tidIntern, __iriTidIntern, __blankTidIntern,
478
+ __literalTidIntern, __iriIntern, __literalIntern]) cache.clear();
479
+ }
480
+
474
481
  // Do not intern extremely large literal strings (e.g., huge numeric intermediates).
475
482
  // Interning them creates global strong references that prevent GC.
476
483
  const MAX_LITERAL_INTERN_LEN = 1024;
@@ -794,6 +801,7 @@ export {
794
801
  DerivedFact,
795
802
  internIri,
796
803
  internLiteral,
804
+ clearParserCaches,
797
805
  isRdfTypePred,
798
806
  isOwlSameAsPred,
799
807
  isLogImplies,
package/src/rdf-syntax.js CHANGED
@@ -192,6 +192,7 @@ export function checkRdfSyntax(text, format) {
192
192
  case 'VERSION':
193
193
  between();
194
194
  if (next?.k !== 'string' || next.v.startsWith(next.v[0].repeat(3))) fail(`${t.v} takes a short string`);
195
+ if (/-messages["']$/.test(next.v)) fail('RDF Message Logs need parseRdfMessages, which preserves message boundaries');
195
196
  if ((ts[k + 2]?.k === '.') !== (t.k === '@version')) fail(t.k === '@version' ? '@version ends with a dot' : 'VERSION has no dot');
196
197
  directive = t.k === '@version' ? 2 : 1;
197
198
  continue;
package/src/rdf.js CHANGED
@@ -18,7 +18,7 @@
18
18
  import { lex } from './rdf-lexer.js';
19
19
  import { checkRdfSyntax } from './rdf-syntax.js';
20
20
  import { Parser } from './rdf-parser.js';
21
- import { Blank, GraphTerm, Iri, ListTerm, Literal, LOG_NS, RDF_NS, literalParts } from './rdf-prelude.js';
21
+ import { Blank, GraphTerm, Iri, ListTerm, Literal, LOG_NS, RDF_NS, clearParserCaches, literalParts } from './rdf-prelude.js';
22
22
  import { EyemindError, Struct } from './terms.js';
23
23
  import { write } from './writer.js';
24
24
 
@@ -46,7 +46,7 @@ export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf' }
46
46
  try {
47
47
  checkRdfSyntax(text, format);
48
48
  assertRdf12SurfaceSyntax(text, format);
49
- const parser = new Parser(lex(text, { rdf: true, trig: format === 'trig' }));
49
+ const parser = new Parser(lex(text, { rdf: true, trig: format === 'trig', messages: false }));
50
50
  // RDF declares every prefix it uses; N3's predeclared ones do not apply.
51
51
  parser.prefixes.map = {};
52
52
  if (base) parser.prefixes.setBase(base);
@@ -74,10 +74,12 @@ export function parseRdf(text, { format = 'turtle', base = null, scope = 'rdf' }
74
74
  if (format !== 'trig' && format !== 'n-quads' && state.out.some((q) => q[3] !== DEFAULT_GRAPH)) {
75
75
  throw new SyntaxError(`${format} has no named graphs`);
76
76
  }
77
- return { quads: state.out, prefixes: prefixesOf(parser.prefixes) };
77
+ return { quads: state.out, prefixes: prefixesOf(parser.prefixes), base: parser.prefixes.baseIri || null };
78
78
  } catch (error) {
79
79
  if (error instanceof EyemindError) throw error;
80
80
  throw new EyemindError(`${format}: ${error.message}`);
81
+ } finally {
82
+ clearParserCaches();
81
83
  }
82
84
  }
83
85
 
@@ -335,9 +337,9 @@ function assertLineSyntax(text) {
335
337
 
336
338
  // Write quads, [S, P, O, G] eyemind terms, as Turtle (or TriG when a quad is
337
339
  // in a named graph) with the prefixes it uses, or as N-Triples or N-Quads.
338
- export function writeRdf(quads, { format = 'turtle', prefixes = {} } = {}) {
340
+ export function writeRdf(quads, { format = 'turtle', prefixes = {}, blankNodePrefix = '' } = {}) {
339
341
  const line = format === 'n-triples' || format === 'n-quads';
340
- const w = new RdfWriter(line ? {} : prefixes, line);
342
+ const w = new RdfWriter(line ? {} : prefixes, line, blankNodePrefix);
341
343
  const body = [];
342
344
  if (line) {
343
345
  for (const [s, p, o, g] of quads) {
@@ -365,12 +367,13 @@ export function writeRdf(quads, { format = 'turtle', prefixes = {} } = {}) {
365
367
  const PN_LOCAL = /^(?:[A-Za-z_0-9À-�]|:)(?:[A-Za-z_0-9·À-�.:-]*[A-Za-z_0-9·À-�:-])?$/u;
366
368
 
367
369
  class RdfWriter {
368
- constructor(prefixes, line) {
370
+ constructor(prefixes, line, blankNodePrefix) {
369
371
  this.prefixes = new Map(Object.entries(prefixes));
370
372
  this.ordered = [...this.prefixes].sort((a, b) => b[1].length - a[1].length);
371
373
  this.line = line;
372
374
  this.used = new Set();
373
375
  this.bnodes = new Map();
376
+ this.blankNodePrefix = blankNodePrefix;
374
377
  }
375
378
 
376
379
  iri(v) {
@@ -399,7 +402,7 @@ class RdfWriter {
399
402
  if (t.name === 'iri' && t.args.length === 1 && typeof a === 'string') return this.iri(a);
400
403
  if ((t.name === 'bnode' && t.args.length === 2) || (t.name === 'skolem' && t.args.length === 3)) {
401
404
  const key = write(t);
402
- if (!this.bnodes.has(key)) this.bnodes.set(key, `_:b${this.bnodes.size}`);
405
+ if (!this.bnodes.has(key)) this.bnodes.set(key, `_:${this.blankNodePrefix}b${this.bnodes.size}`);
403
406
  return this.bnodes.get(key);
404
407
  }
405
408
  if (t.name === 'literal' && t.args.length === 2) return this.literal(a, b);
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.5.5';
2
+ export const VERSION = '0.5.7';