-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathN3DataFactory.js
More file actions
394 lines (338 loc) · 11 KB
/
N3DataFactory.js
File metadata and controls
394 lines (338 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// N3.js implementations of the RDF/JS core data types
// See https://github.com/rdfjs/representation-task-force/blob/master/interface-spec.md
import namespaces from './IRIs';
const { rdf, xsd } = namespaces;
const DEFAULT_CONTEXT = { token: null };
// eslint-disable-next-line prefer-const
let DEFAULTGRAPH;
let _blankNodeCounter = 0;
const escapedLiteral = /^"(.*".*)(?="[^"]*$)/;
// ## DataFactory singleton
// Note: The default data factory does not set the token field of terms.
const DataFactory = {
namedNode: iri => namedNode(iri),
blankNode: name => blankNode(name),
variable: name => variable(name),
literal: (name, datatype) => literal(name, datatype),
defaultGraph,
quad,
triple: quad,
};
export default DataFactory;
// ## Term constructor
export class Term {
constructor(id, context = DEFAULT_CONTEXT) {
this.id = id;
this.context = context;
}
// ### The value of this term
get value() {
return this.id;
}
// ### Returns whether this object represents the same term as the other
equals(other) {
// If both terms were created by this library,
// equality can be computed through ids
if (other instanceof Term)
return this.id === other.id;
// Otherwise, compare term type and value
return !!other && this.termType === other.termType &&
this.value === other.value;
}
// ### Implement hashCode for Immutable.js, since we implement `equals`
// https://immutable-js.com/docs/v4.0.0/ValueObject/#hashCode()
hashCode() {
return 0;
}
// ### Returns a plain object representation of this term
toJSON() {
return {
termType: this.termType,
value: this.value,
};
}
}
// ## NamedNode constructor
export class NamedNode extends Term {
// ### The term type of this term
get termType() {
return 'NamedNode';
}
}
// ## Literal constructor
export class Literal extends Term {
// ### The term type of this term
get termType() {
return 'Literal';
}
// ### The text value of this literal
get value() {
return this.id.substring(1, this.id.lastIndexOf('"'));
}
// ### The language of this literal
get language() {
// Find the last quotation mark (e.g., '"abc"@en-us')
const id = this.id;
let atPos = id.lastIndexOf('"') + 1;
// If "@" it follows, return the remaining substring; empty otherwise
return atPos < id.length && id[atPos++] === '@' ? id.substr(atPos).toLowerCase() : '';
}
// ### The datatype IRI of this literal
get datatype() {
return new NamedNode(this.datatypeString);
}
// ### The datatype string of this literal
get datatypeString() {
// Find the last quotation mark (e.g., '"abc"^^http://ex.org/types#t')
const id = this.id, dtPos = id.lastIndexOf('"') + 1;
const char = dtPos < id.length ? id[dtPos] : '';
// If "^" it follows, return the remaining substring
return char === '^' ? id.substr(dtPos + 2) :
// If "@" follows, return rdf:langString; xsd:string otherwise
(char !== '@' ? xsd.string : rdf.langString);
}
// ### Returns whether this object represents the same term as the other
equals(other) {
// If both literals were created by this library,
// equality can be computed through ids
if (other instanceof Literal)
return this.id === other.id;
// Otherwise, compare term type, value, language, and datatype
return !!other && !!other.datatype &&
this.termType === other.termType &&
this.value === other.value &&
this.language === other.language &&
this.datatype.value === other.datatype.value;
}
toJSON() {
return {
termType: this.termType,
value: this.value,
language: this.language,
datatype: { termType: 'NamedNode', value: this.datatypeString },
};
}
}
// ## BlankNode constructor
export class BlankNode extends Term {
constructor(name, context = DEFAULT_CONTEXT) {
super(`_:${name}`, context);
}
// ### The term type of this term
get termType() {
return 'BlankNode';
}
// ### The name of this blank node
get value() {
return this.id.substr(2);
}
}
export class Variable extends Term {
constructor(name, context = DEFAULT_CONTEXT) {
super(`?${name}`, context);
}
// ### The term type of this term
get termType() {
return 'Variable';
}
// ### The name of this variable
get value() {
return this.id.substr(1);
}
}
// ## DefaultGraph constructor
export class DefaultGraph extends Term {
constructor() {
super('', DEFAULT_CONTEXT);
return DEFAULTGRAPH || this;
}
// ### The term type of this term
get termType() {
return 'DefaultGraph';
}
// ### Returns whether this object represents the same term as the other
equals(other) {
// If both terms were created by this library,
// equality can be computed through strict equality;
// otherwise, compare term types.
return (this === other) || (!!other && (this.termType === other.termType));
}
}
// ## DefaultGraph singleton
DEFAULTGRAPH = new DefaultGraph();
// ### Constructs a term from the given internal string ID
// The third 'nested' parameter of this function is to aid
// with recursion over nested terms. It should not be used
// by consumers of this library.
// See https://github.com/rdfjs/N3.js/pull/311#discussion_r1061042725
export function termFromId(id, factory, nested, token) {
factory = factory || DataFactory;
// Falsy value or empty string indicate the default graph
if (!id)
return factory.defaultGraph();
// Identify the term type based on the first character
switch (id[0]) {
case '?':
return factory.variable(id.substr(1));
case '_':
return factory.blankNode(id.substr(2));
case '"':
// Shortcut for internal literals
if (factory === DataFactory)
return new Literal(id, token);
// Literal without datatype or language
if (id[id.length - 1] === '"')
return factory.literal(id.substr(1, id.length - 2));
// Literal with datatype or language
const endPos = id.lastIndexOf('"', id.length - 1);
return factory.literal(id.substr(1, endPos - 1),
id[endPos + 1] === '@' ? id.substr(endPos + 2)
: factory.namedNode(id.substr(endPos + 3)));
case '[':
id = JSON.parse(id);
break;
default:
if (!nested || !Array.isArray(id)) {
return factory.namedNode(id);
}
}
return factory.quad(
termFromId(id[0], factory, true),
termFromId(id[1], factory, true),
termFromId(id[2], factory, true),
id[3] && termFromId(id[3], factory, true)
);
}
// ### Constructs an internal string ID from the given term or ID string
// The third 'nested' parameter of this function is to aid
// with recursion over nested terms. It should not be used
// by consumers of this library.
// See https://github.com/rdfjs/N3.js/pull/311#discussion_r1061042725
export function termToId(term, nested) {
if (typeof term === 'string')
return term;
if (term instanceof Term && term.termType !== 'Quad')
return term.id;
if (!term)
return DEFAULTGRAPH.id;
// Term instantiated with another library
switch (term.termType) {
case 'NamedNode': return term.value;
case 'BlankNode': return `_:${term.value}`;
case 'Variable': return `?${term.value}`;
case 'DefaultGraph': return '';
case 'Literal': return `"${term.value}"${
term.language ? `@${term.language}` :
(term.datatype && term.datatype.value !== xsd.string ? `^^${term.datatype.value}` : '')}`;
case 'Quad':
const res = [
termToId(term.subject, true),
termToId(term.predicate, true),
termToId(term.object, true),
];
if (term.graph && term.graph.termType !== 'DefaultGraph') {
res.push(termToId(term.graph, true));
}
return nested ? res : JSON.stringify(res);
default: throw new Error(`Unexpected termType: ${term.termType}`);
}
}
// ## Quad constructor
export class Quad extends Term {
constructor(subject, predicate, object, graph) {
super('', DEFAULT_CONTEXT);
this._subject = subject;
this._predicate = predicate;
this._object = object;
this._graph = graph || DEFAULTGRAPH;
}
// ### The term type of this term
get termType() {
return 'Quad';
}
get subject() {
return this._subject;
}
get predicate() {
return this._predicate;
}
get object() {
return this._object;
}
get graph() {
return this._graph;
}
// ### Returns a plain object representation of this quad
toJSON() {
return {
termType: this.termType,
subject: this._subject.toJSON(),
predicate: this._predicate.toJSON(),
object: this._object.toJSON(),
graph: this._graph.toJSON(),
};
}
// ### Returns whether this object represents the same quad as the other
equals(other) {
return !!other && this._subject.equals(other.subject) &&
this._predicate.equals(other.predicate) &&
this._object.equals(other.object) &&
this._graph.equals(other.graph);
}
}
export { Quad as Triple };
// ### Escapes the quotes within the given literal
export function escapeQuotes(id) {
return id.replace(escapedLiteral, (_, quoted) => `"${quoted.replace(/"/g, '""')}`);
}
// ### Unescapes the quotes within the given literal
export function unescapeQuotes(id) {
return id.replace(escapedLiteral, (_, quoted) => `"${quoted.replace(/""/g, '"')}`);
}
// ### Creates an IRI
export function namedNode(iri, context = DEFAULT_CONTEXT) {
return new NamedNode(iri, context);
}
// ### Creates a blank node
export function blankNode(name, context = DEFAULT_CONTEXT) {
return new BlankNode(name || `n3-${_blankNodeCounter++}`, context);
}
// ### Creates a literal
export function literal(value, languageOrDataType, context = DEFAULT_CONTEXT) {
// Create a language-tagged string
if (typeof languageOrDataType === 'string')
return new Literal(`"${value}"@${languageOrDataType.toLowerCase()}`, context);
// Automatically determine datatype for booleans and numbers
let datatype = languageOrDataType ? languageOrDataType.value : '';
if (datatype === '') {
// Convert a boolean
if (typeof value === 'boolean')
datatype = xsd.boolean;
// Convert an integer or double
else if (typeof value === 'number') {
if (Number.isFinite(value))
datatype = Number.isInteger(value) ? xsd.integer : xsd.double;
else {
datatype = xsd.double;
if (!Number.isNaN(value))
value = value > 0 ? 'INF' : '-INF';
}
}
}
// Create a datatyped literal
return (datatype === '' || datatype === xsd.string) ?
new Literal(`"${value}"`, context) :
new Literal(`"${value}"^^${datatype}`, context);
}
// ### Creates a variable
export function variable(name, context = DEFAULT_CONTEXT) {
return new Variable(name, context);
}
// ### Returns the default graph
function defaultGraph() {
return DEFAULTGRAPH;
}
// ### Creates a quad
function quad(subject, predicate, object, graph) {
return new Quad(subject, predicate, object, graph);
}