rdflib 2.2.21-d633bed7 → 2.2.21-e3e59ee9

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/lib/serializer.js CHANGED
@@ -14,7 +14,6 @@ var Util = _interopRequireWildcard(require("./utils-js"));
14
14
  var _canonicalDataFactory = _interopRequireDefault(require("./factories/canonical-data-factory"));
15
15
  var _xsd = require("./xsd");
16
16
  var _solidNamespace = _interopRequireDefault(require("solid-namespace"));
17
- var jsonld = _interopRequireWildcard(require("jsonld"));
18
17
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
19
18
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
20
19
  /* Serialization of RDF Graphs
@@ -974,138 +973,6 @@ class Serializer {
974
973
  var tree2 = [str, tree, '</rdf:RDF>']; // @@ namespace declrations
975
974
  return XMLtreeToString(tree2, -1);
976
975
  } // End @@ body
977
-
978
- statementsToJsonld(sts) {
979
- // TODO
980
- // - make relative with @id: '' in replacing fist @id
981
- // - shall I use @type ?
982
- /* for (var ns in this.prefixes) {
983
- if (!this.prefixes.hasOwnProperty(ns)) continue
984
- if (!this.namespacesUsed[ns]) continue
985
- // str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) +
986
- // '.\n'
987
- context += `"${this.prefixes[ns]}": "${this.explicitURI(ns)}",`
988
- } */
989
-
990
- async function toJsonld(item, context, base) {
991
- function makeRelative(jsonldString) {
992
- /* let j = base.indexOf("#") // cut before #
993
- if (j < 0 ) {
994
- j = base.length // base.lastIndexOf('/') + 1 // cut after /
995
- } */
996
- // console.log('Alain base ' + base + ' ' + base.slice(0, j))
997
- if (base.includes('#')) throw new Error(`${base} must be an URL, it is an URI`);
998
- const id = '"@id": "'; // find URI
999
- const regex = new RegExp(id + base, 'g'); // .slice(0, j), 'g')
1000
- let result,
1001
- indices = [];
1002
- // store indices at begin and end of URI
1003
- while (result = regex.exec(jsonldString)) {
1004
- indices.push(result.index + id.length);
1005
- indices.push(jsonldString.indexOf('"', result.index + id.length));
1006
- }
1007
- for (let i = indices.length - 2; i >= 0; i = i - 2) {
1008
- const idUri = jsonldString.substring(indices[i], indices[i + 1]);
1009
- jsonldString = jsonldString.replace(idUri, Uri.refTo(base, idUri));
1010
- }
1011
- return jsonldString; // .replace(regex, id)
1012
- }
1013
- // console.log(context)
1014
- let jsonldContext = JSON.parse(context);
1015
- /* console.log('alain ' + base)
1016
- let j = base.indexOf("#")
1017
- if (j < 0 ) {
1018
- j = base.lastIndexOf('/')
1019
- }
1020
- console.log(base.slice(0, j))
1021
- const regex = new RegExp(base.slice(0, j), 'g') // alain
1022
- // const regex = new RegExp('http://localhost/t1.ttl', 'g') */
1023
- return jsonld.fromRDF(item, {
1024
- format: 'application/n-quads'
1025
- }).then(n3String => {
1026
- return jsonld.compact(n3String, jsonldContext);
1027
- })
1028
- // TODO add collections, compact do not do it ??
1029
- .then(jsonldObj => {
1030
- return JSON.stringify(jsonldObj, null, 2);
1031
- }) // format jsonld
1032
- .then(jsonldString => {
1033
- return makeRelative(jsonldString);
1034
- }).catch(e => {
1035
- throw e;
1036
- });
1037
- }
1038
- function contextMethod(n3String) {
1039
- let prefixes = new Set();
1040
- const regex = /<(.*?)>/g;
1041
- n3String.match(regex).map(string => {
1042
- const uri = string.slice(1).slice(0, -1);
1043
- console.log(this.base + ' ' + this.base);
1044
- if (uri.includes('//') && (!this.base || !uri.includes(this.base))) prefixes.add(addPrefix(uri));
1045
- });
1046
- let context = `{ `;
1047
- const test = [...prefixes].map(term => {
1048
- context += `${term},`;
1049
- });
1050
- /* console.log(this.prefixes)
1051
- let str = ''
1052
- console.log(this.namespacesUsed)
1053
- for (var ns in this.prefixes) {
1054
- if (!this.prefixes.hasOwnProperty(ns)) continue
1055
- if (!this.namespacesUsed[ns]) continue
1056
- str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) + '.\n'
1057
- // context += `"${this.prefixes[ns]}": "${this.explicitURI(ns)}",`
1058
- }
1059
- console.log('alain string ' +str)
1060
- */
1061
- return context.slice(0, -1) + `}`;
1062
- }
1063
- function addPrefixMethod(uri) {
1064
- var j = uri.indexOf('#');
1065
- if (j < 0) {
1066
- j = uri.lastIndexOf('/');
1067
- }
1068
- if (j >= 0 && (
1069
- // Can split at namespace but only if http[s]: URI or file: or ws[s] (why not others?)
1070
- uri.indexOf('http') === 0 || uri.indexOf('ws') === 0 || uri.indexOf('file') === 0)) {
1071
- var canSplit = true;
1072
- for (var k = j + 1; k < uri.length; k++) {
1073
- if (this._notNameChars.indexOf(uri[k]) >= 0) {
1074
- canSplit = false;
1075
- break;
1076
- }
1077
- }
1078
- if (canSplit) {
1079
- var localid = uri.slice(j + 1);
1080
- var namesp = uri.slice(0, j + 1);
1081
- /*if (this.defaultNamespace && this.defaultNamespace === namesp &&
1082
- this.flags.indexOf('d') < 0) { // d -> suppress default
1083
- if (this.flags.indexOf('k') >= 0 &&
1084
- this.keyords.indexOf(localid) < 0) {
1085
- return localid
1086
- }
1087
- return ':' + localid
1088
- } */
1089
- // this.checkIntegrity() // @@@ Remove when not testing
1090
- var prefix = this.prefixes[namesp];
1091
- if (!prefix) prefix = this.makeUpPrefix(namesp);
1092
- if (prefix) {
1093
- console.log(`Alain "${prefix}": "${namesp}"`);
1094
- return `"${prefix}": "${namesp}"`;
1095
- }
1096
- }
1097
- }
1098
- }
1099
- // return this.explicitURI(uri)
1100
- // }
1101
- var addPrefix = addPrefixMethod.bind(this);
1102
- var context = contextMethod.bind(this);
1103
- const n3String = this.statementsToNTriples(sts);
1104
- // console.log(n3String)
1105
- let contextString = context(n3String);
1106
- // console.log(this.namespacesUsed)
1107
- return toJsonld(n3String, contextString, this.base);
1108
- }
1109
976
  }
