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/xml.js CHANGED
@@ -15,6 +15,10 @@ const XML = 'http://www.w3.org/XML/1998/namespace';
15
15
  const XMLNS = 'http://www.w3.org/2000/xmlns/';
16
16
  const INVALID_RAW = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u0084\u0086-\u009F\uD800-\uDFFF\uFFFE\uFFFF]/u;
17
17
 
18
+ // Whether a text is an XML name without a colon, as rdf:ID and rdf:nodeID are.
19
+ const NC_NAME_ONLY = new RegExp(`^${NC_NAME}$`, 'u');
20
+ export const isNcName = (text) => NC_NAME_ONLY.test(text);
21
+
18
22
  function match(pattern, text, at) {
19
23
  pattern.lastIndex = at;
20
24
  return pattern.exec(text);
@@ -140,3 +144,173 @@ export function isXmlContent(text) {
140
144
  }
141
145
  return open.length === 0;
142
146
  }
147
+
148
+ // An XML document as a tree, for RDF/XML: the root element, each element
149
+ // { name, ns, local, attrs, children, declared } with attrs [{ name, ns,
150
+ // local, value }] and declared the namespaces it declares, and text, comment
151
+ // and processing instruction nodes. A DOCTYPE may declare internal general
152
+ // entities; external ones are not read. Throws a SyntaxError.
153
+ // https://www.w3.org/TR/xml/#sec-documents
154
+ export function parseXml(input) {
155
+ const fail = (message) => { throw new SyntaxError(`XML: ${message}`); };
156
+ if (INVALID_RAW.test(input)) fail('a character is not allowed in XML');
157
+ const text = String(input).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
158
+ const entities = { ...ENTITIES };
159
+ let at = 0;
160
+ const take = (token) => text.startsWith(token, at) && (at += token.length, true);
161
+ const read = (pattern) => {
162
+ const found = match(pattern, text, at)?.[0];
163
+ if (found) at += found.length;
164
+ return found;
165
+ };
166
+ const until = (token, what) => {
167
+ const end = text.indexOf(token, at);
168
+ if (end < 0) fail(`unterminated ${what}`);
169
+ const body = text.slice(at, end);
170
+ at = end + token.length;
171
+ return body;
172
+ };
173
+ // Character and entity references; an entity's text may hold references.
174
+ const expand = (raw, attribute, depth = 0) => {
175
+ if (depth > 16) fail('entities nest too deeply');
176
+ let value = '', start = 0;
177
+ for (let amp = raw.indexOf('&'); amp >= 0; amp = raw.indexOf('&', start)) {
178
+ const plain = raw.slice(start, amp);
179
+ value += attribute ? plain.replace(/[\t\n]/g, ' ') : plain;
180
+ const char = reference(raw, amp);
181
+ if (char) {
182
+ value += char[1];
183
+ start = amp + char[0];
184
+ continue;
185
+ }
186
+ const named = /^&([^;\s&]+);/.exec(raw.slice(amp));
187
+ if (!named || !(named[1] in entities)) fail(`unknown reference ${raw.slice(amp, amp + 12)}`);
188
+ value += named[1] in ENTITIES ? entities[named[1]] : expand(entities[named[1]], attribute, depth + 1);
189
+ start = amp + named[0].length;
190
+ }
191
+ const rest = raw.slice(start);
192
+ return value + (attribute ? rest.replace(/[\t\n]/g, ' ') : rest);
193
+ };
194
+ const misc = () => {
195
+ for (;;) {
196
+ read(SPACE);
197
+ if (take('<!--')) {
198
+ const body = until('-->', 'comment');
199
+ if (body.includes('--')) fail('a comment contains --');
200
+ } else if (text.startsWith('<?', at) && !text.startsWith('<?xml ', at)) {
201
+ at += 2;
202
+ if (!read(PI_NAME)) fail('a processing instruction has no target');
203
+ until('?>', 'processing instruction');
204
+ } else return;
205
+ }
206
+ };
207
+ if (take('<?xml')) until('?>', 'XML declaration');
208
+ misc();
209
+ if (take('<!DOCTYPE')) {
210
+ // Internal general entities; parameter entities and external ones are not read.
211
+ let depth = 0;
212
+ const start = at;
213
+ while (at < text.length && (depth || text[at] !== '>')) {
214
+ if (text[at] === '[') depth++;
215
+ else if (text[at] === ']') depth--;
216
+ else if (text[at] === '"' || text[at] === "'") at = text.indexOf(text[at], at + 1);
217
+ if (at < 0) fail('unterminated DOCTYPE');
218
+ at++;
219
+ }
220
+ for (const [, name, , value] of text.slice(start, at).matchAll(/<!ENTITY\s+([^\s%]+)\s+(["'])([\s\S]*?)\2\s*>/g)) {
221
+ if (!(name in entities)) entities[name] = value;
222
+ }
223
+ if (!take('>')) fail('unterminated DOCTYPE');
224
+ misc();
225
+ }
226
+ const scope = [new Map([['xml', XML], ['', '']])];
227
+ const resolve = (name, element) => {
228
+ const colon = name.indexOf(':');
229
+ const prefix = colon < 0 ? '' : name.slice(0, colon), local = colon < 0 ? name : name.slice(colon + 1);
230
+ if (colon < 0 && !element) return { ns: '', local };
231
+ const ns = scope.at(-1).get(prefix);
232
+ if (ns === undefined) fail(`the prefix ${prefix} is not declared`);
233
+ return { ns, local };
234
+ };
235
+ const element = () => {
236
+ const name = read(QNAME);
237
+ if (!name) fail(`an element name is expected at offset ${at}`);
238
+ const raw = [];
239
+ while (read(SPACE) && text[at] !== '>' && text[at] !== '/') {
240
+ const attr = read(QNAME);
241
+ if (!attr) fail(`an attribute name is expected in <${name}>`);
242
+ read(SPACE);
243
+ if (!take('=')) fail(`the attribute ${attr} has no value`);
244
+ read(SPACE);
245
+ const quote = text[at++];
246
+ if (quote !== '"' && quote !== "'") fail(`the value of ${attr} is not quoted`);
247
+ const value = until(quote, 'attribute value');
248
+ if (value.includes('<')) fail(`the value of ${attr} contains <`);
249
+ if (raw.some(([n]) => n === attr)) fail(`the attribute ${attr} occurs twice`);
250
+ raw.push([attr, expand(value, true)]);
251
+ }
252
+ const empty = take('/>');
253
+ if (!empty && !take('>')) fail(`the tag <${name}> is not closed`);
254
+ const namespaces = new Map(scope.at(-1)), declared = {};
255
+ for (const [key, value] of raw) {
256
+ if (key !== 'xmlns' && !key.startsWith('xmlns:')) continue;
257
+ const prefix = key === 'xmlns' ? '' : key.slice(6);
258
+ if (prefix === 'xmlns' || value === XMLNS || (prefix === 'xml') !== (value === XML) || (prefix && !value)) fail(`the namespace declaration ${key} is not allowed`);
259
+ namespaces.set(prefix, value);
260
+ declared[prefix] = value;
261
+ }
262
+ scope.push(namespaces);
263
+ const node = { type: 'element', name, ...resolve(name, true), attrs: [], children: [], declared };
264
+ const seen = new Set();
265
+ for (const [key, value] of raw) {
266
+ if (key === 'xmlns' || key.startsWith('xmlns:')) continue;
267
+ const attr = { name: key, ...resolve(key, false), value };
268
+ if (seen.has(attr.ns + ' ' + attr.local)) fail(`the attribute ${key} occurs twice`);
269
+ seen.add(attr.ns + ' ' + attr.local);
270
+ node.attrs.push(attr);
271
+ }
272
+ if (!empty) {
273
+ for (;;) {
274
+ if (take('</')) {
275
+ if (read(QNAME) !== name) fail(`</${name}> is expected`);
276
+ read(SPACE);
277
+ if (!take('>')) fail(`the end tag of ${name} is not closed`);
278
+ break;
279
+ } else if (take('<!--')) {
280
+ const body = until('-->', 'comment');
281
+ if (body.includes('--')) fail('a comment contains --');
282
+ node.children.push({ type: 'comment', value: body });
283
+ } else if (take('<![CDATA[')) {
284
+ const value = until(']]>', 'CDATA section'), last = node.children.at(-1);
285
+ if (last?.type === 'text') last.value += value;
286
+ else node.children.push({ type: 'text', value });
287
+ } else if (take('<?')) {
288
+ const target = read(PI_NAME);
289
+ if (!target || target.toLowerCase() === 'xml') fail('a processing instruction has no valid target');
290
+ const data = take('?>') ? '' : (read(SPACE), until('?>', 'processing instruction'));
291
+ node.children.push({ type: 'pi', target, value: data });
292
+ } else if (take('<')) {
293
+ node.children.push(element());
294
+ } else if (at >= text.length) {
295
+ fail(`<${name}> is not closed`);
296
+ } else {
297
+ const end = text.indexOf('<', at);
298
+ const raw = text.slice(at, end < 0 ? text.length : end);
299
+ if (raw.includes(']]>')) fail('character data contains ]]>');
300
+ at += raw.length;
301
+ const value = expand(raw, false);
302
+ const last = node.children.at(-1);
303
+ if (last?.type === 'text') last.value += value;
304
+ else node.children.push({ type: 'text', value });
305
+ }
306
+ }
307
+ }
308
+ scope.pop();
309
+ return node;
310
+ };
311
+ if (!take('<')) fail('the document has no root element');
312
+ const root = element();
313
+ misc();
314
+ if (at < text.length) fail('only one root element is allowed');
315
+ return root;
316
+ }
package/src/rdf-rules.js DELETED
@@ -1,106 +0,0 @@
1
- /**
2
- * eyemind: RDF rule helpers
3
- *
4
- * Built-in rule helpers and utilities used by the engine. This is not the
5
- * inference engine itself, but shared rule-related machinery.
6
- */
7
-
8
-
9
- import {
10
- LOG_NS,
11
- Iri,
12
- Var,
13
- Blank,
14
- ListTerm,
15
- OpenListTerm,
16
- GraphTerm,
17
- Triple,
18
- copyQuotedGraphMetadata,
19
- INTERNAL_BLANK_VAR_PREFIX,
20
- } from './rdf-prelude.js';
21
-
22
- function liftBlankRuleVars(premise, conclusion) {
23
- function isLogIncludesLikePredicate(p) {
24
- return p instanceof Iri && (p.value === LOG_NS + 'includes' || p.value === LOG_NS + 'notIncludes');
25
- }
26
-
27
- // Map blank labels to stable rule-local variable names.
28
- // This runs at rule construction time; keep it simple and allocation-light.
29
- const mapping = Object.create(null);
30
- let counter = 0;
31
-
32
- // These variables are implementation details used to correlate one blank
33
- // node across the lifted rule body. Their names must not be spellable by
34
- // user input; otherwise a user variable such as ?_b1 can capture the
35
- // lifted blank node and leak it into the rule head. The public custom
36
- // builtin API maps these names back to ordinary-looking ?_bN variables.
37
- function blankToVar(label) {
38
- let name = mapping[label];
39
- if (name === undefined) {
40
- counter += 1;
41
- name = `${INTERNAL_BLANK_VAR_PREFIX}${counter}`;
42
- mapping[label] = name;
43
- }
44
- return new Var(name);
45
- }
46
-
47
- function copyQuotedTerm(t) {
48
- // Quoted formulas are data terms with their own local blank scope.
49
- // Copy them structurally so later in-place rewrites cannot mutate shared AST,
50
- // but do not lift their blank nodes into rule-body variables.
51
- if (t instanceof ListTerm) return new ListTerm(t.elems.map(copyQuotedTerm));
52
- if (t instanceof OpenListTerm) return new OpenListTerm(t.prefix.map(copyQuotedTerm), t.tailVar);
53
- if (t instanceof GraphTerm) {
54
- const triples = t.triples.map(
55
- (tr) => new Triple(copyQuotedTerm(tr.s), copyQuotedTerm(tr.p), copyQuotedTerm(tr.o)),
56
- );
57
- return copyQuotedGraphMetadata(t, new GraphTerm(triples));
58
- }
59
- return t;
60
- }
61
-
62
- function convertQuotedPatternTerm(t) {
63
- if (t instanceof Blank) return blankToVar(t.label);
64
- if (t instanceof ListTerm) return new ListTerm(t.elems.map(convertQuotedPatternTerm));
65
- if (t instanceof OpenListTerm) return new OpenListTerm(t.prefix.map(convertQuotedPatternTerm), t.tailVar);
66
- if (t instanceof GraphTerm) {
67
- const triples = t.triples.map(
68
- (tr) =>
69
- new Triple(convertQuotedPatternTerm(tr.s), convertQuotedPatternTerm(tr.p), convertQuotedPatternTerm(tr.o)),
70
- );
71
- return copyQuotedGraphMetadata(t, new GraphTerm(triples));
72
- }
73
- return t;
74
- }
75
-
76
- function convertTerm(t, allowDirectQuotedPattern = false) {
77
- if (t instanceof Blank) return blankToVar(t.label);
78
- if (t instanceof ListTerm) return new ListTerm(t.elems.map((e) => convertTerm(e, false)));
79
- if (t instanceof OpenListTerm)
80
- return new OpenListTerm(
81
- t.prefix.map((e) => convertTerm(e, false)),
82
- t.tailVar,
83
- );
84
- if (t instanceof GraphTerm) return allowDirectQuotedPattern ? convertQuotedPatternTerm(t) : copyQuotedTerm(t);
85
- return t;
86
- }
87
-
88
- const newPremise = premise.map((tr) => {
89
- // In log:includes / log:notIncludes, quoted formula operands are formulas
90
- // consumed by the builtin rather than ordinary triple patterns. Keep their
91
- // local blank nodes as Blank terms so the builtin can treat them as local
92
- // existentials, and bindings returned from an explicit scope are blank nodes
93
- // instead of synthetic rule variables.
94
- const keepFormulaBlanks = isLogIncludesLikePredicate(tr.p);
95
- return new Triple(
96
- keepFormulaBlanks && tr.s instanceof GraphTerm ? copyQuotedTerm(tr.s) : convertTerm(tr.s, true),
97
- convertTerm(tr.p, true),
98
- keepFormulaBlanks && tr.o instanceof GraphTerm ? copyQuotedTerm(tr.o) : convertTerm(tr.o, true),
99
- );
100
- });
101
- return [newPremise, conclusion];
102
- }
103
-
104
- export {
105
- liftBlankRuleVars,
106
- };