forked from shexjs/shex.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshex-term.js
306 lines (277 loc) · 10.4 KB
/
shex-term.js
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
/**
*
* isIRI, isBlank, getLiteralType, getLiteralValue
*/
const ShExTermCjsModule = (function () {
const absoluteIRI = /^[a-z][a-z0-9+.-]*:/i,
schemeAuthority = /^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i,
dotSegments = /(?:^|\/)\.\.?(?:$|[\/#?])/;
const RdfLangString = "http://www.w3.org/1999/02/22-rdf-syntax-ns#langString";
const XsdString = "http://www.w3.org/2001/XMLSchema#string";
// N3.js:lib/N3Parser.js<0.4.5>:576 with
// s/this\./Parser./g
// s/token/iri/
// ### `_resolveIRI` resolves a relative IRI token against the base path,
// assuming that a base path has been set and that the IRI is indeed relative.
function resolveRelativeIRI (base, iri) {
if (absoluteIRI.test(iri))
return iri
switch (iri[0]) {
// An empty relative IRI indicates the base IRI
case undefined: return base;
// Resolve relative fragment IRIs against the base IRI
case '#': return base + iri;
// Resolve relative query string IRIs by replacing the query string
case '?': return base.replace(/(?:\?.*)?$/, iri);
// Resolve root-relative IRIs at the root of the base IRI
case '/':
let m = base.match(schemeAuthority);
// Resolve scheme-relative IRIs to the scheme
return (iri[1] === '/' ? m[1] : m[0]) + _removeDotSegments(iri);
// Resolve all other IRIs at the base IRI's path
default: {
return _removeDotSegments(base.replace(/[^\/?]*(?:\?.*)?$/, '') + iri);
}
}
}
// ### `_removeDotSegments` resolves './' and '../' path segments in an IRI as per RFC3986.
function _removeDotSegments (iri) {
// Don't modify the IRI if it does not contain any dot segments
if (!dotSegments.test(iri))
return iri;
// Start with an imaginary slash before the IRI in order to resolve trailing './' and '../'
const result = '', length = iri.length, i = -1, pathStart = -1, segmentStart = 0, next = '/';
while (i < length) {
switch (next) {
// The path starts with the first slash after the authority
case ':':
if (pathStart < 0) {
// Skip two slashes before the authority
if (iri[++i] === '/' && iri[++i] === '/')
// Skip to slash after the authority
while ((pathStart = i + 1) < length && iri[pathStart] !== '/')
i = pathStart;
}
break;
// Don't modify a query string or fragment
case '?':
case '#':
i = length;
break;
// Handle '/.' or '/..' path segments
case '/':
if (iri[i + 1] === '.') {
next = iri[++i + 1];
switch (next) {
// Remove a '/.' segment
case '/':
result += iri.substring(segmentStart, i - 1);
segmentStart = i + 1;
break;
// Remove a trailing '/.' segment
case undefined:
case '?':
case '#':
return result + iri.substring(segmentStart, i) + iri.substr(i + 1);
// Remove a '/..' segment
case '.':
next = iri[++i + 1];
if (next === undefined || next === '/' || next === '?' || next === '#') {
result += iri.substring(segmentStart, i - 2);
// Try to remove the parent path from result
if ((segmentStart = result.lastIndexOf('/')) >= pathStart)
result = result.substr(0, segmentStart);
// Remove a trailing '/..' segment
if (next !== '/')
return result + '/' + iri.substr(i + 1);
segmentStart = i + 1;
}
}
}
}
next = iri[++i];
}
return result + iri.substring(segmentStart);
}
function internalTerm (node) { // !!rdfjsTermToInternal
switch (node.termType) {
case ("NamedNode"):
return node.value;
case ("BlankNode"):
return "_:" + node.value;
case ("Literal"):
return "\"" + node.value + "\"" + (
node.datatypeString === RdfLangString
? "@" + node.language
: node.datatypeString === XsdString
? ""
: "^^" + node.datatypeString
);
default: throw Error("unknown RDFJS node type: " + JSON.stringify(node))
}
}
function internalTriple (triple) { // !!rdfjsTripleToInternal
return {
subject: internalTerm(triple.subject),
predicate: internalTerm(triple.predicate),
object: internalTerm(triple.object)
};
}
function externalTerm (node, factory) { // !!intermalTermToRdfjs
if (isIRI(node)) {
return factory.namedNode(node);
} else if (isBlank(node)) {
return factory.blankNode(node.substr(2));
} else if (isLiteral(node)) {
let dtOrLang = getLiteralLanguage(node) ||
(getLiteralType(node) === XsdString
? null // seems to screw up N3.js
: factory.namedNode(getLiteralType(node)))
return factory.literal(getLiteralValue(node), dtOrLang)
} else {
throw Error("Unknown internal term type: " + JSON.stringify(node));
}
}
function externalTriple (triple, factory) { // !!rename internalTripleToRdjs
return factory.quad(
externalTerm(triple.subject, factory),
externalTerm(triple.predicate, factory),
externalTerm(triple.object, factory)
);
}
function intermalTermToTurtle (node, base, prefixes) {
if (isIRI(node)) {
// if (node === RDF_TYPE) // only valid in Turtle predicates
// return "a";
// Escape special characters
if (escape.test(node))
node = node.replace(escapeAll, characterReplacer);
const pref = Object.keys(prefixes).find(pref => node.startsWith(prefixes[pref]));
if (pref) {
const rest = node.substr(prefixes[pref].length);
if (rest.indexOf("\\") === -1) // could also say no more than n of these: [...]
return pref + ":" + rest.replace(/([~!$&'()*+,;=/?#@%])/g, '\\' + "$1");
}
if (node.startsWith(base)) {
return "<" + node.substr(base.length) + ">";
} else {
return "<" + node + ">";
}
} else if (isBlank(node)) {
return node;
} else if (isLiteral(node)) {
const value = getLiteralValue(node);
const type = getLiteralType(node);
const language = getLiteralLanguage(node);
// Escape special characters
if (escape.test(value))
value = value.replace(escapeAll, characterReplacer);
// Write the literal, possibly with type or language
if (language)
return '"' + value + '"@' + language;
else if (type && type !== "http://www.w3.org/2001/XMLSchema#string")
return '"' + value + '"^^' + this.intermalTermToTurtle(type, base, prefixes);
else
return '"' + value + '"';
} else {
throw Error("Unknown internal term type: " + JSON.stringify(node));
}
}
// Tests whether the given entity (triple object) represents an IRI in the N3 library
function isIRI (entity) {
if (typeof entity !== 'string')
return false;
else if (entity.length === 0)
return true;
else {
const firstChar = entity[0];
return firstChar !== '"' && firstChar !== '_';
}
}
// Tests whether the given entity (triple object) represents a literal in the N3 library
function isLiteral (entity) {
return typeof entity === 'string' && entity[0] === '"';
}
// Tests whether the given entity (triple object) represents a blank node in the N3 library
function isBlank (entity) {
return typeof entity === 'string' && entity.substr(0, 2) === '_:';
}
// Tests whether the given entity represents the default graph
function isDefaultGraph (entity) {
return !entity;
}
// Tests whether the given triple is in the default graph
function inDefaultGraph (triple) {
return !triple.graph;
}
// Gets the string value of a literal in the N3 library
function getLiteralValue (literal) {
const match = /^"([^]*)"/.exec(literal);
if (!match)
throw new Error(literal + ' is not a literal');
return match[1];
}
// Gets the type of a literal in the N3 library
function getLiteralType (literal) {
const match = /^"[^]*"(?:\^\^([^"]+)|(@)[^@"]+)?$/.exec(literal);
if (!match)
throw new Error(literal + ' is not a literal');
return match[1] || (match[2] ? RdfLangString : XsdString);
}
// Gets the language of a literal in the N3 library
function getLiteralLanguage (literal) {
const match = /^"[^]*"(?:@([^@"]+)|\^\^[^"]+)?$/.exec(literal);
if (!match)
throw new Error(literal + ' is not a literal');
return match[1] ? match[1].toLowerCase() : '';
}
// rdf:type predicate (for 'a' abbreviation)
const RDF_PREFIX = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
RDF_TYPE = RDF_PREFIX + 'type';
// Characters in literals that require escaping
const escape = /["\\\t\n\r\b\f\u0000-\u0019\ud800-\udbff]/,
escapeAll = /["\\\t\n\r\b\f\u0000-\u0019]|[\ud800-\udbff][\udc00-\udfff]/g,
escapeReplacements = {
'\\': '\\\\', '"': '\\"', '\t': '\\t',
'\n': '\\n', '\r': '\\r', '\b': '\\b', '\f': '\\f',
};
// Replaces a character by its escaped version
function characterReplacer (character) {
// Replace a single character by its escaped version
const result = escapeReplacements[character];
if (result === undefined) {
// Replace a single character with its 4-bit unicode escape sequence
if (character.length === 1) {
result = character.charCodeAt(0).toString(16);
result = '\\u0000'.substr(0, 6 - result.length) + result;
}
// Replace a surrogate pair with its 8-bit unicode escape sequence
else {
result = ((character.charCodeAt(0) - 0xD800) * 0x400 +
character.charCodeAt(1) + 0x2400).toString(16);
result = '\\U00000000'.substr(0, 10 - result.length) + result;
}
}
return result;
}
return {
RdfLangString: RdfLangString,
XsdString: XsdString,
resolveRelativeIRI: resolveRelativeIRI,
isIRI: isIRI,
isLiteral: isLiteral,
isBlank: isBlank,
isDefaultGraph: isDefaultGraph,
inDefaultGraph: inDefaultGraph,
getLiteralValue: getLiteralValue,
getLiteralType: getLiteralType,
getLiteralLanguage: getLiteralLanguage,
internalTerm: internalTerm,
internalTriple: internalTriple,
externalTerm: externalTerm,
externalTriple: externalTriple,
intermalTermToTurtle: intermalTermToTurtle,
}
})();
if (typeof require !== 'undefined' && typeof exports !== 'undefined')
module.exports = ShExTermCjsModule; // node environment