@dxos/echo-memory 0.0.0-stage → 0.0.0
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/LICENSE +105 -0
- package/dist/lib/Fact.mjs +1 -0
- package/dist/lib/FactFeed.mjs +1 -0
- package/dist/lib/Graph.mjs +1 -0
- package/dist/lib/Hash.mjs +1 -0
- package/dist/lib/Mapping.mjs +1 -0
- package/dist/lib/MemoryError.mjs +1 -0
- package/dist/lib/MemoryQuery.mjs +1 -0
- package/dist/lib/MemoryService.mjs +1 -0
- package/dist/lib/Ontology.mjs +1 -0
- package/dist/lib/Pipeline.mjs +1 -0
- package/dist/lib/Predicate.mjs +1 -0
- package/dist/lib/Rdf.mjs +1 -0
- package/dist/lib/RdfStore.mjs +1 -0
- package/dist/lib/Sparql.mjs +1 -0
- package/dist/lib/Subscription.mjs +1 -0
- package/dist/lib/Trig.mjs +1 -0
- package/dist/lib/Vocab.mjs +1 -0
- package/dist/lib/Vocabularies.mjs +1 -0
- package/dist/lib/chunk-Fact.mjs +245 -0
- package/dist/lib/chunk-Fact.mjs.map +1 -0
- package/dist/lib/chunk-FactFeed.mjs +29 -0
- package/dist/lib/chunk-FactFeed.mjs.map +1 -0
- package/dist/lib/chunk-Graph.mjs +147 -0
- package/dist/lib/chunk-Graph.mjs.map +1 -0
- package/dist/lib/chunk-Hash.mjs +16 -0
- package/dist/lib/chunk-Hash.mjs.map +1 -0
- package/dist/lib/chunk-Mapping.mjs +226 -0
- package/dist/lib/chunk-Mapping.mjs.map +1 -0
- package/dist/lib/chunk-MemoryError.mjs +10 -0
- package/dist/lib/chunk-MemoryError.mjs.map +1 -0
- package/dist/lib/chunk-MemoryQuery.mjs +99 -0
- package/dist/lib/chunk-MemoryQuery.mjs.map +1 -0
- package/dist/lib/chunk-MemoryService.mjs +31 -0
- package/dist/lib/chunk-MemoryService.mjs.map +1 -0
- package/dist/lib/chunk-Ontology.mjs +529 -0
- package/dist/lib/chunk-Ontology.mjs.map +1 -0
- package/dist/lib/chunk-Pipeline.mjs +84 -0
- package/dist/lib/chunk-Pipeline.mjs.map +1 -0
- package/dist/lib/chunk-Predicate.mjs +66 -0
- package/dist/lib/chunk-Predicate.mjs.map +1 -0
- package/dist/lib/chunk-Rdf.mjs +120 -0
- package/dist/lib/chunk-Rdf.mjs.map +1 -0
- package/dist/lib/chunk-RdfStore.mjs +60 -0
- package/dist/lib/chunk-RdfStore.mjs.map +1 -0
- package/dist/lib/chunk-Sparql.mjs +153 -0
- package/dist/lib/chunk-Sparql.mjs.map +1 -0
- package/dist/lib/chunk-Subscription.mjs +44 -0
- package/dist/lib/chunk-Subscription.mjs.map +1 -0
- package/dist/lib/chunk-Trig.mjs +106 -0
- package/dist/lib/chunk-Trig.mjs.map +1 -0
- package/dist/lib/chunk-Vocab.mjs +164 -0
- package/dist/lib/chunk-Vocab.mjs.map +1 -0
- package/dist/lib/chunk-Vocabularies.mjs +343 -0
- package/dist/lib/chunk-Vocabularies.mjs.map +1 -0
- package/dist/lib/chunk-rolldown-runtime.mjs +13 -0
- package/dist/lib/index.mjs +19 -0
- package/dist/types/src/Fact.d.ts +339 -0
- package/dist/types/src/Fact.d.ts.map +1 -0
- package/dist/types/src/Fact.test.d.ts +2 -0
- package/dist/types/src/Fact.test.d.ts.map +1 -0
- package/dist/types/src/FactFeed.d.ts +11 -0
- package/dist/types/src/FactFeed.d.ts.map +1 -0
- package/dist/types/src/FactFeed.test.d.ts +2 -0
- package/dist/types/src/FactFeed.test.d.ts.map +1 -0
- package/dist/types/src/Graph.d.ts +31 -0
- package/dist/types/src/Graph.d.ts.map +1 -0
- package/dist/types/src/Graph.test.d.ts +2 -0
- package/dist/types/src/Graph.test.d.ts.map +1 -0
- package/dist/types/src/Hash.d.ts +3 -0
- package/dist/types/src/Hash.d.ts.map +1 -0
- package/dist/types/src/Mapping.d.ts +18 -0
- package/dist/types/src/Mapping.d.ts.map +1 -0
- package/dist/types/src/Mapping.test.d.ts +2 -0
- package/dist/types/src/Mapping.test.d.ts.map +1 -0
- package/dist/types/src/MemoryError.d.ts +33 -0
- package/dist/types/src/MemoryError.d.ts.map +1 -0
- package/dist/types/src/MemoryQuery.d.ts +136 -0
- package/dist/types/src/MemoryQuery.d.ts.map +1 -0
- package/dist/types/src/MemoryQuery.test.d.ts +2 -0
- package/dist/types/src/MemoryQuery.test.d.ts.map +1 -0
- package/dist/types/src/MemoryService.d.ts +72 -0
- package/dist/types/src/MemoryService.d.ts.map +1 -0
- package/dist/types/src/Ontology.d.ts +115 -0
- package/dist/types/src/Ontology.d.ts.map +1 -0
- package/dist/types/src/Ontology.test.d.ts +2 -0
- package/dist/types/src/Ontology.test.d.ts.map +1 -0
- package/dist/types/src/Pipeline.d.ts +103 -0
- package/dist/types/src/Pipeline.d.ts.map +1 -0
- package/dist/types/src/Predicate.d.ts +17 -0
- package/dist/types/src/Predicate.d.ts.map +1 -0
- package/dist/types/src/Predicate.test.d.ts +2 -0
- package/dist/types/src/Predicate.test.d.ts.map +1 -0
- package/dist/types/src/Rdf.d.ts +33 -0
- package/dist/types/src/Rdf.d.ts.map +1 -0
- package/dist/types/src/Rdf.test.d.ts +2 -0
- package/dist/types/src/Rdf.test.d.ts.map +1 -0
- package/dist/types/src/RdfStore.d.ts +471 -0
- package/dist/types/src/RdfStore.d.ts.map +1 -0
- package/dist/types/src/Sparql.d.ts +58 -0
- package/dist/types/src/Sparql.d.ts.map +1 -0
- package/dist/types/src/Sparql.test.d.ts +2 -0
- package/dist/types/src/Sparql.test.d.ts.map +1 -0
- package/dist/types/src/Subscription.d.ts +100 -0
- package/dist/types/src/Subscription.d.ts.map +1 -0
- package/dist/types/src/Trig.d.ts +8 -0
- package/dist/types/src/Trig.d.ts.map +1 -0
- package/dist/types/src/Trig.test.d.ts +2 -0
- package/dist/types/src/Trig.test.d.ts.map +1 -0
- package/dist/types/src/Vocab.d.ts +90 -0
- package/dist/types/src/Vocab.d.ts.map +1 -0
- package/dist/types/src/Vocabularies.d.ts +45 -0
- package/dist/types/src/Vocabularies.d.ts.map +1 -0
- package/dist/types/src/index.d.ts +19 -0
- package/dist/types/src/index.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -0
- package/package.json +133 -3
- package/src/Fact.test.ts +74 -0
- package/src/Fact.ts +269 -0
- package/src/FactFeed.test.ts +40 -0
- package/src/FactFeed.ts +38 -0
- package/src/Graph.test.ts +106 -0
- package/src/Graph.ts +158 -0
- package/src/Hash.ts +15 -0
- package/src/Mapping.test.ts +197 -0
- package/src/Mapping.ts +320 -0
- package/src/MemoryError.ts +10 -0
- package/src/MemoryQuery.test.ts +67 -0
- package/src/MemoryQuery.ts +114 -0
- package/src/MemoryService.ts +89 -0
- package/src/Ontology.test.ts +94 -0
- package/src/Ontology.ts +571 -0
- package/src/Pipeline.ts +97 -0
- package/src/Predicate.test.ts +47 -0
- package/src/Predicate.ts +89 -0
- package/src/Rdf.test.ts +104 -0
- package/src/Rdf.ts +158 -0
- package/src/RdfStore.ts +111 -0
- package/src/Sparql.test.ts +72 -0
- package/src/Sparql.ts +237 -0
- package/src/Subscription.ts +47 -0
- package/src/Trig.test.ts +199 -0
- package/src/Trig.ts +170 -0
- package/src/Vocab.ts +134 -0
- package/src/Vocabularies.ts +204 -0
- package/src/index.ts +22 -0
- package/README.md +0 -3
package/src/Sparql.ts
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// @import-as-namespace
|
|
6
|
+
|
|
7
|
+
import type * as Schema from 'effect/Schema';
|
|
8
|
+
|
|
9
|
+
import * as Fact from './Fact.ts';
|
|
10
|
+
import * as Mapping from './Mapping.ts';
|
|
11
|
+
import type * as MemoryQuery from './MemoryQuery.ts';
|
|
12
|
+
import * as Ontology from './Ontology.ts';
|
|
13
|
+
import * as Rdf from './Rdf.ts';
|
|
14
|
+
import type * as RdfStore from './RdfStore.ts';
|
|
15
|
+
import * as Vocab from './Vocab.ts';
|
|
16
|
+
|
|
17
|
+
//
|
|
18
|
+
// How a fact query becomes SPARQL over the stored layout (one named graph per provenance, its statements inside and
|
|
19
|
+
// its provenance about it in the default graph), and how solutions become quads and facts again. Shared by every store
|
|
20
|
+
// that keeps facts as quads, so they answer a query alike.
|
|
21
|
+
//
|
|
22
|
+
|
|
23
|
+
/** A fact query in its plain form. */
|
|
24
|
+
export type Pattern = Schema.Codec.Encoded<typeof MemoryQuery.FactQuery>;
|
|
25
|
+
|
|
26
|
+
/** A solution as an engine reports it: a variable it leaves unbound may be present as `undefined`. */
|
|
27
|
+
export type Row = Readonly<Record<string, MemoryQuery.SparqlTerm | undefined>>;
|
|
28
|
+
|
|
29
|
+
/** SPARQL IRIREF excludes these characters; a UCHAR escape keeps an arbitrary IRI or key from breaking the query. */
|
|
30
|
+
const iriRef = (iri: string): string =>
|
|
31
|
+
`<${[...iri]
|
|
32
|
+
.map((char) =>
|
|
33
|
+
char <= ' ' || '<>"{}|^`\\'.includes(char) ? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}` : char,
|
|
34
|
+
)
|
|
35
|
+
.join('')}>`;
|
|
36
|
+
|
|
37
|
+
const ONTOLOGY = iriRef(Vocab.ONTOLOGY_GRAPH);
|
|
38
|
+
|
|
39
|
+
const KINDS = Mapping.KIND_CLASSES.map(iriRef).join(', ');
|
|
40
|
+
|
|
41
|
+
/** Excludes rows that are not statements: the ontology graph, and an entity's label or kind. */
|
|
42
|
+
const statementFilter = (graph: string, predicate: string, object: string) =>
|
|
43
|
+
`FILTER(${graph} != ${ONTOLOGY} && ${predicate} != ${iriRef(Vocab.RDFS_LABEL)} && !(${predicate} = ${iriRef(Vocab.RDF_TYPE)} && ${object} IN (${KINDS})))`;
|
|
44
|
+
|
|
45
|
+
/** An entity key names its IRI exactly, and a slug also names the graph-local entity of that slug in every graph. */
|
|
46
|
+
const isEntity = (variable: string, key: string): string => {
|
|
47
|
+
const node = iriRef(Vocab.entityNode(key).value);
|
|
48
|
+
return Vocab.isIri(key)
|
|
49
|
+
? `${variable} = ${node}`
|
|
50
|
+
: `(${variable} = ${node} || (isIRI(${variable}) && STRENDS(STR(${variable}), ${JSON.stringify(Vocab.localEntitySuffix(key))})))`;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Every quad of the ontology graph (predicate labels), as `?g ?s ?p ?o`. */
|
|
54
|
+
export const ONTOLOGY_SPARQL = `SELECT ?g ?s ?p ?o WHERE { VALUES ?g { ${ONTOLOGY} } GRAPH ?g { ?s ?p ?o } }`;
|
|
55
|
+
|
|
56
|
+
/** The distinct predicates of every stored statement. */
|
|
57
|
+
export const STORED_PREDICATES_SPARQL = `SELECT DISTINCT ?p WHERE { GRAPH ?g { ?s ?p ?o } ${statementFilter('?g', '?p', '?o')} }`;
|
|
58
|
+
|
|
59
|
+
/** Every predicate the ontology graph already describes as an `rdf:Property`. */
|
|
60
|
+
export const DESCRIBED_PREDICATES_SPARQL = `SELECT DISTINCT ?s WHERE { GRAPH ${ONTOLOGY} { ?s ${iriRef(Vocab.RDF_TYPE)} ${iriRef(Vocab.RDF_PROPERTY)} } }`;
|
|
61
|
+
|
|
62
|
+
/** The seed-version marker, kept in the default graph about the ontology graph. */
|
|
63
|
+
export const SEED_MARKER_SPARQL = `SELECT ?v WHERE { ${ONTOLOGY} ${iriRef(Vocab.SX_SEED)} ?v }`;
|
|
64
|
+
|
|
65
|
+
/** SPARQL UPDATEs removing the seed marker and the ontology-graph description of each of `iris`, one per request. */
|
|
66
|
+
export const deleteSeedSparql = (iris: readonly string[]): string[] => [
|
|
67
|
+
`DELETE WHERE { ${ONTOLOGY} ${iriRef(Vocab.SX_SEED)} ?v }`,
|
|
68
|
+
...iris.map((iri) => `DELETE WHERE { GRAPH ${ONTOLOGY} { ${iriRef(iri)} ?p ?o } }`),
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
/** The label of each stored predicate: from the ontology graph, else the ontology, else its IRI. */
|
|
72
|
+
export const predicateLabels = (
|
|
73
|
+
stored: Iterable<string>,
|
|
74
|
+
ontologyQuads: readonly Rdf.Quad[],
|
|
75
|
+
ontology: Ontology.Ontology = Ontology.DEFAULT,
|
|
76
|
+
): Map<string, string> => {
|
|
77
|
+
const labels = new Map<string, string>();
|
|
78
|
+
for (const quad of ontologyQuads) {
|
|
79
|
+
if (quad.predicate.value === Vocab.RDFS_LABEL && !labels.has(quad.subject.value)) {
|
|
80
|
+
labels.set(quad.subject.value, quad.object.value);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return new Map(
|
|
84
|
+
[...stored].map((iri) => [iri, labels.get(iri) ?? ontology.get(iri)?.label ?? Ontology.labelFromIri(iri)]),
|
|
85
|
+
);
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Group pattern binding `?g` to every named graph holding a statement that matches each of the query's
|
|
90
|
+
* constraints, with `predicates` the IRIs its predicate names. Confidence is not a constraint here: the caller
|
|
91
|
+
* re-checks every statement (`statementMatches`).
|
|
92
|
+
*/
|
|
93
|
+
export const candidateGraphs = (query: Pattern, predicates?: ReadonlySet<string>): string => {
|
|
94
|
+
const patterns: string[] = [];
|
|
95
|
+
if (query.subjectEntity) {
|
|
96
|
+
patterns.push(
|
|
97
|
+
`{ GRAPH ?g { ?ss ?sp ?so } ${statementFilter('?g', '?sp', '?so')} FILTER(${isEntity('?ss', query.subjectEntity)}) }`,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
if (predicates) {
|
|
101
|
+
patterns.push(
|
|
102
|
+
`{ GRAPH ?g { ?ps ?pp ?po } FILTER(?g != ${ONTOLOGY} && ?pp IN (${[...predicates].map(iriRef).join(', ')})) }`,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
if (query.source) {
|
|
106
|
+
patterns.push(`?g ${iriRef(`${Vocab.PROV}wasDerivedFrom`)} ${JSON.stringify(query.source)} .`);
|
|
107
|
+
}
|
|
108
|
+
if (query.entity) {
|
|
109
|
+
patterns.push(
|
|
110
|
+
`{ GRAPH ?g { ?es ?ep ?eo } ${statementFilter('?g', '?ep', '?eo')} FILTER(${isEntity('?es', query.entity)} || ${isEntity('?eo', query.entity)}) }`,
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return patterns.length === 0 ? `?g ${iriRef(Vocab.RDF_TYPE)} ${iriRef(Vocab.SX_GRAPH)} .` : patterns.join('\n');
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/** Group pattern binding `?g` to exactly the given graph IRIs. */
|
|
117
|
+
export const graphValues = (graphs: readonly string[]): string => `VALUES ?g { ${graphs.map(iriRef).join(' ')} }`;
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* SPARQL loading every quad of the graphs `candidates` binds, as `?g ?s ?p ?o`, and each graph's provenance from
|
|
121
|
+
* the default graph, as `?g ?p ?o` with `?s` unbound.
|
|
122
|
+
*/
|
|
123
|
+
export const graphQuadsSparql = (candidates: string): string =>
|
|
124
|
+
`SELECT ?g ?s ?p ?o WHERE { { SELECT DISTINCT ?g WHERE { ${candidates} } } { GRAPH ?g { ?s ?p ?o } } UNION { ?g ?p ?o } }`;
|
|
125
|
+
|
|
126
|
+
/** Whether one relation key's words occur, in order and whole, in another's: `is a` (key `a`) is not in `work_at`. */
|
|
127
|
+
const contains = (haystack: string, needle: string): boolean => {
|
|
128
|
+
const words = haystack.split('_');
|
|
129
|
+
const sought = needle.split('_');
|
|
130
|
+
return words.some((_, start) => sought.every((word, offset) => words[start + offset] === word));
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The stored predicates a query's predicate names: those its surface form resolves to through the ontology, and
|
|
135
|
+
* those whose label or synonyms share its relation key, either way round, since a model rarely reproduces the
|
|
136
|
+
* stored phrase verbatim.
|
|
137
|
+
*/
|
|
138
|
+
export const matchingPredicates = (
|
|
139
|
+
surface: string,
|
|
140
|
+
predicates: ReadonlyMap<string, string>,
|
|
141
|
+
ontology: Ontology.Ontology = Ontology.DEFAULT,
|
|
142
|
+
): Set<string> => {
|
|
143
|
+
if (Vocab.isIri(surface)) {
|
|
144
|
+
return ontology.equivalents(surface);
|
|
145
|
+
}
|
|
146
|
+
const needle = Ontology.key(surface);
|
|
147
|
+
const matches = new Set([ontology.resolve(surface).iri]);
|
|
148
|
+
for (const [iri, label] of predicates) {
|
|
149
|
+
const entry = ontology.get(iri);
|
|
150
|
+
const keys = [label, ...(entry ? [entry.name, ...(entry.synonyms ?? [])] : [])].map(Ontology.key);
|
|
151
|
+
if (keys.some((key) => contains(key, needle) || contains(needle, key))) {
|
|
152
|
+
matches.add(iri);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// Merged predicates match each other, so statements made before a merge still answer.
|
|
156
|
+
return new Set([...matches].flatMap((iri) => [...ontology.equivalents(iri)]));
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Whether a statement satisfies the query. Candidate graphs are found by any statement in them, so each statement
|
|
161
|
+
* is checked again here: a graph about Rich may also hold a statement about DXOS.
|
|
162
|
+
*/
|
|
163
|
+
export const statementMatches = (fact: Fact.Fact, query: Pattern, predicates?: ReadonlySet<string>): boolean => {
|
|
164
|
+
const subject = Fact.termValue(fact.assertion.subject);
|
|
165
|
+
const object = Fact.termValue(fact.assertion.object);
|
|
166
|
+
return (
|
|
167
|
+
(query.subjectEntity === undefined || subject === query.subjectEntity) &&
|
|
168
|
+
(query.entity === undefined ||
|
|
169
|
+
subject === query.entity ||
|
|
170
|
+
(fact.assertion.object.kind === 'entity' && object === query.entity)) &&
|
|
171
|
+
(predicates === undefined || predicates.has(fact.assertion.predicateIri ?? '')) &&
|
|
172
|
+
(query.source === undefined || fact.attribution.source === query.source) &&
|
|
173
|
+
(query.minConfidence === undefined || (fact.factuality.confidence ?? 0) >= query.minConfidence)
|
|
174
|
+
);
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const { blankNode, defaultGraph, literal, namedNode, quad } = Rdf;
|
|
178
|
+
|
|
179
|
+
const XSD_STRING = 'http://www.w3.org/2001/XMLSchema#string';
|
|
180
|
+
|
|
181
|
+
/** RDF/JS term → the engine's plain-data term. */
|
|
182
|
+
export const toTerm = (term: Rdf.Term): MemoryQuery.SparqlTerm => {
|
|
183
|
+
switch (term.termType) {
|
|
184
|
+
case 'NamedNode':
|
|
185
|
+
case 'BlankNode':
|
|
186
|
+
return { termType: term.termType, value: term.value };
|
|
187
|
+
case 'Literal':
|
|
188
|
+
return term.language
|
|
189
|
+
? { termType: 'Literal', value: term.value, language: term.language }
|
|
190
|
+
: term.datatype.value === XSD_STRING
|
|
191
|
+
? { termType: 'Literal', value: term.value }
|
|
192
|
+
: { termType: 'Literal', value: term.value, datatype: term.datatype.value };
|
|
193
|
+
default:
|
|
194
|
+
throw new TypeError(`Unsupported term in a stored triple: ${term.termType}`);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
/** RDF/JS quad → engine quad (the default graph is the engine's absent `g`). */
|
|
199
|
+
export const toQuad = (triple: Rdf.Quad): RdfStore.Quad => ({
|
|
200
|
+
s: toTerm(triple.subject),
|
|
201
|
+
p: toTerm(triple.predicate),
|
|
202
|
+
o: toTerm(triple.object),
|
|
203
|
+
...(triple.graph.termType === 'DefaultGraph' ? {} : { g: toTerm(triple.graph) }),
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
const toResource = (term: MemoryQuery.SparqlTerm) =>
|
|
207
|
+
term.termType === 'BlankNode' ? blankNode(term.value) : namedNode(term.value);
|
|
208
|
+
|
|
209
|
+
const toObject = (term: MemoryQuery.SparqlTerm) =>
|
|
210
|
+
term.termType === 'Literal'
|
|
211
|
+
? literal(term.value, term.language ?? (term.datatype ? namedNode(term.datatype) : undefined))
|
|
212
|
+
: toResource(term);
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* `?g ?s ?p ?o` solutions as quads: a row with `?s` bound is a quad in graph `?g`, one without it is a default-graph
|
|
216
|
+
* triple about `?g` (its provenance). Rows with a literal in a resource position are skipped.
|
|
217
|
+
*/
|
|
218
|
+
export const rowsToQuads = (rows: readonly Row[]): Rdf.Quad[] =>
|
|
219
|
+
rows.flatMap(({ g, s, p, o }) => {
|
|
220
|
+
if (g?.termType !== 'NamedNode' || p?.termType !== 'NamedNode' || o === undefined) {
|
|
221
|
+
return [];
|
|
222
|
+
}
|
|
223
|
+
if (s === undefined) {
|
|
224
|
+
return [quad(namedNode(g.value), namedNode(p.value), toObject(o), defaultGraph())];
|
|
225
|
+
}
|
|
226
|
+
return s.termType === 'Literal' ? [] : [quad(toResource(s), namedNode(p.value), toObject(o), namedNode(g.value))];
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
/** The distinct graph IRIs a raw SELECT binds to `?g`, or to `?fact`, the variable of the earlier reified shape. */
|
|
230
|
+
export const boundGraphs = (rows: readonly Row[]): string[] => [
|
|
231
|
+
...new Set(
|
|
232
|
+
rows.flatMap((row) => {
|
|
233
|
+
const graph = row.g ?? row.fact;
|
|
234
|
+
return graph?.termType === 'NamedNode' ? [graph.value] : [];
|
|
235
|
+
}),
|
|
236
|
+
),
|
|
237
|
+
];
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// @import-as-namespace
|
|
6
|
+
|
|
7
|
+
import * as Schema from 'effect/Schema';
|
|
8
|
+
|
|
9
|
+
import * as Fact from './Fact.ts';
|
|
10
|
+
|
|
11
|
+
/** A subscription's id, unique in its space; chosen by the caller. */
|
|
12
|
+
export const SubscriptionId = Schema.String.pipe(Schema.brand('@dxos/echo-memory/SubscriptionId'));
|
|
13
|
+
export type SubscriptionId = Schema.Schema.Type<typeof SubscriptionId>;
|
|
14
|
+
|
|
15
|
+
/** An event's id, stable per subscription, wake and facts, so a wake derived twice queues once. */
|
|
16
|
+
export const MemoryEventId = Schema.String.pipe(Schema.brand('@dxos/echo-memory/MemoryEventId'));
|
|
17
|
+
export type MemoryEventId = Schema.Schema.Type<typeof MemoryEventId>;
|
|
18
|
+
|
|
19
|
+
/** Most subscriptions one space's memory holds at once. */
|
|
20
|
+
export const MAX_SUBSCRIPTIONS = 256;
|
|
21
|
+
|
|
22
|
+
/** Goal rules held against a space's memory, and the caller's own record of why. */
|
|
23
|
+
export const Subscription = Schema.Struct({
|
|
24
|
+
id: SubscriptionId,
|
|
25
|
+
/** The agent that holds it; `subscriptions(owner)` filters by it. */
|
|
26
|
+
owner: Schema.optional(Fact.EntityKey),
|
|
27
|
+
/** Datalog goal rules (`@dxos/brain`). */
|
|
28
|
+
rules: Schema.String,
|
|
29
|
+
/** ISO; facts put before it wake nothing. */
|
|
30
|
+
createdAt: Schema.String,
|
|
31
|
+
/** Stored and returned as is; never interpreted by memory. */
|
|
32
|
+
payload: Schema.optional(Schema.Unknown),
|
|
33
|
+
});
|
|
34
|
+
export interface Subscription extends Schema.Schema.Type<typeof Subscription> {}
|
|
35
|
+
|
|
36
|
+
/** One wake of a subscription's rules, queued in its outbox until acknowledged. */
|
|
37
|
+
export const MemoryEvent = Schema.Struct({
|
|
38
|
+
id: MemoryEventId,
|
|
39
|
+
subscription: SubscriptionId,
|
|
40
|
+
/** The rules' wake label, `achieved`, or a sub-goal id. */
|
|
41
|
+
label: Schema.String,
|
|
42
|
+
/** The facts behind the wake; empty for a wake the clock caused. */
|
|
43
|
+
facts: Schema.Array(Fact.Fact),
|
|
44
|
+
/** When it woke (ISO). */
|
|
45
|
+
at: Schema.String,
|
|
46
|
+
});
|
|
47
|
+
export interface MemoryEvent extends Schema.Schema.Type<typeof MemoryEvent> {}
|
package/src/Trig.test.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import { Parser, Writer } from 'n3';
|
|
6
|
+
import { describe, test } from 'vitest';
|
|
7
|
+
|
|
8
|
+
import * as Fact from './Fact.ts';
|
|
9
|
+
import * as Graph from './Graph.ts';
|
|
10
|
+
import * as Mapping from './Mapping.ts';
|
|
11
|
+
import * as Pipeline from './Pipeline.ts';
|
|
12
|
+
import * as Rdf from './Rdf.ts';
|
|
13
|
+
import * as Trig from './Trig.ts';
|
|
14
|
+
|
|
15
|
+
const EX = 'https://example.org/';
|
|
16
|
+
const XSD = 'http://www.w3.org/2001/XMLSchema#';
|
|
17
|
+
|
|
18
|
+
/** n3's TriG for the same quads, the format this writer reproduces. */
|
|
19
|
+
const n3Trig = (quads: readonly Rdf.Quad[], prefixes: Record<string, string> = {}): string => {
|
|
20
|
+
const writer = new Writer({ format: 'application/trig', prefixes });
|
|
21
|
+
writer.addQuads([...quads]);
|
|
22
|
+
let output = '';
|
|
23
|
+
writer.end((error, result) => {
|
|
24
|
+
if (error) {
|
|
25
|
+
throw error;
|
|
26
|
+
}
|
|
27
|
+
output = result;
|
|
28
|
+
});
|
|
29
|
+
return output;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const parse = (trig: string): Rdf.Quad[] => new Parser({ format: 'application/trig' }).parse(trig);
|
|
33
|
+
|
|
34
|
+
/** Order-insensitive equality in which each quad consumes its own match, so a duplicate cannot stand in for a loss. */
|
|
35
|
+
const sameQuads = (left: readonly Rdf.Quad[], right: readonly Rdf.Quad[]): boolean => {
|
|
36
|
+
const unmatched = [...right];
|
|
37
|
+
return (
|
|
38
|
+
left.length === right.length &&
|
|
39
|
+
left.every((quad) => {
|
|
40
|
+
const index = unmatched.findIndex((other) => other.equals(quad));
|
|
41
|
+
return index >= 0 && unmatched.splice(index, 1).length === 1;
|
|
42
|
+
})
|
|
43
|
+
);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const ex = (name: string) => Rdf.namedNode(`${EX}${name}`);
|
|
47
|
+
|
|
48
|
+
const fact = (id: string, quote: string): Fact.Fact =>
|
|
49
|
+
Fact.make({
|
|
50
|
+
id,
|
|
51
|
+
assertion: {
|
|
52
|
+
subject: { kind: 'entity', entity: 'rich', label: 'Rich "the founder"' },
|
|
53
|
+
predicate: 'has role',
|
|
54
|
+
object: { kind: 'entity', entity: 'founder' },
|
|
55
|
+
quote,
|
|
56
|
+
},
|
|
57
|
+
factuality: { value: 'CT+', polarity: '+' },
|
|
58
|
+
attribution: { source: 'https://dxos.org/team', generatedAtTime: '2026-10-13T00:00:00Z' },
|
|
59
|
+
recordedAt: '2026-10-13T00:00:00Z',
|
|
60
|
+
extractor: { id: 'default', model: 'm', version: '1' },
|
|
61
|
+
sourceHash: 'h',
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
describe('Trig', () => {
|
|
65
|
+
test('writes nothing for no quads, and only the prefix block for prefixes alone', ({ expect }) => {
|
|
66
|
+
expect(Trig.write([])).toBe('');
|
|
67
|
+
expect(Trig.write([], { prefixes: { ex: EX } })).toBe(n3Trig([], { ex: EX }));
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('groups a subject with `;` and a predicate with `,`, in the default and a named graph', ({ expect }) => {
|
|
71
|
+
const quads = [
|
|
72
|
+
Rdf.quad(ex('s'), ex('p'), ex('o1')),
|
|
73
|
+
Rdf.quad(ex('s'), ex('p'), ex('o2')),
|
|
74
|
+
Rdf.quad(ex('s'), ex('q'), Rdf.literal('v')),
|
|
75
|
+
Rdf.quad(ex('t'), ex('p'), ex('o1')),
|
|
76
|
+
Rdf.quad(ex('s'), ex('p'), ex('o1'), ex('g')),
|
|
77
|
+
Rdf.quad(ex('s'), ex('q'), ex('o2'), ex('g')),
|
|
78
|
+
Rdf.quad(ex('u'), ex('p'), ex('o1'), ex('h')),
|
|
79
|
+
Rdf.quad(ex('s'), ex('p'), ex('o3')),
|
|
80
|
+
];
|
|
81
|
+
expect(Trig.write(quads)).toBe(n3Trig(quads));
|
|
82
|
+
expect(Trig.write(quads, { prefixes: { ex: EX } })).toBe(n3Trig(quads, { ex: EX }));
|
|
83
|
+
expect(sameQuads(parse(Trig.write(quads, { prefixes: { ex: EX } })), quads)).toBe(true);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
test('abbreviates IRIs only where the local name is valid, and writes rdf:type as `a`', ({ expect }) => {
|
|
87
|
+
const quads = [
|
|
88
|
+
Rdf.quad(ex('valid_name-1'), Rdf.namedNode(Rdf.RDF_TYPE), ex('Thing')),
|
|
89
|
+
Rdf.quad(ex('has/slash'), ex('p'), ex('with space')),
|
|
90
|
+
Rdf.quad(ex('café'), ex('p'), Rdf.namedNode(`${EX}`)),
|
|
91
|
+
Rdf.quad(Rdf.namedNode('https://other.org/x'), ex('p'), Rdf.blankNode('b1')),
|
|
92
|
+
];
|
|
93
|
+
const prefixes = { ex: EX, other: 'https://other.org/' };
|
|
94
|
+
expect(Trig.write(quads, { prefixes })).toBe(n3Trig(quads, prefixes));
|
|
95
|
+
expect(Trig.write(quads, { prefixes })).toContain('ex:valid_name-1 a ex:Thing');
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('a later prefix for the same namespace replaces the earlier one', ({ expect }) => {
|
|
99
|
+
const quads = [Rdf.quad(ex('s'), ex('p'), ex('o'))];
|
|
100
|
+
const prefixes = { first: EX, second: EX };
|
|
101
|
+
expect(Trig.write(quads, { prefixes })).toBe(n3Trig(quads, prefixes));
|
|
102
|
+
expect(Trig.write(quads, { prefixes })).toContain('second:s second:p second:o');
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
test('escapes literals: quotes, backslashes, control characters and astral characters', ({ expect }) => {
|
|
106
|
+
const values = [
|
|
107
|
+
'say "hi"',
|
|
108
|
+
'back\\slash',
|
|
109
|
+
'tab\tline\nreturn\rfeed\fbell\b',
|
|
110
|
+
'\u0001\u0019\u001a\u001f',
|
|
111
|
+
'emoji 😀',
|
|
112
|
+
'lone \ud800 high',
|
|
113
|
+
'lone \udc00 low',
|
|
114
|
+
'plain',
|
|
115
|
+
];
|
|
116
|
+
const quads = values.map((value, index) => Rdf.quad(ex(`s${index}`), ex('p'), Rdf.literal(value)));
|
|
117
|
+
expect(Trig.write(quads)).toBe(n3Trig(quads));
|
|
118
|
+
expect(parse(Trig.write(quads)).map((quad) => quad.object.value)).toEqual(values);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
test('writes language tags, abbreviates valid numbers and booleans, and keeps other datatypes', ({ expect }) => {
|
|
122
|
+
const typed = (value: string, type: string) => Rdf.literal(value, Rdf.namedNode(`${XSD}${type}`));
|
|
123
|
+
const objects = [
|
|
124
|
+
Rdf.literal('chat', 'fr'),
|
|
125
|
+
typed('42', 'integer'),
|
|
126
|
+
typed('-4.2', 'decimal'),
|
|
127
|
+
typed('1.5e3', 'double'),
|
|
128
|
+
typed('true', 'boolean'),
|
|
129
|
+
typed('maybe', 'boolean'),
|
|
130
|
+
typed('4x', 'integer'),
|
|
131
|
+
typed('2026-10-13', 'date'),
|
|
132
|
+
Rdf.literal('{}', Rdf.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#JSON')),
|
|
133
|
+
];
|
|
134
|
+
const quads = objects.map((object, index) => Rdf.quad(ex(`s${index}`), ex('p'), object));
|
|
135
|
+
expect(Trig.write(quads)).toBe(n3Trig(quads));
|
|
136
|
+
expect(Trig.write(quads, { prefixes: { xsd: XSD } })).toBe(n3Trig(quads, { xsd: XSD }));
|
|
137
|
+
expect(sameQuads(parse(Trig.write(quads, { prefixes: { xsd: XSD } })), quads)).toBe(true);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("a store's facts round-trip through an independent TriG parser", ({ expect }) => {
|
|
141
|
+
const facts = Graph.assign([fact('a', 'Rich is the founder.'), fact('b', 'He said: "I founded it"\n— twice.')]);
|
|
142
|
+
const quads = facts.flatMap((placed) => Mapping.factToTriples(placed));
|
|
143
|
+
const trig = Graph.toTriG(facts);
|
|
144
|
+
const parsed = parse(trig);
|
|
145
|
+
expect(sameQuads(parsed, quads)).toBe(true);
|
|
146
|
+
expect(Mapping.triplesToFacts(parsed)).toEqual(Mapping.triplesToFacts(quads));
|
|
147
|
+
expect(trig).toBe(
|
|
148
|
+
n3Trig(
|
|
149
|
+
quads,
|
|
150
|
+
Object.fromEntries(
|
|
151
|
+
[...trig.matchAll(/^@prefix (\w+): <([^>]+)>\.$/gm)].map(([, prefix, iri]) => [prefix, iri]),
|
|
152
|
+
),
|
|
153
|
+
),
|
|
154
|
+
);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
test("a pipeline's state round-trips as TriG", ({ expect }) => {
|
|
158
|
+
const state: Pipeline.State = {
|
|
159
|
+
name: 'crawl "general"',
|
|
160
|
+
status: 'done',
|
|
161
|
+
startedAt: '2026-10-13T00:00:00Z',
|
|
162
|
+
endedAt: '2026-10-13T01:00:00Z',
|
|
163
|
+
sources: [{ id: 'general', items: 3, cursor: '42' }],
|
|
164
|
+
stages: [{ id: 'extract', label: 'Extract', order: 0, models: [] }],
|
|
165
|
+
facts: 7,
|
|
166
|
+
};
|
|
167
|
+
const quads = Pipeline.toQuads(state);
|
|
168
|
+
const trig = Trig.write(quads);
|
|
169
|
+
expect(trig).toBe(n3Trig(quads));
|
|
170
|
+
expect(Pipeline.fromValues(parse(trig).map((quad) => quad.object.value))).toEqual([state]);
|
|
171
|
+
});
|
|
172
|
+
test('abbreviates only namespace IRIs: a bracketed namespace is matched literally and a prefix-like IRI stays whole', ({
|
|
173
|
+
expect,
|
|
174
|
+
}) => {
|
|
175
|
+
const prefixes = { local: 'https://[::1]/', ex: EX };
|
|
176
|
+
const quads = [
|
|
177
|
+
Rdf.quad(Rdf.namedNode('https://[::1]/thing'), Rdf.namedNode('https://example'), Rdf.literal('one')),
|
|
178
|
+
Rdf.quad(Rdf.namedNode('ex:Post'), ex('p'), Rdf.literal('two')),
|
|
179
|
+
];
|
|
180
|
+
const trig = Trig.write(quads, { prefixes });
|
|
181
|
+
expect(trig).toContain('local:thing <https://example> "one"');
|
|
182
|
+
expect(trig).toContain('<ex:Post> ex:p "two"');
|
|
183
|
+
expect(sameQuads(new Parser({ format: 'application/trig' }).parse(trig), quads)).toBe(true);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
test('keeps the base direction of a language-tagged literal, as n3 does', ({ expect }) => {
|
|
187
|
+
const quads = [Rdf.quad(ex('s'), ex('p'), Rdf.literal('مرحبا', { language: 'ar', direction: 'rtl' }))];
|
|
188
|
+
const trig = Trig.write(quads);
|
|
189
|
+
expect(trig).toBe(n3Trig(quads));
|
|
190
|
+
expect(trig).toContain('"مرحبا"@ar--rtl');
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
test('refuses quoted triples and variables rather than writing them as other terms', ({ expect }) => {
|
|
194
|
+
const quoted = Rdf.quad(ex('s'), ex('p'), Rdf.literal('o'));
|
|
195
|
+
expect(() => Trig.write([Rdf.quad(ex('s'), ex('p'), quoted)])).toThrow(/quoted triple/);
|
|
196
|
+
expect(() => Trig.write([Rdf.quad(ex('s'), Rdf.variable('p'), ex('o'))])).toThrow(/variable/);
|
|
197
|
+
expect(() => Trig.write([Rdf.quad(ex('s'), ex('p'), Rdf.variable('o'))])).toThrow(/variable/);
|
|
198
|
+
});
|
|
199
|
+
});
|
package/src/Trig.ts
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright 2026 DXOS.org
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
// @import-as-namespace
|
|
6
|
+
|
|
7
|
+
import * as Rdf from './Rdf.ts';
|
|
8
|
+
|
|
9
|
+
//
|
|
10
|
+
// A TriG writer whose output matches n3's `Writer` in TriG mode character for character (prefix block, named graph
|
|
11
|
+
// blocks, `;` and `,` grouping, datatype abbreviations, escapes, base direction), so readers of n3's TriG keep working;
|
|
12
|
+
// it differs only where n3's output would not read back: an IRI that only looks prefixed stays bracketed, and quoted
|
|
13
|
+
// triples and variables are refused.
|
|
14
|
+
//
|
|
15
|
+
|
|
16
|
+
const XSD = 'http://www.w3.org/2001/XMLSchema#';
|
|
17
|
+
|
|
18
|
+
const ESCAPES: Readonly<Record<string, string>> = {
|
|
19
|
+
'\\': '\\\\',
|
|
20
|
+
'"': '\\"',
|
|
21
|
+
'\t': '\\t',
|
|
22
|
+
'\n': '\\n',
|
|
23
|
+
'\r': '\\r',
|
|
24
|
+
'\b': '\\b',
|
|
25
|
+
'\f': '\\f',
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const escapeCharacter = (character: string): string => {
|
|
29
|
+
const known = ESCAPES[character];
|
|
30
|
+
if (known !== undefined) {
|
|
31
|
+
return known;
|
|
32
|
+
}
|
|
33
|
+
if (character.length === 1) {
|
|
34
|
+
return `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`;
|
|
35
|
+
}
|
|
36
|
+
// A surrogate pair: its code point as an 8-digit escape.
|
|
37
|
+
const codePoint = (character.charCodeAt(0) - 0xd800) * 0x400 + character.charCodeAt(1) + 0x2400;
|
|
38
|
+
return `\\U${codePoint.toString(16).padStart(8, '0')}`;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** Code units up to U+0019 are escaped, as n3 does (it leaves U+001A..U+001F as they are). */
|
|
42
|
+
const isEscaped = (code: number): boolean => code === 0x22 || code === 0x5c || code <= 0x19;
|
|
43
|
+
const isHighSurrogate = (code: number): boolean => code >= 0xd800 && code <= 0xdbff;
|
|
44
|
+
const isLowSurrogate = (code: number): boolean => code >= 0xdc00 && code <= 0xdfff;
|
|
45
|
+
|
|
46
|
+
/** Escapes quotes, backslashes, control characters and surrogate pairs, scanning code units so no regex holds control characters. */
|
|
47
|
+
const escape = (text: string): string => {
|
|
48
|
+
let output = '';
|
|
49
|
+
let start = 0;
|
|
50
|
+
for (let index = 0; index < text.length; index++) {
|
|
51
|
+
const code = text.charCodeAt(index);
|
|
52
|
+
const width = isEscaped(code) ? 1 : isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1)) ? 2 : 0;
|
|
53
|
+
if (width > 0) {
|
|
54
|
+
output += text.slice(start, index) + escapeCharacter(text.slice(index, index + width));
|
|
55
|
+
index += width - 1;
|
|
56
|
+
start = index + 1;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return start === 0 ? text : output + text.slice(start);
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const escapeRegex = (text: string): string => text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
|
63
|
+
|
|
64
|
+
export type WriteOptions = {
|
|
65
|
+
/** Namespaces to abbreviate IRIs with, by prefix; a later prefix for the same namespace replaces an earlier one. */
|
|
66
|
+
readonly prefixes?: Readonly<Record<string, string>>;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** Serializes quads as TriG, in the order given; consecutive quads that share a graph and subject are grouped. */
|
|
70
|
+
export const write = (quads: Iterable<Rdf.Quad>, { prefixes = {} }: WriteOptions = {}): string => {
|
|
71
|
+
const prefixByNamespace = new Map<string, string>();
|
|
72
|
+
let output = '';
|
|
73
|
+
for (const [prefix, namespace] of Object.entries(prefixes)) {
|
|
74
|
+
prefixByNamespace.set(namespace, `${prefix}:`);
|
|
75
|
+
output += `@prefix ${prefix}: <${namespace}>.\n`;
|
|
76
|
+
}
|
|
77
|
+
const hasPrefixes = prefixByNamespace.size > 0;
|
|
78
|
+
if (hasPrefixes) {
|
|
79
|
+
output += '\n';
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// An IRI in one of the namespaces followed by a valid local name; any other IRI keeps its angle brackets.
|
|
83
|
+
const prefixPattern = hasPrefixes
|
|
84
|
+
? new RegExp(`^(${[...prefixByNamespace.keys()].map(escapeRegex).join('|')})([_a-zA-Z0-9][\\-_a-zA-Z0-9]*)$`)
|
|
85
|
+
: undefined;
|
|
86
|
+
|
|
87
|
+
const iriOrBlank = (term: Rdf.Term): string => {
|
|
88
|
+
if (term.termType !== 'NamedNode') {
|
|
89
|
+
return `_:${term.value}`;
|
|
90
|
+
}
|
|
91
|
+
const iri = escape(term.value);
|
|
92
|
+
const match = prefixPattern?.exec(iri);
|
|
93
|
+
if (!match) {
|
|
94
|
+
return `<${iri}>`;
|
|
95
|
+
}
|
|
96
|
+
return `${prefixByNamespace.get(match[1])}${match[2]}`;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const literal = (term: Rdf.Literal): string => {
|
|
100
|
+
const value = escape(term.value);
|
|
101
|
+
if (term.language) {
|
|
102
|
+
return `"${value}"@${term.language}${term.direction ? `--${term.direction}` : ''}`;
|
|
103
|
+
}
|
|
104
|
+
switch (term.datatype.value) {
|
|
105
|
+
case `${XSD}string`:
|
|
106
|
+
return `"${value}"`;
|
|
107
|
+
case `${XSD}boolean`:
|
|
108
|
+
if (value === 'true' || value === 'false') {
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
break;
|
|
112
|
+
case `${XSD}integer`:
|
|
113
|
+
if (/^[+-]?\d+$/.test(value)) {
|
|
114
|
+
return value;
|
|
115
|
+
}
|
|
116
|
+
break;
|
|
117
|
+
case `${XSD}decimal`:
|
|
118
|
+
if (/^[+-]?\d*\.\d+$/.test(value)) {
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
break;
|
|
122
|
+
case `${XSD}double`:
|
|
123
|
+
if (/^[+-]?(?:\d+\.\d*|\.?\d+)[eE][+-]?\d+$/.test(value)) {
|
|
124
|
+
return value;
|
|
125
|
+
}
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
return `"${value}"^^${iriOrBlank(term.datatype)}`;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const object = (term: Rdf.QuadObject): string => (term.termType === 'Literal' ? literal(term) : iriOrBlank(term));
|
|
132
|
+
const predicate = (term: Rdf.QuadPredicate): string =>
|
|
133
|
+
term.termType === 'NamedNode' && term.value === Rdf.RDF_TYPE ? 'a' : iriOrBlank(term);
|
|
134
|
+
|
|
135
|
+
let graph: Rdf.QuadGraph = Rdf.defaultGraph();
|
|
136
|
+
let subject: Rdf.QuadSubject | undefined;
|
|
137
|
+
let lastPredicate: Rdf.QuadPredicate | undefined;
|
|
138
|
+
const closing = () => (graph.termType === 'DefaultGraph' ? '.\n' : '\n}\n');
|
|
139
|
+
|
|
140
|
+
for (const next of quads) {
|
|
141
|
+
for (const term of [next.subject, next.predicate, next.object, next.graph]) {
|
|
142
|
+
if (term.termType === 'Quad' || term.termType === 'Variable') {
|
|
143
|
+
throw new TypeError(
|
|
144
|
+
`TriG cannot write a ${term.termType === 'Quad' ? 'quoted triple' : 'variable'} as a term.`,
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (!next.graph.equals(graph)) {
|
|
149
|
+
output +=
|
|
150
|
+
(subject === undefined ? '' : closing()) +
|
|
151
|
+
(next.graph.termType === 'DefaultGraph' ? '' : `${iriOrBlank(next.graph)} {\n`);
|
|
152
|
+
graph = next.graph;
|
|
153
|
+
subject = undefined;
|
|
154
|
+
}
|
|
155
|
+
if (subject !== undefined && next.subject.equals(subject)) {
|
|
156
|
+
output +=
|
|
157
|
+
lastPredicate !== undefined && next.predicate.equals(lastPredicate)
|
|
158
|
+
? `, ${object(next.object)}`
|
|
159
|
+
: `;\n ${predicate(next.predicate)} ${object(next.object)}`;
|
|
160
|
+
} else {
|
|
161
|
+
output += `${subject === undefined ? '' : '.\n'}${iriOrBlank(next.subject)} ${predicate(next.predicate)} ${object(next.object)}`;
|
|
162
|
+
}
|
|
163
|
+
subject = next.subject;
|
|
164
|
+
lastPredicate = next.predicate;
|
|
165
|
+
}
|
|
166
|
+
if (subject !== undefined) {
|
|
167
|
+
output += closing();
|
|
168
|
+
}
|
|
169
|
+
return output;
|
|
170
|
+
};
|