1110
977
 
1111
978
  // String escaping utilities
package/lib/store.d.ts CHANGED
@@ -299,5 +299,5 @@ export default class IndexedFormula extends Formula {
299
299
  * @param term
300
300
  */
301
301
  uris(term: Quad_Subject): string[];
302
- serialize(base: any, contentType: any, provenance: any, options?: any): string | Promise<string> | undefined;
302
+ serialize(base: any, contentType: any, provenance: any, options?: any): string | undefined;
303
303
  }
package/lib/store.js CHANGED
@@ -1045,12 +1045,11 @@ class IndexedFormula extends _formula.default {
1045
1045
  return res;
1046
1046
  }
1047
1047
  serialize(base, contentType, provenance, options) {
1048
- var _options;
1049
1048
  // override Formula.serialize to force the serializer namespace prefixes
1050
1049
  // to those of this IndexedFormula
1051
1050
 
1052
1051
  // if namespaces are explicitly passed in options, let them override the existing namespaces in this formula
1053
- const namespaces = (_options = options) !== null && _options !== void 0 && _options.namespaces ? {
1052
+ const namespaces = options?.namespaces ? {
1054
1053
  ...this.namespaces,
1055
1054
  ...options.namespaces
1056
1055
  } : {
@@ -51,7 +51,7 @@ export default class UpdateManager {
51
51
  * Returns a list of all bnodes occurring in a list of statements
52
52
  * @private
53
53
  */
54
- statementArrayBnodes(sts: Quad[]): BlankNode[];
54
+ statementArrayBnodes(sts: ReadonlyArray<Quad>): BlankNode[];
55
55
  /**
56
56
  * Makes a cached list of [Inverse-]Functional properties
57
57
  * @private
@@ -685,6 +685,11 @@ class UpdateManager {
685
685
  // console.log(message)
686
686
  throw new Error(message);
687
687
  }
688
+ if (doc.termType !== 'NamedNode') {
689
+ let message = 'Error patching: document not a NamedNode:' + ds[0] + ', ' + is[0];
690
+ // console.log(message)
691
+ throw new Error(message);
692
+ }
688
693
  var control = this.patchControlFor(doc);
689
694
  var startTime = Date.now();
690
695
  var props = ['subject', 'predicate', 'object', 'why'];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "rdflib",
3
3
  "description": "an RDF library for node.js. Suitable for client and server side.",
4
- "version": "2.2.21-d633bed7",
4
+ "version": "2.2.21-e3e59ee9",
5
5
  "private": false,
6
6
  "browserslist": [
7
7
  "> 0.5%"
@@ -46,6 +46,7 @@
46
46
  "dependencies": {
47
47
  "@babel/runtime": "^7.20.1",
48
48
  "@xmldom/xmldom": "^0.8.6",
49
+ "async": "^3.2.4",
49
50
  "cross-fetch": "^3.1.5",
50
51
  "jsonld": "^8.1.0",
51
52
  "n3": "^1.16.3",
@@ -91,7 +92,7 @@
91
92
  "build:esm": "babel src --extensions \".ts,.js\" --env-name esm -d esm",
92
93
  "build:browser": "webpack --progress",
93
94
  "build:types": "tsc --emitDeclarationOnly -d --moduleResolution node --declarationDir lib",
94
- "build:all": "npm run build && npm run build:types && npm run build:browser && npm run build:esm ",
95
+ "build:all": "npm run build && npm run build:types && npm run build:browser && npm run build:esm",
95
96
  "doc": "typedoc --out ./doc ./src/index.ts --excludePrivate --excludeInternal --tsconfig ./tsconfig.json",
96
97
  "ignore:prepublishOnly": "npm ci && npm run build:all && npm run doc && npm run test",
97
98
  "postversion": "git push --follow-tags",
@@ -99,7 +100,7 @@
99
100
  "test": "npm run test:unit && npm run test:serialize && npm run test:types",
100
101
  "test:clean": "rimraf tests/serialize/,*",
101
102
  "test:serialize": "npm run build && npm run test:serialize:all && npm run test:clean",
102
- "test:serialize:all": "npm run test:serialize:1 && npm run test:serialize:2 && npm run test:serialize:3 && npm run test:serialize:4 && npm run test:serialize:5 && npm run test:serialize:6 && npm run test:serialize:7 && npm run test:serialize:8 && npm run test:serialize:9 ; npm run test:serialize:10 && npm run test:serialize:11 && npm run test:serialize:12 && npm run test:serialize:13 && npm run test:serialize:14 && npm run test:serialize:16 ; npm run test:serialize:15",
103
+ "test:serialize:all": "npm run test:serialize:1 && npm run test:serialize:2 && npm run test:serialize:3 && npm run test:serialize:4 && npm run test:serialize:5 && npm run test:serialize:6 && npm run test:serialize:7 && npm run test:serialize:10 && npm run test:serialize:11 && npm run test:serialize:12 && npm run test:serialize:13 && npm run test:serialize:14 && npm run test:serialize:15",
103
104
  "test:serialize:1": "cd ./tests/serialize && node ./data.js -in=t1.ttl -format=application/rdf+xml -out=,t1.xml && fs-grep http://www.w3.org/2001/XMLSchema#integer ,t1.xml",
104
105
  "test:serialize:2": "cd ./tests/serialize && node ./data.js -in=t2.ttl -format=application/rdf+xml -out=,t2.xml && node diff ,t2.xml t2-ref.xml",
105
106
  "test:serialize:3": "cd ./tests/serialize && node ./data.js -in=t3.ttl -format=application/rdf+xml -out=,t3.xml && node diff ,t3.xml t3-ref.xml",
@@ -107,15 +108,14 @@
107
108
  "test:serialize:5": "cd ./tests/serialize && node ./data.js -in=t5.n3 -format=text/turtle -out=,t5.ttl && node diff ,t5.ttl t5-ref.ttl",
108
109
  "test:serialize:6": "cd ./tests/serialize && node ./data.js -in=t5.n3 -format=text/n3 -out=,t6.n3 && node diff ,t6.n3 t6-ref.n3",
109
110
  "test:serialize:7": "cd ./tests/serialize && node ./data.js -in=t7.n3 -format=application/n-triples -out=,t7.nt && node diff ,t7.nt t7-ref.nt",
110
- "test:serialize:8": "cd ./tests/serialize && node ./data.js -in=t5.n3 -format=application/n-quads -out=,t8.nq && node diff ,t8.nq t8-ref.nq",
111
- "test:serialize:9": "cd ./tests/serialize && node ./data.js -in=t7.n3 -format=application/ld+json -out=,t9.jsonld && node diff ,t9.jsonld t9-ref.jsonld",
111
+ "test:serialize:8": "cd ./tests/serialize && node ./data.js -in=t5.n3 -format=application/n-quads -dump=,t8.nq && node diff ,t8.nq t8-ref.nq",
112
+ "test:serialize:9": "cd ./tests/serialize && node ./data.js -in=t7.n3 -format=application/ld+json -out=,t9.json && node diff ,t9.json t9-ref.json",
112
113
  "test:serialize:10": "cd ./tests/serialize && node ./data.js -in=details.ttl -format=text/turtle -out=,t10.ttl && node diff ,t10.ttl t10-ref.ttl",
113
114
  "test:serialize:11": "cd ./tests/serialize && node ./data.js -in=structures.n3 -format=application/rdf+xml -out=,structures.xml && node diff ,structures.xml t11-ref.xml",
114
115
  "test:serialize:12": "cd ./tests/serialize && node ./data.js -in=structures.n3 -format=text/turtle -out=,structures.ttl && node diff ,structures.ttl t12-ref.ttl",
115
116
  "test:serialize:13": "cd ./tests/serialize && node ./data.js -in=structures.n3 -format=application/n-triples -out=,structures.nt && node ./data.js -format=application/n-triples -in=,structures.nt -format=text/turtle -out=,structures.nt.ttl && node diff ,structures.nt.ttl t13-ref.ttl",
116
117
  "test:serialize:14": "cd ./tests/serialize && node ./data.js -in=t14.html -format=text/turtle -out=,t14.ttl && node diff ,t14.ttl t14-ref.ttl",
117
118
  "test:serialize:15": "cd ./tests/serialize && node ./data.js -in=t15.html -format=text/turtle -out=,t15.ttl && node diff ,t15.ttl t15-ref.ttl",
118
- "test:serialize:16": "cd ./tests/serialize && node ./data.js -in=t1.ttl -format=application/ld+json -out=,t16.jsonld && node diff ,t16.jsonld t16-ref.jsonld",
119
119
  "test:types": "tsc --noEmit --target es2019 --moduleResolution node tests/types/*.ts",
120
120
  "test:unit": "mocha --growl --require ./tests/babel-register.js tests/unit/**-test.*",
121
121
  "test:unit:egp": "mocha --require ./tests/babel-register.js tests/unit/fetcher-egp-test.js",
package/src/convert.js ADDED
@@ -0,0 +1,70 @@
1
+ import asyncLib from 'async' // @@ Goal: remove this dependency
2
+ import jsonld from 'jsonld'
3
+ import { Parser, Writer } from 'n3' // @@ Goal: remove this dependency
4
+
5
+ export function convertToJson (n3String, jsonCallback) {
6
+ var jsonString
7
+ var n3Parser = new Parser()
8
+ var n3Writer = new Writer({
9
+ format: 'N-Quads'
10
+ })
11
+ asyncLib.waterfall([
12
+ function (callback) {
13
+ n3Parser.parse(n3String, function (error, quad, prefixes) {
14
+ if (error) {
15
+ callback(error);
16
+ } else if (quad !== null) {
17
+ n3Writer.addQuad(quad);
18
+ } else {
19
+ n3Writer.end(callback);
20
+ }
21
+ });
22
+ },
23
+ function (result, callback) {
24
+ try {
25
+ jsonld.fromRDF(result, {
26
+ format: 'application/nquads'
27
+ }).then((result) => {
28
+ callback(null, result)
29
+ })
30
+ } catch (err) {
31
+ callback(err)
32
+ }
33
+ },
34
+ function (json, callback) {
35
+ jsonString = JSON.stringify(json)
36
+ jsonCallback(null, jsonString)
37
+ }
38
+ ], function (err, result) {
39
+ jsonCallback(err, jsonString)
40
+ }
41
+ )
42
+ }
43
+
44
+ export function convertToNQuads (n3String, nquadCallback) {
45
+ var nquadString
46
+ var n3Parser = new Parser()
47
+ var n3Writer = new Writer({
48
+ format: 'N-Quads'
49
+ })
50
+ asyncLib.waterfall([
51
+ function (callback) {
52
+ n3Parser.parse(n3String, function (error, triple, prefixes) {
53
+ if (error) {
54
+ callback(error);
55
+ } else if (quad !== null) {
56
+ n3Writer.addQuad(quad);
57
+ } else {
58
+ n3Writer.end(callback);
59
+ }
60
+ });
61
+ },
62
+ function (result, callback) {
63
+ nquadString = result
64
+ nquadCallback(null, nquadString)
65
+ }
66
+ ], function (err, result) {
67
+ nquadCallback(err, nquadString)
68
+ }
69
+ )
70
+ }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ import { IRDFlibDataFactory } from './types'
2
2
 
3
3
  import BlankNode from './blank-node'
4
4
  import Collection from './collection'
5
+ import * as convert from './convert'
5
6
  import Empty from './empty'
6
7
  import Fetcher from './fetcher'
7
8
  import Formula from './formula'
@@ -65,6 +66,7 @@ export type { AutoInitOptions, ExtendedResponse, FetchError } from './fetcher'
65
66
  export {
66
67
  BlankNode,
67
68
  Collection,
69
+ convert,
68
70
  DataFactory,
69
71
  Empty,
70
72
  Fetcher,
@@ -22,7 +22,7 @@ export function jsonldObjectToTerm (kb, obj) {
22
22
  }
23
23
 
24
24
  if (Object.prototype.hasOwnProperty.call(obj, '@id')) {
25
- return nodeType(kb, obj)
25
+ return kb.rdfFactory.namedNode(obj['@id'])
26
26
  }
27
27
 
28
28
  if (Object.prototype.hasOwnProperty.call(obj, '@language')) {
@@ -44,7 +44,7 @@ export function jsonldObjectToTerm (kb, obj) {
44
44
  * Adds the statements in a json-ld list object to {kb}.
45
45
  */
46
46
  function listToStatements (kb, obj) {
47
- const listId = obj['@id'] ? nodeType(kb, obj) : kb.rdfFactory.blankNode()
47
+ const listId = obj['@id'] ? kb.rdfFactory.namedNode(obj['@id']) : kb.rdfFactory.blankNode()
48
48
 
49
49
  const items = obj['@list'].map((listItem => jsonldObjectToTerm(kb, listItem)))
50
50
  const statements = arrayToStatements(kb.rdfFactory, listId, items)
@@ -82,19 +82,10 @@ export default function jsonldParser (str, kb, base, callback) {
82
82
  .catch(callback)
83
83
  }
84
84
 
85
- function nodeType (kb, obj) {
86
- if (obj['@id'].startsWith('_:')) {
87
- // This object is a Blank Node.. pass the id without the preceding _:
88
- return kb.rdfFactory.blankNode(obj['@id'].substring(2));
89
- } else {
90
- // This object is a Named Node
91
- return kb.rdfFactory.namedNode(obj['@id']);
92
- }
93
- }
94
85
 
95
86
  function processResource(kb, base, flatResource) {
96
87
  const id = flatResource['@id']
97
- ? nodeType(kb, flatResource)
88
+ ? kb.rdfFactory.namedNode(flatResource['@id'])
98
89
  : kb.rdfFactory.blankNode()
99
90
 
100
91
  for (const property of Object.keys(flatResource)) {
@@ -145,4 +136,4 @@ function createStatement(kb, id, property, value, base) {
145
136
  object = jsonldObjectToTerm(kb, value)
146
137
  }
147
138
  return kb.rdfFactory.quad(id, predicate, object, kb.rdfFactory.namedNode(base))
148
- }
139
+ }
package/src/serialize.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import * as convert from './convert'
1
2
  import Formula from './formula'
2
3
  import Serializer from './serializer'
3
4
  import {
@@ -41,7 +42,7 @@ export default function serialize (
41
42
  */
42
43
  namespaces?: Record<string, string>
43
44
  }
44
- ): string | undefined | Promise<string> {
45
+ ): string | undefined {
45
46
  base = base || target?.value
46
47
  const opts = options || {}
47
48
  contentType = contentType || TurtleContentType // text/n3 if complex?
@@ -50,6 +51,7 @@ export default function serialize (
50
51
  var sz = Serializer(kb)
51
52
  if ((opts as any).flags) sz.setFlags((opts as any).flags)
52
53
  var newSts = kb!.statementsMatching(undefined, undefined, undefined, target as NamedNode)
54
+ var n3String: string
53
55
 
54
56
  // If an IndexedFormula, use the namespaces from the given graph as suggestions
55
57
  if ('namespaces' in kb) {
@@ -81,12 +83,18 @@ export default function serialize (
81
83
  return executeCallback(null, documentString)
82
84
  case JSONLDContentType:
83
85
  sz.setFlags('deinprstux') // Use adapters to connect to incmpatible parser
84
- return sz.statementsToJsonld(newSts)
86
+ n3String = sz.statementsToNTriples(newSts)
87
+ // n3String = sz.statementsToN3(newSts)
88
+ convert.convertToJson(n3String, callback)
89
+ break
85
90
  case NQuadsContentType:
86
91
  case NQuadsAltContentType: // @@@ just outpout the quads? Does not work for collections
87
92
  sz.setFlags('deinprstux q') // Suppress nice parts of N3 to make ntriples
88
93
  documentString = sz.statementsToNTriples(newSts) // q in flag means actually quads
89
94
  return executeCallback(null, documentString)
95
+ // n3String = sz.statementsToN3(newSts)
96
+ // documentString = convert.convertToNQuads(n3String, callback)
97
+ // break
90
98
  default:
91
99
  throw new Error('Serialize: Content-type ' + contentType + ' not supported for data write.')
92
100
  }
package/src/serializer.js CHANGED
@@ -12,7 +12,6 @@ import * as Util from './utils-js'
12
12
  import CanonicalDataFactory from './factories/canonical-data-factory'
13
13
  import { createXSD } from './xsd'
14
14
  import solidNs from 'solid-namespace'
15
- import * as jsonld from 'jsonld'
16
15
 
17
16
 
18
17
  export default function createSerializer(store) {
@@ -1012,131 +1011,6 @@ export class Serializer {
1012
1011
  var tree2 = [str, tree, '</rdf:RDF>'] // @@ namespace declrations
1013
1012
  return XMLtreeToString(tree2, -1)
1014
1013
  } // End @@ body
1015
-
1016
- statementsToJsonld (sts) {
1017
- // TODO
1018
- // - make relative with @id: '' in replacing fist @id
1019
- // - shall I use @type ?
1020
- /* for (var ns in this.prefixes) {
1021
- if (!this.prefixes.hasOwnProperty(ns)) continue
1022
- if (!this.namespacesUsed[ns]) continue
1023
- // str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) +
1024
- // '.\n'
1025
- context += `"${this.prefixes[ns]}": "${this.explicitURI(ns)}",`
1026
- } */
1027
-
1028
- async function toJsonld (item, context, base ) {
1029
- function makeRelative(jsonldString) {
1030
- /* let j = base.indexOf("#") // cut before #
1031
- if (j < 0 ) {
1032
- j = base.length // base.lastIndexOf('/') + 1 // cut after /
1033
- } */
1034
- // console.log('Alain base ' + base + ' ' + base.slice(0, j))
1035
- if (base.includes('#')) throw new Error(`${base} must be an URL, it is an URI`)
1036
- const id = '"@id": "' // find URI
1037
- const regex = new RegExp(id + base, 'g') // .slice(0, j), 'g')
1038
- let result, indices = [];
1039
- // store indices at begin and end of URI
1040
- while ( (result = regex.exec(jsonldString)) ) {
1041
- indices.push(result.index + id.length);
1042
- indices.push(jsonldString.indexOf('"', result.index + id.length ))
1043
- }
1044
- for (let i = indices.length - 2; i >= 0; i = i - 2) {
1045
- const idUri = jsonldString.substring(indices[i], indices[i + 1])
1046
- jsonldString = jsonldString.replace(idUri, Uri.refTo(base, idUri))
1047
- }
1048
-
1049
- return jsonldString // .replace(regex, id)
1050
- }
1051
- // console.log(context)
1052
- let jsonldContext = JSON.parse(context)
1053
- /* console.log('alain ' + base)
1054
- let j = base.indexOf("#")
1055
- if (j < 0 ) {
1056
- j = base.lastIndexOf('/')
1057
- }
1058
- console.log(base.slice(0, j))
1059
- const regex = new RegExp(base.slice(0, j), 'g') // alain
1060
- // const regex = new RegExp('http://localhost/t1.ttl', 'g') */
1061
- return jsonld.fromRDF(item, {format: 'application/n-quads'})
1062
- .then( n3String => { return jsonld.compact(n3String, jsonldContext) })
1063
- // TODO add collections, compact do not do it ??
1064
- .then( jsonldObj => { return JSON.stringify(jsonldObj, null, 2) }) // format jsonld
1065
- .then( jsonldString => { return makeRelative(jsonldString)})
1066
- .catch( e => { throw e })
1067
- }
1068
- function contextMethod (n3String) {
1069
- let prefixes = new Set()
1070
- const regex = /<(.*?)>/g
1071
- n3String.match(regex).map(string => {
1072
- const uri = string.slice(1).slice(0, -1)
1073
- console.log(this.base + ' ' + this.base)
1074
- if (uri.includes('//') && (!this.base || !uri.includes(this.base))) prefixes.add(addPrefix(uri))
1075
- })
1076
- let context = `{ `
1077
- const test = [...prefixes].map(term => {
1078
- context += `${term},`
1079
- })
1080
- /* console.log(this.prefixes)
1081
- let str = ''
1082
- console.log(this.namespacesUsed)
1083
- for (var ns in this.prefixes) {
1084
- if (!this.prefixes.hasOwnProperty(ns)) continue
1085
- if (!this.namespacesUsed[ns]) continue
1086
- str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) + '.\n'
1087
- // context += `"${this.prefixes[ns]}": "${this.explicitURI(ns)}",`
1088
- }
1089
- console.log('alain string ' +str)
1090
- */
1091
- return context.slice(0, -1) + `}`
1092
- }
1093
- function addPrefixMethod (uri) {
1094
- var j = uri.indexOf('#')
1095
- if (j < 0 ) {
1096
- j = uri.lastIndexOf('/')
1097
- }
1098
- if (j >= 0 &&
1099
- // Can split at namespace but only if http[s]: URI or file: or ws[s] (why not others?)
1100
- (uri.indexOf('http') === 0 || uri.indexOf('ws') === 0 || uri.indexOf('file') === 0)) {
1101
- var canSplit = true
1102
- for (var k = j + 1; k < uri.length; k++) {
1103
- if (this._notNameChars.indexOf(uri[k]) >= 0) {
1104
- canSplit = false
1105
- break
1106
- }
1107
- }
1108
- if (canSplit) {
1109
- var localid = uri.slice(j + 1)
1110
- var namesp = uri.slice(0, j + 1)
1111
- /*if (this.defaultNamespace && this.defaultNamespace === namesp &&
1112
- this.flags.indexOf('d') < 0) { // d -> suppress default
1113
- if (this.flags.indexOf('k') >= 0 &&
1114
- this.keyords.indexOf(localid) < 0) {
1115
- return localid
1116
- }
1117
- return ':' + localid
1118
- } */
1119
- // this.checkIntegrity() // @@@ Remove when not testing
1120
- var prefix = this.prefixes[namesp]
1121
- if (!prefix) prefix = this.makeUpPrefix(namesp)
1122
- if (prefix) {
1123
- console.log(`Alain "${prefix}": "${namesp}"`)
1124
- return `"${prefix}": "${namesp}"`
1125
- }
1126
- }
1127
- }
1128
- }
1129
- // return this.explicitURI(uri)
1130
- // }
1131
- var addPrefix = addPrefixMethod.bind(this)
1132
- var context = contextMethod.bind(this)
1133
-
1134
- const n3String = this.statementsToNTriples(sts)
1135
- // console.log(n3String)
1136
- let contextString = context(n3String)
1137
- // console.log(this.namespacesUsed)
1138
- return toJsonld(n3String, contextString, this.base)
1139
- }
1140
1014
  }
1141
1015
 
1142
1016
  // String escaping utilities
@@ -213,7 +213,7 @@ export default class UpdateManager {
213
213
  * Returns a list of all bnodes occurring in a list of statements
214
214
  * @private
215
215
  */
216
- statementArrayBnodes (sts: Quad[]) {
216
+ statementArrayBnodes (sts: ReadonlyArray<Quad>) {
217
217
  var bnodes: BlankNode[] = []
218
218
  for (let i = 0; i < sts.length; i++) {
219
219
  bnodes = bnodes.concat(this.statementBnodes(sts[i]))
@@ -752,7 +752,13 @@ export default class UpdateManager {
752
752
  // console.log(message)
753
753
  throw new Error(message)
754
754
  }
755
- var control = this.patchControlFor(doc as NamedNode)
755
+ if (doc.termType !== 'NamedNode') {
756
+ let message = 'Error patching: document not a NamedNode:' + ds[0] + ', ' + is[0]
757
+ // console.log(message)
758
+ throw new Error(message)
759
+ }
760
+ var control = this.patchControlFor(doc)
761
+
756
762
  var startTime = Date.now()
757
763
 
758
764
  var props = ['subject', 'predicate', 'object', 'why']