rdflib 2.2.21 → 2.2.22

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.
Files changed (106) hide show
  1. package/dist/rdflib.min.js +1 -1
  2. package/dist/rdflib.min.js.LICENSE.txt +9 -1
  3. package/dist/rdflib.min.js.map +1 -1
  4. package/esm/blank-node.js +61 -114
  5. package/esm/class-order.js +1 -1
  6. package/esm/collection.js +70 -128
  7. package/esm/convert.js +1 -2
  8. package/esm/default-graph.js +14 -48
  9. package/esm/empty.js +8 -39
  10. package/esm/factories/canonical-data-factory.js +33 -65
  11. package/esm/factories/extended-term-factory.js +18 -25
  12. package/esm/factories/factory-types.js +3 -2
  13. package/esm/factories/rdflib-data-factory.js +9 -19
  14. package/esm/fetcher.js +1341 -1854
  15. package/esm/formula.js +639 -846
  16. package/esm/index.js +40 -76
  17. package/esm/jsonldparser.js +24 -49
  18. package/esm/jsonparser.js +1 -8
  19. package/esm/lists.js +47 -110
  20. package/esm/literal.js +120 -189
  21. package/esm/log.js +7 -7
  22. package/esm/n3parser.js +1015 -1412
  23. package/esm/named-node.js +70 -119
  24. package/esm/namespace.js +2 -5
  25. package/esm/node-internal.js +73 -110
  26. package/esm/node.js +2 -7
  27. package/esm/parse.js +12 -19
  28. package/esm/patch-parser.js +10 -30
  29. package/esm/query-to-sparql.js +0 -18
  30. package/esm/query.js +63 -147
  31. package/esm/rdfaparser.js +794 -997
  32. package/esm/rdfxmlparser.js +347 -461
  33. package/esm/serialize.js +9 -27
  34. package/esm/serializer.js +820 -1049
  35. package/esm/sparql-to-query.js +44 -134
  36. package/esm/statement.js +54 -85
  37. package/esm/store.js +830 -1103
  38. package/esm/types.js +22 -21
  39. package/esm/update-manager.js +869 -1106
  40. package/esm/updates-via.js +104 -161
  41. package/esm/uri.js +9 -53
  42. package/esm/utils/default-graph-uri.js +3 -2
  43. package/esm/utils/termValue.js +0 -1
  44. package/esm/utils/terms.js +19 -21
  45. package/esm/utils-js.js +20 -61
  46. package/esm/utils.js +10 -21
  47. package/esm/variable.js +32 -78
  48. package/esm/xsd.js +2 -2
  49. package/lib/blank-node.js +60 -113
  50. package/lib/class-order.js +1 -2
  51. package/lib/collection.js +69 -131
  52. package/lib/convert.js +3 -9
  53. package/lib/default-graph.js +13 -52
  54. package/lib/empty.js +8 -43
  55. package/lib/factories/canonical-data-factory.js +35 -79
  56. package/lib/factories/extended-term-factory.js +18 -32
  57. package/lib/factories/factory-types.d.ts +6 -6
  58. package/lib/factories/factory-types.js +1 -4
  59. package/lib/factories/rdflib-data-factory.js +9 -23
  60. package/lib/fetcher.d.ts +6 -6
  61. package/lib/fetcher.js +1370 -1843
  62. package/lib/formula.js +640 -855
  63. package/lib/index.js +66 -152
  64. package/lib/jsonldparser.js +23 -53
  65. package/lib/jsonparser.js +1 -10
  66. package/lib/lists.js +55 -112
  67. package/lib/literal.js +120 -195
  68. package/lib/log.d.ts +0 -6
  69. package/lib/log.js +7 -8
  70. package/lib/n3parser.js +1030 -1436
  71. package/lib/named-node.js +69 -126
  72. package/lib/namespace.js +2 -7
  73. package/lib/node-internal.js +74 -107
  74. package/lib/node.js +2 -12
  75. package/lib/parse.d.ts +1 -1
  76. package/lib/parse.js +12 -32
  77. package/lib/patch-parser.js +11 -34
  78. package/lib/query-to-sparql.js +0 -23
  79. package/lib/query.js +62 -167
  80. package/lib/rdfaparser.js +796 -1009
  81. package/lib/rdfxmlparser.js +349 -466
  82. package/lib/serialize.js +11 -37
  83. package/lib/serializer.js +823 -1064
  84. package/lib/sparql-to-query.js +42 -167
  85. package/lib/statement.js +55 -91
  86. package/lib/store.d.ts +1 -1
  87. package/lib/store.js +850 -1112
  88. package/lib/tf-types.d.ts +4 -4
  89. package/lib/types.d.ts +8 -8
  90. package/lib/types.js +23 -23
  91. package/lib/update-manager.d.ts +1 -1
  92. package/lib/update-manager.js +865 -1103
  93. package/lib/updates-via.js +105 -164
  94. package/lib/uri.js +8 -61
  95. package/lib/utils/default-graph-uri.js +3 -5
  96. package/lib/utils/termValue.js +0 -2
  97. package/lib/utils/terms.js +19 -40
  98. package/lib/utils-js.js +23 -88
  99. package/lib/utils.js +10 -27
  100. package/lib/variable.js +34 -85
  101. package/lib/xsd-internal.js +0 -3
  102. package/lib/xsd.js +2 -6
  103. package/package.json +36 -36
  104. package/src/fetcher.ts +2 -2
  105. package/src/update-manager.ts +12 -7
  106. package/changes.txt +0 -59
@@ -1,47 +1,27 @@
1
1
  "use strict";
2
2
 
3
3
  var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
-
5
- var _typeof3 = require("@babel/runtime/helpers/typeof");
6
-
7
4
  Object.defineProperty(exports, "__esModule", {
8
5
  value: true
9
6
  });
10
7
  exports.default = void 0;
11
-
12
- var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
13
-
14
- var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
15
-
16
- var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
17
-
18
8
  var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
19
-
20
9
  var _store = _interopRequireDefault(require("./store"));
21
-
22
10
  var _uri = require("./uri");
23
-
24
11
  var _fetcher = _interopRequireDefault(require("./fetcher"));
25
-
26
12
  var _namespace = _interopRequireDefault(require("./namespace"));
27
-
28
13
  var _serializer = _interopRequireDefault(require("./serializer"));
29
-
30
14
  var _terms = require("./utils/terms");
31
-
32
15
  var Util = _interopRequireWildcard(require("./utils-js"));
33
-
34
16
  var _termValue = require("./utils/termValue");
35
-
36
- function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
37
-
38
- function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof3(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; }
39
-
40
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
41
-
42
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
43
-
44
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
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); }
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; }
19
+ /* @file Update Manager Class
20
+ **
21
+ ** 2007-07-15 originall sparl update module by Joe Presbrey <presbrey@mit.edu>
22
+ ** 2010-08-08 TimBL folded in Kenny's WEBDAV
23
+ ** 2010-12-07 TimBL addred local file write code
24
+ */
45
25
 
46
26
  /**
47
27
  * The UpdateManager is a helper object for a store.
@@ -49,7 +29,7 @@ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len
49
29
  * the Update Manager provides functionality for making small patches in real time,
50
30
  * and also looking out for concurrent updates from other agents
51
31
  */
52
- var UpdateManager = /*#__PURE__*/function () {
32
+ class UpdateManager {
53
33
  /** Index of objects for coordinating incoming and outgoing patches */
54
34
 
55
35
  /** Object of namespaces */
@@ -57,23 +37,19 @@ var UpdateManager = /*#__PURE__*/function () {
57
37
  /**
58
38
  * @param store - The quadstore to store data and metadata. Created if not passed.
59
39
  */
60
- function UpdateManager(store) {
61
- (0, _classCallCheck2.default)(this, UpdateManager);
40
+ constructor(store) {
62
41
  (0, _defineProperty2.default)(this, "store", void 0);
63
42
  (0, _defineProperty2.default)(this, "ifps", void 0);
64
43
  (0, _defineProperty2.default)(this, "fps", void 0);
65
44
  (0, _defineProperty2.default)(this, "patchControl", void 0);
66
45
  (0, _defineProperty2.default)(this, "ns", void 0);
67
46
  store = store || new _store.default();
68
-
69
47
  if (store.updater) {
70
48
  throw new Error("You can't have two UpdateManagers for the same store");
71
49
  }
72
-
73
50
  if (!store.fetcher) {
74
51
  store.fetcher = new _fetcher.default(store);
75
52
  }
76
-
77
53
  this.store = store;
78
54
  store.updater = this;
79
55
  this.ifps = {};
@@ -89,1183 +65,969 @@ var UpdateManager = /*#__PURE__*/function () {
89
65
  this.ns.owl = (0, _namespace.default)('http://www.w3.org/2002/07/owl#');
90
66
  this.patchControl = [];
91
67
  }
92
-
93
- (0, _createClass2.default)(UpdateManager, [{
94
- key: "patchControlFor",
95
- value: function patchControlFor(doc) {
96
- if (!this.patchControl[doc.value]) {
97
- this.patchControl[doc.value] = [];
98
- }
99
-
100
- return this.patchControl[doc.value];
68
+ patchControlFor(doc) {
69
+ if (!this.patchControl[doc.value]) {
70
+ this.patchControl[doc.value] = [];
101
71
  }
102
- }, {
103
- key: "isHttpUri",
104
- value: function isHttpUri(uri) {
105
- return uri.slice(0, 4) === 'http';
106
- }
107
- /**
108
- * Tests whether a file is editable.
109
- * If the file has a specific annotation that it is machine written,
110
- * for safety, it is editable (this doesn't actually check for write access)
111
- * If the file has wac-allow and accept patch headers, those are respected.
112
- * and local write access is determined by those headers.
113
- * This version only looks at past HTTP requests, does not make new ones.
114
- *
115
- * @returns The method string SPARQL or DAV or
116
- * LOCALFILE or false if known, undefined if not known.
117
- */
118
-
119
- }, {
120
- key: "editable",
121
- value: function editable(uri, kb) {
122
- if (!uri) {
123
- return false; // Eg subject is bnode, no known doc to write to
124
- }
125
-
126
- if (!kb) {
127
- kb = this.store;
128
- }
72
+ return this.patchControl[doc.value];
73
+ }
74
+ isHttpUri(uri) {
75
+ return uri.slice(0, 4) === 'http';
76
+ }
129
77
 
130
- uri = (0, _termValue.termValue)(uri);
78
+ /**
79
+ * Tests whether a file is editable.
80
+ * If the file has a specific annotation that it is machine written,
81
+ * for safety, it is editable (this doesn't actually check for write access)
82
+ * If the file has wac-allow and accept patch headers, those are respected.
83
+ * and local write access is determined by those headers.
84
+ * This version only looks at past HTTP requests, does not make new ones.
85
+ *
86
+ * @returns The method string SPARQL or DAV or
87
+ * LOCALFILE or false if known, undefined if not known.
88
+ */
89
+ editable(uri, kb) {
90
+ if (!uri) {
91
+ return false; // Eg subject is bnode, no known doc to write to
92
+ }
131
93
 
132
- if (!this.isHttpUri(uri)) {
133
- if (kb.holds(this.store.rdfFactory.namedNode(uri), this.store.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), this.store.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#MachineEditableDocument'))) {
134
- return 'LOCALFILE';
135
- }
94
+ if (!kb) {
95
+ kb = this.store;
96
+ }
97
+ uri = (0, _termValue.termValue)(uri);
98
+ if (!this.isHttpUri(uri)) {
99
+ if (kb.holds(this.store.rdfFactory.namedNode(uri), this.store.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), this.store.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#MachineEditableDocument'))) {
100
+ return 'LOCALFILE';
136
101
  }
137
-
138
- var request;
139
- var definitive = false; // @ts-ignore passes a string to kb.each, which expects a term. Should this work?
140
-
141
- var requests = kb.each(undefined, this.ns.link('requestedURI'), (0, _uri.docpart)(uri));
142
- var method;
143
-
144
- for (var r = 0; r < requests.length; r++) {
145
- request = requests[r];
146
-
102
+ }
103
+ var request;
104
+ var definitive = false;
105
+ // @ts-ignore passes a string to kb.each, which expects a term. Should this work?
106
+ var requests = kb.each(undefined, this.ns.link('requestedURI'), (0, _uri.docpart)(uri));
107
+ var method;
108
+ for (var r = 0; r < requests.length; r++) {
109
+ request = requests[r];
110
+ if (request !== undefined) {
111
+ var response = kb.any(request, this.ns.link('response'));
147
112
  if (request !== undefined) {
148
- var response = kb.any(request, this.ns.link('response'));
149
-
150
- if (request !== undefined) {
151
- var wacAllow = kb.anyValue(response, this.ns.httph('wac-allow'));
152
-
153
- if (wacAllow) {
154
- var _iterator = _createForOfIteratorHelper(wacAllow.split(',')),
155
- _step;
156
-
157
- try {
158
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
159
- var bit = _step.value;
160
- var lr = bit.split('=');
161
-
162
- if (lr[0].includes('user') && !lr[1].includes('write') && !lr[1].includes('append')) {
163
- // console.log(' editable? excluded by WAC-Allow: ', wacAllow)
164
- return false;
165
- }
166
- }
167
- } catch (err) {
168
- _iterator.e(err);
169
- } finally {
170
- _iterator.f();
113
+ var wacAllow = kb.anyValue(response, this.ns.httph('wac-allow'));
114
+ if (wacAllow) {
115
+ for (var bit of wacAllow.split(',')) {
116
+ var lr = bit.split('=');
117
+ if (lr[0].includes('user') && !lr[1].includes('write') && !lr[1].includes('append')) {
118
+ // console.log(' editable? excluded by WAC-Allow: ', wacAllow)
119
+ return false;
171
120
  }
172
121
  }
173
-
174
- var acceptPatch = kb.each(response, this.ns.httph('accept-patch'));
175
-
176
- if (acceptPatch.length) {
177
- for (var i = 0; i < acceptPatch.length; i++) {
178
- method = acceptPatch[i].value.trim();
179
- if (method.indexOf('application/sparql-update') >= 0) return 'SPARQL';
180
- if (method.indexOf('application/sparql-update-single-match') >= 0) return 'SPARQL';
181
- }
122
+ }
123
+ var acceptPatch = kb.each(response, this.ns.httph('accept-patch'));
124
+ if (acceptPatch.length) {
125
+ for (let i = 0; i < acceptPatch.length; i++) {
126
+ method = acceptPatch[i].value.trim();
127
+ if (method.indexOf('application/sparql-update') >= 0) return 'SPARQL';
128
+ if (method.indexOf('application/sparql-update-single-match') >= 0) return 'SPARQL';
182
129
  }
183
-
184
- var authorVia = kb.each(response, this.ns.httph('ms-author-via'));
185
-
186
- if (authorVia.length) {
187
- for (var _i = 0; _i < authorVia.length; _i++) {
188
- method = authorVia[_i].value.trim();
189
-
190
- if (method.indexOf('SPARQL') >= 0) {
191
- return 'SPARQL';
192
- }
193
-
194
- if (method.indexOf('DAV') >= 0) {
195
- return 'DAV';
196
- }
130
+ }
131
+ var authorVia = kb.each(response, this.ns.httph('ms-author-via'));
132
+ if (authorVia.length) {
133
+ for (let i = 0; i < authorVia.length; i++) {
134
+ method = authorVia[i].value.trim();
135
+ if (method.indexOf('SPARQL') >= 0) {
136
+ return 'SPARQL';
137
+ }
138
+ if (method.indexOf('DAV') >= 0) {
139
+ return 'DAV';
197
140
  }
198
141
  }
199
-
200
- if (!this.isHttpUri(uri)) {
201
- if (!wacAllow) return false;else return 'LOCALFILE';
202
- }
203
-
204
- var status = kb.each(response, this.ns.http('status'));
205
-
206
- if (status.length) {
207
- for (var _i2 = 0; _i2 < status.length; _i2++) {
208
- // @ts-ignore since statuses should be TFTerms, this should always be false
209
- if (status[_i2] === 200 || status[_i2] === 404) {
210
- definitive = true; // return false // A definitive answer
211
- }
142
+ }
143
+ if (!this.isHttpUri(uri)) {
144
+ if (!wacAllow) return false;else return 'LOCALFILE';
145
+ }
146
+ var status = kb.each(response, this.ns.http('status'));
147
+ if (status.length) {
148
+ for (let i = 0; i < status.length; i++) {
149
+ // @ts-ignore since statuses should be TFTerms, this should always be false
150
+ if (status[i] === 200 || status[i] === 404) {
151
+ definitive = true;
152
+ // return false // A definitive answer
212
153
  }
213
154
  }
214
- } else {// console.log('UpdateManager.editable: No response for ' + uri + '\n')
215
155
  }
156
+ } else {
157
+ // console.log('UpdateManager.editable: No response for ' + uri + '\n')
216
158
  }
217
159
  }
218
-
219
- if (requests.length === 0) {// console.log('UpdateManager.editable: No request for ' + uri + '\n')
220
- } else {
221
- if (definitive) {
222
- return false; // We have got a request and it did NOT say editable => not editable
223
- }
224
- } // console.log('UpdateManager.editable: inconclusive for ' + uri + '\n')
225
-
226
-
227
- return undefined; // We don't know (yet) as we haven't had a response (yet)
228
- }
229
- }, {
230
- key: "anonymize",
231
- value: function anonymize(obj) {
232
- return obj.toNT().substr(0, 2) === '_:' && this.mentioned(obj) ? '?' + obj.toNT().substr(2) : obj.toNT();
233
- }
234
- }, {
235
- key: "anonymizeNT",
236
- value: function anonymizeNT(stmt) {
237
- return this.anonymize(stmt.subject) + ' ' + this.anonymize(stmt.predicate) + ' ' + this.anonymize(stmt.object) + ' .';
238
- }
239
- }, {
240
- key: "nTriples",
241
- value: function nTriples(stmt) {
242
- return "".concat(stmt.subject.toNT(), " ").concat(stmt.predicate.toNT(), " ").concat(stmt.object.toNT(), " .");
243
160
  }
244
- /**
245
- * Returns a list of all bnodes occurring in a statement
246
- * @private
247
- */
248
-
249
- }, {
250
- key: "statementBnodes",
251
- value: function statementBnodes(st) {
252
- return [st.subject, st.predicate, st.object].filter(function (x) {
253
- return (0, _terms.isBlankNode)(x);
254
- });
255
- }
256
- /**
257
- * Returns a list of all bnodes occurring in a list of statements
258
- * @private
259
- */
260
-
261
- }, {
262
- key: "statementArrayBnodes",
263
- value: function statementArrayBnodes(sts) {
264
- var bnodes = [];
265
-
266
- for (var i = 0; i < sts.length; i++) {
267
- bnodes = bnodes.concat(this.statementBnodes(sts[i]));
268
- }
269
-
270
- bnodes.sort(); // in place sort - result may have duplicates
271
-
272
- var bnodes2 = [];
273
-
274
- for (var j = 0; j < bnodes.length; j++) {
275
- if (j === 0 || !bnodes[j].equals(bnodes[j - 1])) {
276
- bnodes2.push(bnodes[j]);
277
- }
161
+ if (requests.length === 0) {
162
+ // console.log('UpdateManager.editable: No request for ' + uri + '\n')
163
+ } else {
164
+ if (definitive) {
165
+ return false; // We have got a request and it did NOT say editable => not editable
278
166
  }
279
-
280
- return bnodes2;
281
167
  }
282
- /**
283
- * Makes a cached list of [Inverse-]Functional properties
284
- * @private
285
- */
286
-
287
- }, {
288
- key: "cacheIfps",
289
- value: function cacheIfps() {
290
- this.ifps = {};
291
- var a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('InverseFunctionalProperty'));
168
+ // console.log('UpdateManager.editable: inconclusive for ' + uri + '\n')
169
+ return undefined; // We don't know (yet) as we haven't had a response (yet)
170
+ }
292
171
 
293
- for (var i = 0; i < a.length; i++) {
294
- this.ifps[a[i].value] = true;
295
- }
172
+ anonymize(obj) {
173
+ return obj.toNT().substr(0, 2) === '_:' && this.mentioned(obj) ? '?' + obj.toNT().substr(2) : obj.toNT();
174
+ }
175
+ anonymizeNT(stmt) {
176
+ return this.anonymize(stmt.subject) + ' ' + this.anonymize(stmt.predicate) + ' ' + this.anonymize(stmt.object) + ' .';
177
+ }
178
+ nTriples(stmt) {
179
+ return `${stmt.subject.toNT()} ${stmt.predicate.toNT()} ${stmt.object.toNT()} .`;
180
+ }
296
181
 
297
- this.fps = {};
298
- a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('FunctionalProperty'));
182
+ /**
183
+ * Returns a list of all bnodes occurring in a statement
184
+ * @private
185
+ */
186
+ statementBnodes(st) {
187
+ return [st.subject, st.predicate, st.object].filter(function (x) {
188
+ return (0, _terms.isBlankNode)(x);
189
+ });
190
+ }
299
191
 
300
- for (var _i3 = 0; _i3 < a.length; _i3++) {
301
- this.fps[a[_i3].value] = true;
192
+ /**
193
+ * Returns a list of all bnodes occurring in a list of statements
194
+ * @private
195
+ */
196
+ statementArrayBnodes(sts) {
197
+ var bnodes = [];
198
+ for (let i = 0; i < sts.length; i++) {
199
+ bnodes = bnodes.concat(this.statementBnodes(sts[i]));
200
+ }
201
+ bnodes.sort(); // in place sort - result may have duplicates
202
+ var bnodes2 = [];
203
+ for (let j = 0; j < bnodes.length; j++) {
204
+ if (j === 0 || !bnodes[j].equals(bnodes[j - 1])) {
205
+ bnodes2.push(bnodes[j]);
302
206
  }
303
207
  }
304
- /**
305
- * Returns a context to bind a given node, up to a given depth
306
- * @private
307
- */
308
-
309
- }, {
310
- key: "bnodeContext2",
311
- value: function bnodeContext2(x, source, depth) {
312
- // Return a list of statements which indirectly identify a node
313
- // Depth > 1 if try further indirection.
314
- // Return array of statements (possibly empty), or null if failure
315
- var sts = this.store.statementsMatching(undefined, undefined, x, source); // incoming links
316
-
317
- var y;
318
- var res;
319
-
320
- for (var i = 0; i < sts.length; i++) {
321
- if (this.fps[sts[i].predicate.value]) {
322
- y = sts[i].subject;
323
-
324
- if (!y.isBlank) {
325
- return [sts[i]];
326
- }
208
+ return bnodes2;
209
+ }
327
210
 
328
- if (depth) {
329
- res = this.bnodeContext2(y, source, depth - 1);
211
+ /**
212
+ * Makes a cached list of [Inverse-]Functional properties
213
+ * @private
214
+ */
215
+ cacheIfps() {
216
+ this.ifps = {};
217
+ var a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('InverseFunctionalProperty'));
218
+ for (let i = 0; i < a.length; i++) {
219
+ this.ifps[a[i].value] = true;
220
+ }
221
+ this.fps = {};
222
+ a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('FunctionalProperty'));
223
+ for (let i = 0; i < a.length; i++) {
224
+ this.fps[a[i].value] = true;
225
+ }
226
+ }
330
227
 
331
- if (res) {
332
- return res.concat([sts[i]]);
333
- }
334
- }
228
+ /**
229
+ * Returns a context to bind a given node, up to a given depth
230
+ * @private
231
+ */
232
+ bnodeContext2(x, source, depth) {
233
+ // Return a list of statements which indirectly identify a node
234
+ // Depth > 1 if try further indirection.
235
+ // Return array of statements (possibly empty), or null if failure
236
+ var sts = this.store.statementsMatching(undefined, undefined, x, source); // incoming links
237
+ var y;
238
+ var res;
239
+ for (let i = 0; i < sts.length; i++) {
240
+ if (this.fps[sts[i].predicate.value]) {
241
+ y = sts[i].subject;
242
+ if (!y.isBlank) {
243
+ return [sts[i]];
335
244
  }
336
- } // outgoing links
337
-
338
-
339
- sts = this.store.statementsMatching(x, undefined, undefined, source);
340
-
341
- for (var _i4 = 0; _i4 < sts.length; _i4++) {
342
- if (this.ifps[sts[_i4].predicate.value]) {
343
- y = sts[_i4].object;
344
-
345
- if (!y.isBlank) {
346
- return [sts[_i4]];
347
- }
348
-
349
- if (depth) {
350
- res = this.bnodeContext2(y, source, depth - 1);
351
-
352
- if (res) {
353
- return res.concat([sts[_i4]]);
354
- }
245
+ if (depth) {
246
+ res = this.bnodeContext2(y, source, depth - 1);
247
+ if (res) {
248
+ return res.concat([sts[i]]);
355
249
  }
356
250
  }
357
251
  }
358
-
359
- return null; // Failure
360
252
  }
361
- /**
362
- * Returns the smallest context to bind a given single bnode
363
- * @private
364
- */
365
-
366
- }, {
367
- key: "bnodeContext1",
368
- value: function bnodeContext1(x, source) {
369
- // Return a list of statements which indirectly identify a node
370
- // Breadth-first
371
- for (var depth = 0; depth < 3; depth++) {
372
- // Try simple first
373
- var con = this.bnodeContext2(x, source, depth);
374
- if (con !== null) return con;
375
- } // If we can't guarantee unique with logic just send all info about node
376
-
377
-
378
- return this.store.connectedStatements(x, source); // was:
379
- // throw new Error('Unable to uniquely identify bnode: ' + x.toNT())
380
- }
381
- /**
382
- * @private
383
- */
384
-
385
- }, {
386
- key: "mentioned",
387
- value: function mentioned(x) {
388
- return this.store.statementsMatching(x, null, null, null).length !== 0 || // Don't pin fresh bnodes
389
- this.store.statementsMatching(null, x).length !== 0 || this.store.statementsMatching(null, null, x).length !== 0;
390
- }
391
- /**
392
- * @private
393
- */
394
-
395
- }, {
396
- key: "bnodeContext",
397
- value: function bnodeContext(bnodes, doc) {
398
- var context = [];
399
-
400
- if (bnodes.length) {
401
- this.cacheIfps();
402
-
403
- for (var i = 0; i < bnodes.length; i++) {
404
- // Does this occur in old graph?
405
- var bnode = bnodes[i];
406
- if (!this.mentioned(bnode)) continue;
407
- context = context.concat(this.bnodeContext1(bnode, doc));
253
+ // outgoing links
254
+ sts = this.store.statementsMatching(x, undefined, undefined, source);
255
+ for (let i = 0; i < sts.length; i++) {
256
+ if (this.ifps[sts[i].predicate.value]) {
257
+ y = sts[i].object;
258
+ if (!y.isBlank) {
259
+ return [sts[i]];
260
+ }
261
+ if (depth) {
262
+ res = this.bnodeContext2(y, source, depth - 1);
263
+ if (res) {
264
+ return res.concat([sts[i]]);
265
+ }
408
266
  }
409
267
  }
410
-
411
- return context;
412
- }
413
- /**
414
- * Returns the best context for a single statement
415
- * @private
416
- */
417
-
418
- }, {
419
- key: "statementContext",
420
- value: function statementContext(st) {
421
- var bnodes = this.statementBnodes(st);
422
- return this.bnodeContext(bnodes, st.graph);
423
268
  }
424
- /**
425
- * @private
426
- */
269
+ return null; // Failure
270
+ }
427
271
 
428
- }, {
429
- key: "contextWhere",
430
- value: function contextWhere(context) {
431
- var updater = this;
432
- return !context || context.length === 0 ? '' : 'WHERE { ' + context.map(function (x) {
433
- return updater.anonymizeNT(x);
434
- }).join('\n') + ' }\n';
272
+ /**
273
+ * Returns the smallest context to bind a given single bnode
274
+ * @private
275
+ */
276
+ bnodeContext1(x, source) {
277
+ // Return a list of statements which indirectly identify a node
278
+ // Breadth-first
279
+ for (var depth = 0; depth < 3; depth++) {
280
+ // Try simple first
281
+ var con = this.bnodeContext2(x, source, depth);
282
+ if (con !== null) return con;
435
283
  }
436
- /**
437
- * @private
438
- */
439
-
440
- }, {
441
- key: "fire",
442
- value: function fire(uri, query, callbackFunction) {
443
- var _this = this;
444
-
445
- var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
446
- return Promise.resolve().then(function () {
447
- if (!uri) {
448
- throw new Error('No URI given for remote editing operation: ' + query);
449
- } // console.log('UpdateManager: sending update to <' + uri + '>')
450
-
451
-
452
- options.noMeta = true;
453
- options.contentType = 'application/sparql-update';
454
- options.body = query;
455
- return _this.store.fetcher.webOperation('PATCH', uri, options);
456
- }).then(function (response) {
457
- if (!response.ok) {
458
- var _message = 'UpdateManager: update failed for <' + uri + '> status=' + response.status + ', ' + response.statusText + '\n for query: ' + query; // console.log(message)
459
-
460
-
461
- throw new Error(_message);
462
- } // console.log('UpdateManager: update Ok for <' + uri + '>')
463
-
464
-
465
- callbackFunction(uri, response.ok, response.responseText, response);
466
- }).catch(function (err) {
467
- callbackFunction(uri, false, err.message, err);
468
- });
469
- } // ARE THESE THEE FUNCTIONS USED? DEPROCATE?
284
+ // If we can't guarantee unique with logic just send all info about node
285
+ return this.store.connectedStatements(x, source); // was:
286
+ // throw new Error('Unable to uniquely identify bnode: ' + x.toNT())
287
+ }
470
288
 
471
- /** return a statemnet updating function
472
- *
473
- * This does NOT update the statement.
474
- * It returns an object which includes
475
- * function which can be used to change the object of the statement.
476
- */
289
+ /**
290
+ * @private
291
+ */
292
+ mentioned(x) {
293
+ return this.store.statementsMatching(x, null, null, null).length !== 0 ||
294
+ // Don't pin fresh bnodes
295
+ this.store.statementsMatching(null, x).length !== 0 || this.store.statementsMatching(null, null, x).length !== 0;
296
+ }
477
297
 
478
- }, {
479
- key: "update_statement",
480
- value: function update_statement(statement) {
481
- if (statement && !statement.graph) {
482
- return;
298
+ /**
299
+ * @private
300
+ */
301
+ bnodeContext(bnodes, doc) {
302
+ var context = [];
303
+ if (bnodes.length) {
304
+ this.cacheIfps();
305
+ for (let i = 0; i < bnodes.length; i++) {
306
+ // Does this occur in old graph?
307
+ var bnode = bnodes[i];
308
+ if (!this.mentioned(bnode)) continue;
309
+ context = context.concat(this.bnodeContext1(bnode, doc));
483
310
  }
484
-
485
- var updater = this;
486
- var context = this.statementContext(statement);
487
- return {
488
- statement: statement ? [statement.subject, statement.predicate, statement.object, statement.graph] : undefined,
489
- statementNT: statement ? this.anonymizeNT(statement) : undefined,
490
- where: updater.contextWhere(context),
491
- set_object: function set_object(obj, callbackFunction) {
492
- var query = this.where;
493
- query += 'DELETE DATA { ' + this.statementNT + ' } ;\n';
494
- query += 'INSERT DATA { ' + // @ts-ignore `this` might refer to the wrong scope. Does this work?
495
- this.anonymize(this.statement[0]) + ' ' + // @ts-ignore
496
- this.anonymize(this.statement[1]) + ' ' + // @ts-ignore
497
- this.anonymize(obj) + ' ' + ' . }\n';
498
- updater.fire(this.statement[3].value, query, callbackFunction);
499
- }
500
- };
501
311
  }
502
- }, {
503
- key: "insert_statement",
504
- value: function insert_statement(st, callbackFunction) {
505
- var st0 = st instanceof Array ? st[0] : st;
506
- var query = this.contextWhere(this.statementContext(st0));
312
+ return context;
313
+ }
507
314
 
508
- if (st instanceof Array) {
509
- var stText = '';
315
+ /**
316
+ * Returns the best context for a single statement
317
+ * @private
318
+ */
319
+ statementContext(st) {
320
+ var bnodes = this.statementBnodes(st);
321
+ return this.bnodeContext(bnodes, st.graph);
322
+ }
510
323
 
511
- for (var i = 0; i < st.length; i++) {
512
- stText += st[i] + '\n';
513
- }
324
+ /**
325
+ * @private
326
+ */
327
+ contextWhere(context) {
328
+ var updater = this;
329
+ return !context || context.length === 0 ? '' : 'WHERE { ' + context.map(function (x) {
330
+ return updater.anonymizeNT(x);
331
+ }).join('\n') + ' }\n';
332
+ }
514
333
 
515
- query += 'INSERT DATA { ' + stText + ' }\n';
516
- } else {
517
- query += 'INSERT DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n';
334
+ /**
335
+ * @private
336
+ */
337
+ fire(uri, query, callbackFunction) {
338
+ let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
339
+ return Promise.resolve().then(() => {
340
+ if (!uri) {
341
+ throw new Error('No URI given for remote editing operation: ' + query);
518
342
  }
343
+ // console.log('UpdateManager: sending update to <' + uri + '>')
519
344
 
520
- this.fire(st0.graph.value, query, callbackFunction);
521
- }
522
- }, {
523
- key: "delete_statement",
524
- value: function delete_statement(st, callbackFunction) {
525
- var st0 = st instanceof Array ? st[0] : st;
526
- var query = this.contextWhere(this.statementContext(st0));
527
-
528
- if (st instanceof Array) {
529
- var stText = '';
530
-
531
- for (var i = 0; i < st.length; i++) {
532
- stText += st[i] + '\n';
533
- }
534
-
535
- query += 'DELETE DATA { ' + stText + ' }\n';
536
- } else {
537
- query += 'DELETE DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n';
345
+ options.noMeta = true;
346
+ options.contentType = 'application/sparql-update';
347
+ options.body = query;
348
+ return this.store.fetcher.webOperation('PATCH', uri, options);
349
+ }).then(response => {
350
+ if (!response.ok) {
351
+ let message = 'UpdateManager: update failed for <' + uri + '> status=' + response.status + ', ' + response.statusText + '\n for query: ' + query;
352
+ // console.log(message)
353
+ throw new Error(message);
538
354
  }
539
355
 
540
- this.fire(st0.graph.value, query, callbackFunction);
541
- } /// //////////////////////
356
+ // console.log('UpdateManager: update Ok for <' + uri + '>')
542
357
 
543
- /**
544
- * Requests a now or future action to refresh changes coming downstream
545
- * This is designed to allow the system to re-request the server version,
546
- * when a websocket has pinged to say there are changes.
547
- * If the websocket, by contrast, has sent a patch, then this may not be necessary.
548
- *
549
- * @param doc
550
- * @param action
551
- */
552
-
553
- }, {
554
- key: "requestDownstreamAction",
555
- value: function requestDownstreamAction(doc, action) {
556
- var control = this.patchControlFor(doc);
358
+ callbackFunction(uri, response.ok, response.responseText, response);
359
+ }).catch(err => {
360
+ callbackFunction(uri, false, err.message, err);
361
+ });
362
+ }
557
363
 
558
- if (!control.pendingUpstream) {
559
- action(doc);
560
- } else {
561
- if (control.downstreamAction) {
562
- if ('' + control.downstreamAction !== '' + action) {
563
- // Kludge compare
564
- throw new Error("Can't wait for > 1 different downstream actions");
565
- }
566
- } else {
567
- control.downstreamAction = action;
568
- }
569
- }
364
+ // ARE THESE THEE FUNCTIONS USED? DEPROCATE?
365
+
366
+ /** return a statemnet updating function
367
+ *
368
+ * This does NOT update the statement.
369
+ * It returns an object which includes
370
+ * function which can be used to change the object of the statement.
371
+ */
372
+ update_statement(statement) {
373
+ if (statement && !statement.graph) {
374
+ return;
570
375
  }
571
- /**
572
- * We want to start counting websocket notifications
573
- * to distinguish the ones from others from our own.
574
- */
575
-
576
- }, {
577
- key: "clearUpstreamCount",
578
- value: function clearUpstreamCount(doc) {
579
- var control = this.patchControlFor(doc);
580
- control.upstreamCount = 0;
376
+ var updater = this;
377
+ var context = this.statementContext(statement);
378
+ return {
379
+ statement: statement ? [statement.subject, statement.predicate, statement.object, statement.graph] : undefined,
380
+ statementNT: statement ? this.anonymizeNT(statement) : undefined,
381
+ where: updater.contextWhere(context),
382
+ set_object: function (obj, callbackFunction) {
383
+ var query = this.where;
384
+ query += 'DELETE DATA { ' + this.statementNT + ' } ;\n';
385
+ query += 'INSERT DATA { ' +
386
+ // @ts-ignore `this` might refer to the wrong scope. Does this work?
387
+ this.anonymize(this.statement[0]) + ' ' +
388
+ // @ts-ignore
389
+ this.anonymize(this.statement[1]) + ' ' +
390
+ // @ts-ignore
391
+ this.anonymize(obj) + ' ' + ' . }\n';
392
+ updater.fire(this.statement[3].value, query, callbackFunction);
393
+ }
394
+ };
395
+ }
396
+ insert_statement(st, callbackFunction) {
397
+ var st0 = st instanceof Array ? st[0] : st;
398
+ var query = this.contextWhere(this.statementContext(st0));
399
+ if (st instanceof Array) {
400
+ var stText = '';
401
+ for (let i = 0; i < st.length; i++) stText += st[i] + '\n';
402
+ query += 'INSERT DATA { ' + stText + ' }\n';
403
+ } else {
404
+ query += 'INSERT DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n';
581
405
  }
582
- }, {
583
- key: "getUpdatesVia",
584
- value: function getUpdatesVia(doc) {
585
- var linkHeaders = this.store.fetcher.getHeader(doc, 'updates-via');
586
- if (!linkHeaders || !linkHeaders.length) return null;
587
- return linkHeaders[0].trim();
406
+ this.fire(st0.graph.value, query, callbackFunction);
407
+ }
408
+ delete_statement(st, callbackFunction) {
409
+ var st0 = st instanceof Array ? st[0] : st;
410
+ var query = this.contextWhere(this.statementContext(st0));
411
+ if (st instanceof Array) {
412
+ var stText = '';
413
+ for (let i = 0; i < st.length; i++) stText += st[i] + '\n';
414
+ query += 'DELETE DATA { ' + stText + ' }\n';
415
+ } else {
416
+ query += 'DELETE DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n';
588
417
  }
589
- }, {
590
- key: "addDownstreamChangeListener",
591
- value: function addDownstreamChangeListener(doc, listener) {
592
- var _this2 = this;
418
+ this.fire(st0.graph.value, query, callbackFunction);
419
+ }
593
420
 
594
- var control = this.patchControlFor(doc);
421
+ /// //////////////////////
595
422
 
596
- if (!control.downstreamChangeListeners) {
597
- control.downstreamChangeListeners = [];
423
+ /**
424
+ * Requests a now or future action to refresh changes coming downstream
425
+ * This is designed to allow the system to re-request the server version,
426
+ * when a websocket has pinged to say there are changes.
427
+ * If the websocket, by contrast, has sent a patch, then this may not be necessary.
428
+ *
429
+ * @param doc
430
+ * @param action
431
+ */
432
+ requestDownstreamAction(doc, action) {
433
+ var control = this.patchControlFor(doc);
434
+ if (!control.pendingUpstream) {
435
+ action(doc);
436
+ } else {
437
+ if (control.downstreamAction) {
438
+ if ('' + control.downstreamAction !== '' + action) {
439
+ // Kludge compare
440
+ throw new Error("Can't wait for > 1 different downstream actions");
441
+ }
442
+ } else {
443
+ control.downstreamAction = action;
598
444
  }
599
-
600
- control.downstreamChangeListeners.push(listener);
601
- this.setRefreshHandler(doc, function (doc) {
602
- _this2.reloadAndSync(doc);
603
- });
604
445
  }
605
- }, {
606
- key: "reloadAndSync",
607
- value: function reloadAndSync(doc) {
608
- var control = this.patchControlFor(doc);
609
- var updater = this;
610
-
611
- if (control.reloading) {
612
- // console.log(' Already reloading - note this load may be out of date')
613
- control.outOfDate = true;
614
- return; // once only needed @@ Not true, has changed again
615
- }
616
-
617
- control.reloading = true;
618
- var retryTimeout = 1000; // ms
619
-
620
- var tryReload = function tryReload() {
621
- // console.log('try reload - timeout = ' + retryTimeout)
622
- updater.reload(updater.store, doc, function (ok, message, response) {
623
- if (ok) {
624
- if (control.downstreamChangeListeners) {
625
- for (var i = 0; i < control.downstreamChangeListeners.length; i++) {
626
- // console.log(' Calling downstream listener ' + i)
627
- control.downstreamChangeListeners[i]();
628
- }
629
- }
446
+ }
630
447
 
631
- control.reloading = false;
448
+ /**
449
+ * We want to start counting websocket notifications
450
+ * to distinguish the ones from others from our own.
451
+ */
452
+ clearUpstreamCount(doc) {
453
+ var control = this.patchControlFor(doc);
454
+ control.upstreamCount = 0;
455
+ }
456
+ getUpdatesVia(doc) {
457
+ var linkHeaders = this.store.fetcher.getHeader(doc, 'updates-via');
458
+ if (!linkHeaders || !linkHeaders.length) return null;
459
+ return linkHeaders[0].trim();
460
+ }
461
+ addDownstreamChangeListener(doc, listener) {
462
+ var control = this.patchControlFor(doc);
463
+ if (!control.downstreamChangeListeners) {
464
+ control.downstreamChangeListeners = [];
465
+ }
466
+ control.downstreamChangeListeners.push(listener);
467
+ this.setRefreshHandler(doc, doc => {
468
+ this.reloadAndSync(doc);
469
+ });
470
+ }
471
+ reloadAndSync(doc) {
472
+ var control = this.patchControlFor(doc);
473
+ var updater = this;
474
+ if (control.reloading) {
475
+ // console.log(' Already reloading - note this load may be out of date')
476
+ control.outOfDate = true;
477
+ return; // once only needed @@ Not true, has changed again
478
+ }
632
479
 
633
- if (control.outOfDate) {
634
- // console.log(' Extra reload because of extra update.')
635
- control.outOfDate = false;
636
- tryReload();
480
+ control.reloading = true;
481
+ var retryTimeout = 1000; // ms
482
+ var tryReload = function () {
483
+ // console.log('try reload - timeout = ' + retryTimeout)
484
+ updater.reload(updater.store, doc, function (ok, message, response) {
485
+ if (ok) {
486
+ if (control.downstreamChangeListeners) {
487
+ for (let i = 0; i < control.downstreamChangeListeners.length; i++) {
488
+ // console.log(' Calling downstream listener ' + i)
489
+ control.downstreamChangeListeners[i]();
637
490
  }
491
+ }
492
+ control.reloading = false;
493
+ if (control.outOfDate) {
494
+ // console.log(' Extra reload because of extra update.')
495
+ control.outOfDate = false;
496
+ tryReload();
497
+ }
498
+ } else {
499
+ control.reloading = false;
500
+ if (response.status === 0) {
501
+ // console.log('Network error refreshing the data. Retrying in ' +
502
+ // retryTimeout / 1000)
503
+ control.reloading = true;
504
+ retryTimeout = retryTimeout * 2;
505
+ setTimeout(tryReload, retryTimeout);
638
506
  } else {
639
- control.reloading = false;
640
-
641
- if (response.status === 0) {
642
- // console.log('Network error refreshing the data. Retrying in ' +
643
- // retryTimeout / 1000)
644
- control.reloading = true;
645
- retryTimeout = retryTimeout * 2;
646
- setTimeout(tryReload, retryTimeout);
647
- } else {// console.log('Error ' + (response as Response).status + 'refreshing the data:' +
648
- // message + '. Stopped' + doc)
649
- }
507
+ // console.log('Error ' + (response as Response).status + 'refreshing the data:' +
508
+ // message + '. Stopped' + doc)
650
509
  }
651
- });
652
- };
510
+ }
511
+ });
512
+ };
513
+ tryReload();
514
+ }
653
515
 
654
- tryReload();
516
+ /**
517
+ * Sets up websocket to listen on
518
+ *
519
+ * There is coordination between upstream changes and downstream ones
520
+ * so that a reload is not done in the middle of an upstream patch.
521
+ * If you use this API then you get called when a change happens, and you
522
+ * have to reload the file yourself, and then refresh the UI.
523
+ * Alternative is addDownstreamChangeListener(), where you do not
524
+ * have to do the reload yourself. Do mot mix them.
525
+ *
526
+ * kb contains the HTTP metadata from previous operations
527
+ *
528
+ * @param doc
529
+ * @param handler
530
+ *
531
+ * @returns {boolean}
532
+ */
533
+ setRefreshHandler(doc, handler) {
534
+ let wssURI = this.getUpdatesVia(doc); // relative
535
+ // var kb = this.store
536
+ var theHandler = handler;
537
+ var self = this;
538
+ var updater = this;
539
+ var retryTimeout = 1500; // *2 will be 3 Seconds, 6, 12, etc
540
+ var retries = 0;
541
+ if (!wssURI) {
542
+ // console.log('Server does not support live updates through Updates-Via :-(')
543
+ return false;
655
544
  }
656
- /**
657
- * Sets up websocket to listen on
658
- *
659
- * There is coordination between upstream changes and downstream ones
660
- * so that a reload is not done in the middle of an upstream patch.
661
- * If you use this API then you get called when a change happens, and you
662
- * have to reload the file yourself, and then refresh the UI.
663
- * Alternative is addDownstreamChangeListener(), where you do not
664
- * have to do the reload yourself. Do mot mix them.
665
- *
666
- * kb contains the HTTP metadata from previous operations
667
- *
668
- * @param doc
669
- * @param handler
670
- *
671
- * @returns {boolean}
672
- */
673
-
674
- }, {
675
- key: "setRefreshHandler",
676
- value: function setRefreshHandler(doc, handler) {
677
- var wssURI = this.getUpdatesVia(doc); // relative
678
- // var kb = this.store
679
-
680
- var theHandler = handler;
681
- var self = this;
682
- var updater = this;
683
- var retryTimeout = 1500; // *2 will be 3 Seconds, 6, 12, etc
684
-
685
- var retries = 0;
686
-
687
- if (!wssURI) {
688
- // console.log('Server does not support live updates through Updates-Via :-(')
689
- return false;
545
+ wssURI = (0, _uri.join)(wssURI, doc.value);
546
+ const validWssURI = wssURI.replace(/^http:/, 'ws:').replace(/^https:/, 'wss:');
547
+ // console.log('Web socket URI ' + wssURI)
548
+
549
+ var openWebsocket = function () {
550
+ // From https://github.com/solid/solid-spec#live-updates
551
+ var socket;
552
+ if (typeof WebSocket !== 'undefined') {
553
+ socket = new WebSocket(validWssURI);
554
+ } else if (typeof window !== 'undefined' && window.WebSocket) {
555
+ socket = window.WebSocket(validWssURI);
556
+ } else {
557
+ // console.log('Live update disabled, as WebSocket not supported by platform :-(')
558
+ return;
690
559
  }
691
-
692
- wssURI = (0, _uri.join)(wssURI, doc.value);
693
- var validWssURI = wssURI.replace(/^http:/, 'ws:').replace(/^https:/, 'wss:'); // console.log('Web socket URI ' + wssURI)
694
-
695
- var openWebsocket = function openWebsocket() {
696
- // From https://github.com/solid/solid-spec#live-updates
697
- var socket;
698
-
699
- if (typeof WebSocket !== 'undefined') {
700
- socket = new WebSocket(validWssURI);
701
- } else if (typeof window !== 'undefined' && window.WebSocket) {
702
- socket = window.WebSocket(validWssURI);
703
- } else {
704
- // console.log('Live update disabled, as WebSocket not supported by platform :-(')
705
- return;
560
+ socket.onopen = function () {
561
+ // console.log(' websocket open')
562
+ retryTimeout = 1500; // reset timeout to fast on success
563
+ this.send('sub ' + doc.value);
564
+ if (retries) {
565
+ // console.log('Web socket has been down, better check for any news.')
566
+ updater.requestDownstreamAction(doc, theHandler);
706
567
  }
568
+ };
569
+ var control = self.patchControlFor(doc);
570
+ control.upstreamCount = 0;
571
+ socket.onerror = function onerror(err) {
572
+ // console.log('Error on Websocket:', err)
573
+ };
707
574
 
708
- socket.onopen = function () {
709
- // console.log(' websocket open')
710
- retryTimeout = 1500; // reset timeout to fast on success
711
-
712
- this.send('sub ' + doc.value);
713
-
714
- if (retries) {
715
- // console.log('Web socket has been down, better check for any news.')
716
- updater.requestDownstreamAction(doc, theHandler);
717
- }
718
- };
719
-
720
- var control = self.patchControlFor(doc);
721
- control.upstreamCount = 0;
722
-
723
- socket.onerror = function onerror(err) {// console.log('Error on Websocket:', err)
724
- }; // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
725
- //
726
- // 1000 CLOSE_NORMAL Normal closure; the connection successfully completed whatever purpose for which it was created.
727
- // 1001 CLOSE_GOING_AWAY The endpoint is going away, either
728
- // because of a server failure or because the browser is navigating away from the page that opened the connection.
729
- // 1002 CLOSE_PROTOCOL_ERROR The endpoint is terminating the connection due to a protocol error.
730
- // 1003 CLOSE_UNSUPPORTED The connection is being terminated because the endpoint
731
- // received data of a type it cannot accept (for example, a text-only endpoint received binary data).
732
- // 1004 Reserved. A meaning might be defined in the future.
733
- // 1005 CLOSE_NO_STATUS Reserved. Indicates that no status code was provided even though one was expected.
734
- // 1006 CLOSE_ABNORMAL Reserved. Used to indicate that a connection was closed abnormally (
735
- //
736
- //
737
-
738
-
739
- socket.onclose = function (event) {
740
- // console.log('*** Websocket closed with code ' + event.code +
741
- // ", reason '" + event.reason + "' clean = " + event.wasClean)
742
- retryTimeout *= 2;
743
- retries += 1; // console.log('Retrying in ' + retryTimeout + 'ms') // (ask user?)
744
-
745
- setTimeout(function () {
746
- // console.log('Trying websocket again')
747
- openWebsocket();
748
- }, retryTimeout);
749
- };
750
-
751
- socket.onmessage = function (msg) {
752
- if (msg.data && msg.data.slice(0, 3) === 'pub') {
753
- if ('upstreamCount' in control) {
754
- control.upstreamCount -= 1;
755
-
756
- if (control.upstreamCount >= 0) {
757
- // console.log('just an echo: ' + control.upstreamCount)
758
- return; // Just an echo
759
- }
760
- } // console.log('Assume a real downstream change: ' + control.upstreamCount + ' -> 0')
761
-
762
-
763
- control.upstreamCount = 0;
764
- self.requestDownstreamAction(doc, theHandler);
575
+ // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
576
+ //
577
+ // 1000 CLOSE_NORMAL Normal closure; the connection successfully completed whatever purpose for which it was created.
578
+ // 1001 CLOSE_GOING_AWAY The endpoint is going away, either
579
+ // because of a server failure or because the browser is navigating away from the page that opened the connection.
580
+ // 1002 CLOSE_PROTOCOL_ERROR The endpoint is terminating the connection due to a protocol error.
581
+ // 1003 CLOSE_UNSUPPORTED The connection is being terminated because the endpoint
582
+ // received data of a type it cannot accept (for example, a text-only endpoint received binary data).
583
+ // 1004 Reserved. A meaning might be defined in the future.
584
+ // 1005 CLOSE_NO_STATUS Reserved. Indicates that no status code was provided even though one was expected.
585
+ // 1006 CLOSE_ABNORMAL Reserved. Used to indicate that a connection was closed abnormally (
586
+ //
587
+ //
588
+ socket.onclose = function (event) {
589
+ // console.log('*** Websocket closed with code ' + event.code +
590
+ // ", reason '" + event.reason + "' clean = " + event.wasClean)
591
+ retryTimeout *= 2;
592
+ retries += 1;
593
+ // console.log('Retrying in ' + retryTimeout + 'ms') // (ask user?)
594
+ setTimeout(function () {
595
+ // console.log('Trying websocket again')
596
+ openWebsocket();
597
+ }, retryTimeout);
598
+ };
599
+ socket.onmessage = function (msg) {
600
+ if (msg.data && msg.data.slice(0, 3) === 'pub') {
601
+ if ('upstreamCount' in control) {
602
+ control.upstreamCount -= 1;
603
+ if (control.upstreamCount >= 0) {
604
+ // console.log('just an echo: ' + control.upstreamCount)
605
+ return; // Just an echo
606
+ }
765
607
  }
766
- };
767
- }; // openWebsocket
768
-
608
+ // console.log('Assume a real downstream change: ' + control.upstreamCount + ' -> 0')
609
+ control.upstreamCount = 0;
610
+ self.requestDownstreamAction(doc, theHandler);
611
+ }
612
+ };
613
+ }; // openWebsocket
614
+ openWebsocket();
615
+ return true;
616
+ }
769
617
 
770
- openWebsocket();
771
- return true;
618
+ /**
619
+ * This high-level function updates the local store iff the web is changed successfully.
620
+ * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).
621
+ * The `why` property of each statement must be the give the web document to be updated.
622
+ * The statements to be deleted and inserted may span more than one web document.
623
+ * @param deletions - Statement or statements to be deleted.
624
+ * @param insertions - Statement or statements to be inserted.
625
+ * @returns a promise
626
+ */
627
+ updateMany(deletions) {
628
+ let insertions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
629
+ const docs = deletions.concat(insertions).map(st => st.why);
630
+ const thisUpdater = this;
631
+ const uniqueDocs = [];
632
+ docs.forEach(doc => {
633
+ if (!uniqueDocs.find(uniqueDoc => uniqueDoc.equals(doc))) uniqueDocs.push(doc);
634
+ });
635
+ const updates = uniqueDocs.map(doc => thisUpdater.update(deletions.filter(st => st.why.equals(doc)), insertions.filter(st => st.why.equals(doc))));
636
+ if (updates.length > 1) {
637
+ // console.log(`@@ updateMany to ${updates.length}: ${uniqueDocs}`)
772
638
  }
773
- /**
774
- * This high-level function updates the local store iff the web is changed successfully.
775
- * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).
776
- * The `why` property of each statement must be the give the web document to be updated.
777
- * The statements to be deleted and inserted may span more than one web document.
778
- * @param deletions - Statement or statements to be deleted.
779
- * @param insertions - Statement or statements to be inserted.
780
- * @returns a promise
781
- */
639
+ return Promise.all(updates);
640
+ }
782
641
 
783
- }, {
784
- key: "updateMany",
785
- value: function updateMany(deletions) {
786
- var insertions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
787
- var docs = deletions.concat(insertions).map(function (st) {
788
- return st.why;
789
- });
642
+ /**
643
+ * This high-level function updates the local store iff the web is changed successfully.
644
+ * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).
645
+ * The `why` property of each statement must be the same and give the web document to be updated.
646
+ * @param deletions - Statement or statements to be deleted.
647
+ * @param insertions - Statement or statements to be inserted.
648
+ * @param callback - called as callbackFunction(uri, success, errorbody)
649
+ * OR returns a promise
650
+ * @param options - Options for the fetch call
651
+ */
652
+ update(deletions, insertions, callback, secondTry) {
653
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
654
+ if (!callback) {
790
655
  var thisUpdater = this;
791
- var uniqueDocs = [];
792
- docs.forEach(function (doc) {
793
- if (!uniqueDocs.find(function (uniqueDoc) {
794
- return uniqueDoc.equals(doc);
795
- })) uniqueDocs.push(doc);
796
- });
797
- var updates = uniqueDocs.map(function (doc) {
798
- return thisUpdater.update(deletions.filter(function (st) {
799
- return st.why.equals(doc);
800
- }), insertions.filter(function (st) {
801
- return st.why.equals(doc);
802
- }));
803
- });
656
+ return new Promise(function (resolve, reject) {
657
+ // Promise version
658
+ thisUpdater.update(deletions, insertions, function (uri, ok, errorBody) {
659
+ if (!ok) {
660
+ reject(new Error(errorBody));
661
+ } else {
662
+ resolve();
663
+ }
664
+ }, secondTry, options); // callbackFunction
665
+ }); // promise
666
+ } // if
804
667
 
805
- if (updates.length > 1) {// console.log(`@@ updateMany to ${updates.length}: ${uniqueDocs}`)
668
+ try {
669
+ var kb = this.store;
670
+ var ds = !deletions ? [] : (0, _terms.isStore)(deletions) ? deletions.statements : deletions instanceof Array ? deletions : [deletions];
671
+ var is = !insertions ? [] : (0, _terms.isStore)(insertions) ? insertions.statements : insertions instanceof Array ? insertions : [insertions];
672
+ if (!(ds instanceof Array)) {
673
+ throw new Error('Type Error ' + typeof ds + ': ' + ds);
674
+ }
675
+ if (!(is instanceof Array)) {
676
+ throw new Error('Type Error ' + typeof is + ': ' + is);
677
+ }
678
+ if (ds.length === 0 && is.length === 0) {
679
+ return callback(null, true); // success -- nothing needed to be done.
806
680
  }
807
681
 
808
- return Promise.all(updates);
809
- }
810
- /**
811
- * This high-level function updates the local store iff the web is changed successfully.
812
- * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).
813
- * The `why` property of each statement must be the same and give the web document to be updated.
814
- * @param deletions - Statement or statements to be deleted.
815
- * @param insertions - Statement or statements to be inserted.
816
- * @param callback - called as callbackFunction(uri, success, errorbody)
817
- * OR returns a promise
818
- * @param options - Options for the fetch call
819
- */
820
-
821
- }, {
822
- key: "update",
823
- value: function update(deletions, insertions, callback, secondTry) {
824
- var _this3 = this;
825
-
826
- var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
827
-
828
- if (!callback) {
829
- var thisUpdater = this;
830
- return new Promise(function (resolve, reject) {
831
- // Promise version
832
- thisUpdater.update(deletions, insertions, function (uri, ok, errorBody) {
833
- if (!ok) {
834
- reject(new Error(errorBody));
835
- } else {
836
- resolve();
837
- }
838
- }, secondTry, options); // callbackFunction
839
- }); // promise
840
- } // if
841
-
842
-
843
- try {
844
- var kb = this.store;
845
- var ds = !deletions ? [] : (0, _terms.isStore)(deletions) ? deletions.statements : deletions instanceof Array ? deletions : [deletions];
846
- var is = !insertions ? [] : (0, _terms.isStore)(insertions) ? insertions.statements : insertions instanceof Array ? insertions : [insertions];
847
-
848
- if (!(ds instanceof Array)) {
849
- throw new Error('Type Error ' + (0, _typeof2.default)(ds) + ': ' + ds);
850
- }
851
-
852
- if (!(is instanceof Array)) {
853
- throw new Error('Type Error ' + (0, _typeof2.default)(is) + ': ' + is);
854
- }
855
-
856
- if (ds.length === 0 && is.length === 0) {
857
- return callback(null, true); // success -- nothing needed to be done.
858
- }
859
-
860
- var doc = ds.length ? ds[0].graph : is[0].graph;
861
-
862
- if (!doc) {
863
- var _message2 = 'Error patching: statement does not specify which document to patch:' + ds[0] + ', ' + is[0]; // console.log(message)
864
-
865
-
866
- throw new Error(_message2);
867
- }
868
-
869
- var control = this.patchControlFor(doc);
870
- var startTime = Date.now();
871
- var props = ['subject', 'predicate', 'object', 'why'];
872
- var verbs = ['insert', 'delete'];
873
- var clauses = {
874
- 'delete': ds,
875
- 'insert': is
876
- };
877
- verbs.map(function (verb) {
878
- clauses[verb].map(function (st) {
879
- if (!doc.equals(st.graph)) {
880
- throw new Error('update: destination ' + doc + ' inconsistent with delete quad ' + st.graph);
682
+ var doc = ds.length ? ds[0].graph : is[0].graph;
683
+ if (!doc) {
684
+ let message = 'Error patching: statement does not specify which document to patch:' + ds[0] + ', ' + is[0];
685
+ // console.log(message)
686
+ throw new Error(message);
687
+ }
688
+ var control = this.patchControlFor(doc);
689
+ var startTime = Date.now();
690
+ var props = ['subject', 'predicate', 'object', 'why'];
691
+ var verbs = ['insert', 'delete'];
692
+ var clauses = {
693
+ 'delete': ds,
694
+ 'insert': is
695
+ };
696
+ verbs.map(function (verb) {
697
+ clauses[verb].map(function (st) {
698
+ if (!doc.equals(st.graph)) {
699
+ throw new Error('update: destination ' + doc + ' inconsistent with delete quad ' + st.graph);
700
+ }
701
+ props.map(function (prop) {
702
+ if (typeof st[prop] === 'undefined') {
703
+ throw new Error('update: undefined ' + prop + ' of statement.');
881
704
  }
882
-
883
- props.map(function (prop) {
884
- if (typeof st[prop] === 'undefined') {
885
- throw new Error('update: undefined ' + prop + ' of statement.');
886
- }
887
- });
888
705
  });
889
706
  });
890
- var protocol = this.editable(doc.value, kb);
891
-
892
- if (protocol === false) {
893
- throw new Error('Update: Can\'t make changes in uneditable ' + doc);
707
+ });
708
+ var protocol = this.editable(doc.value, kb);
709
+ if (protocol === false) {
710
+ throw new Error('Update: Can\'t make changes in uneditable ' + doc);
711
+ }
712
+ if (protocol === undefined) {
713
+ // Not enough metadata
714
+ if (secondTry) {
715
+ throw new Error('Update: Loaded ' + doc + "but stil can't figure out what editing protcol it supports.");
894
716
  }
895
-
896
- if (protocol === undefined) {
897
- // Not enough metadata
898
- if (secondTry) {
899
- throw new Error('Update: Loaded ' + doc + "but stil can't figure out what editing protcol it supports.");
900
- } // console.log(`Update: have not loaded ${doc} before: loading now...`);
901
-
902
-
903
- this.store.fetcher.load(doc).then(function (response) {
904
- _this3.update(deletions, insertions, callback, true, options);
905
- }, function (err) {
906
- if (err.response.status === 404) {
907
- // nonexistent files are fine
908
- _this3.update(deletions, insertions, callback, true, options);
909
- } else {
910
- throw new Error("Update: Can't get updatability status ".concat(doc, " before patching: ").concat(err));
911
- }
912
- });
913
- return;
914
- } else if (protocol.indexOf('SPARQL') >= 0) {
915
- var bnodes = [];
916
- if (ds.length) bnodes = this.statementArrayBnodes(ds);
917
- if (is.length) bnodes = bnodes.concat(this.statementArrayBnodes(is));
918
- var context = this.bnodeContext(bnodes, doc);
919
- var whereClause = this.contextWhere(context);
920
- var query = '';
921
-
922
- if (whereClause.length) {
923
- // Is there a WHERE clause?
924
- if (ds.length) {
925
- query += 'DELETE { ';
926
-
927
- for (var i = 0; i < ds.length; i++) {
928
- query += this.anonymizeNT(ds[i]) + '\n';
929
- }
930
-
931
- query += ' }\n';
932
- }
933
-
934
- if (is.length) {
935
- query += 'INSERT { ';
936
-
937
- for (var _i5 = 0; _i5 < is.length; _i5++) {
938
- query += this.anonymizeNT(is[_i5]) + '\n';
939
- }
940
-
941
- query += ' }\n';
942
- }
943
-
944
- query += whereClause;
717
+ // console.log(`Update: have not loaded ${doc} before: loading now...`);
718
+ this.store.fetcher.load(doc).then(response => {
719
+ this.update(deletions, insertions, callback, true, options);
720
+ }, err => {
721
+ if (err.response.status === 404) {
722
+ // nonexistent files are fine
723
+ this.update(deletions, insertions, callback, true, options);
945
724
  } else {
946
- // no where clause
947
- if (ds.length) {
948
- query += 'DELETE DATA { ';
949
-
950
- for (var _i6 = 0; _i6 < ds.length; _i6++) {
951
- query += this.anonymizeNT(ds[_i6]) + '\n';
952
- }
953
-
954
- query += ' } \n';
725
+ throw new Error(`Update: Can't get updatability status ${doc} before patching: ${err}`);
726
+ }
727
+ });
728
+ return;
729
+ } else if (protocol.indexOf('SPARQL') >= 0) {
730
+ var bnodes = [];
731
+ // change ReadOnly type to Mutable type
732
+
733
+ if (ds.length) bnodes = this.statementArrayBnodes(ds);
734
+ if (is.length) bnodes = bnodes.concat(this.statementArrayBnodes(is));
735
+ var context = this.bnodeContext(bnodes, doc);
736
+ var whereClause = this.contextWhere(context);
737
+ var query = '';
738
+ if (whereClause.length) {
739
+ // Is there a WHERE clause?
740
+ if (ds.length) {
741
+ query += 'DELETE { ';
742
+ for (let i = 0; i < ds.length; i++) {
743
+ query += this.anonymizeNT(ds[i]) + '\n';
955
744
  }
956
-
957
- if (is.length) {
958
- if (ds.length) query += ' ; ';
959
- query += 'INSERT DATA { ';
960
-
961
- for (var _i7 = 0; _i7 < is.length; _i7++) {
962
- query += this.nTriples(is[_i7]) + '\n';
963
- }
964
-
965
- query += ' }\n';
745
+ query += ' }\n';
746
+ }
747
+ if (is.length) {
748
+ query += 'INSERT { ';
749
+ for (let i = 0; i < is.length; i++) {
750
+ query += this.anonymizeNT(is[i]) + '\n';
966
751
  }
967
- } // Track pending upstream patches until they have finished their callbackFunction
968
-
969
-
970
- control.pendingUpstream = control.pendingUpstream ? control.pendingUpstream + 1 : 1;
971
-
972
- if ('upstreamCount' in control) {
973
- control.upstreamCount += 1; // count changes we originated ourselves
974
- // console.log('upstream count up to : ' + control.upstreamCount)
752
+ query += ' }\n';
975
753
  }
976
-
977
- this.fire(doc.value, query, function (uri, success, body, response) {
978
- response.elapsedTimeMs = Date.now() - startTime;
979
- /* console.log(' UpdateManager: Return ' +
980
- (success ? 'success ' : 'FAILURE ') + (response as Response).status +
981
- ' elapsed ' + (response as any).elapsedTimeMs + 'ms')
982
- */
983
-
984
- if (success) {
985
- try {
986
- kb.remove(ds);
987
- } catch (e) {
988
- success = false;
989
- body = 'Remote Ok BUT error deleting ' + ds.length + ' from store!!! ' + e;
990
- } // Add in any case -- help recover from weirdness??
991
-
992
-
993
- for (var _i8 = 0; _i8 < is.length; _i8++) {
994
- kb.add(is[_i8].subject, is[_i8].predicate, is[_i8].object, doc);
995
- }
754
+ query += whereClause;
755
+ } else {
756
+ // no where clause
757
+ if (ds.length) {
758
+ query += 'DELETE DATA { ';
759
+ for (let i = 0; i < ds.length; i++) {
760
+ query += this.anonymizeNT(ds[i]) + '\n';
996
761
  }
997
-
998
- callback(uri, success, body, response);
999
- control.pendingUpstream -= 1; // When upstream patches have been sent, reload state if downstream waiting
1000
-
1001
- if (control.pendingUpstream === 0 && control.downstreamAction) {
1002
- var downstreamAction = control.downstreamAction;
1003
- delete control.downstreamAction; // console.log('delayed downstream action:')
1004
-
1005
- downstreamAction(doc);
762
+ query += ' } \n';
763
+ }
764
+ if (is.length) {
765
+ if (ds.length) query += ' ; ';
766
+ query += 'INSERT DATA { ';
767
+ for (let i = 0; i < is.length; i++) {
768
+ query += this.nTriples(is[i]) + '\n';
1006
769
  }
1007
- }, options);
1008
- } else if (protocol.indexOf('DAV') >= 0) {
1009
- this.updateDav(doc, ds, is, callback, options);
1010
- } else {
1011
- if (protocol.indexOf('LOCALFILE') >= 0) {
770
+ query += ' }\n';
771
+ }
772
+ }
773
+ // Track pending upstream patches until they have finished their callbackFunction
774
+ control.pendingUpstream = control.pendingUpstream ? control.pendingUpstream + 1 : 1;
775
+ if ('upstreamCount' in control) {
776
+ control.upstreamCount += 1; // count changes we originated ourselves
777
+ // console.log('upstream count up to : ' + control.upstreamCount)
778
+ }
779
+
780
+ this.fire(doc.value, query, (uri, success, body, response) => {
781
+ response.elapsedTimeMs = Date.now() - startTime;
782
+ /* console.log(' UpdateManager: Return ' +
783
+ (success ? 'success ' : 'FAILURE ') + (response as Response).status +
784
+ ' elapsed ' + (response as any).elapsedTimeMs + 'ms')
785
+ */
786
+ if (success) {
1012
787
  try {
1013
- this.updateLocalFile(doc, ds, is, callback, options);
788
+ kb.remove(ds);
1014
789
  } catch (e) {
1015
- callback(doc.value, false, 'Exception trying to write back file <' + doc.value + '>\n' // + tabulator.Util.stackString(e))
1016
- );
790
+ success = false;
791
+ body = 'Remote Ok BUT error deleting ' + ds.length + ' from store!!! ' + e;
792
+ } // Add in any case -- help recover from weirdness??
793
+ for (let i = 0; i < is.length; i++) {
794
+ kb.add(is[i].subject, is[i].predicate, is[i].object, doc);
1017
795
  }
1018
- } else {
1019
- throw new Error("Unhandled edit method: '" + protocol + "' for " + doc);
1020
796
  }
797
+ callback(uri, success, body, response);
798
+ control.pendingUpstream -= 1;
799
+ // When upstream patches have been sent, reload state if downstream waiting
800
+ if (control.pendingUpstream === 0 && control.downstreamAction) {
801
+ var downstreamAction = control.downstreamAction;
802
+ delete control.downstreamAction;
803
+ // console.log('delayed downstream action:')
804
+ downstreamAction(doc);
805
+ }
806
+ }, options);
807
+ } else if (protocol.indexOf('DAV') >= 0) {
808
+ this.updateDav(doc, ds, is, callback, options);
809
+ } else {
810
+ if (protocol.indexOf('LOCALFILE') >= 0) {
811
+ try {
812
+ this.updateLocalFile(doc, ds, is, callback, options);
813
+ } catch (e) {
814
+ callback(doc.value, false, 'Exception trying to write back file <' + doc.value + '>\n'
815
+ // + tabulator.Util.stackString(e))
816
+ );
817
+ }
818
+ } else {
819
+ throw new Error("Unhandled edit method: '" + protocol + "' for " + doc);
1021
820
  }
1022
- } catch (e) {
1023
- callback(undefined, false, 'Exception in update: ' + e + '\n' + Util.stackString(e));
1024
821
  }
822
+ } catch (e) {
823
+ callback(undefined, false, 'Exception in update: ' + e + '\n' + Util.stackString(e));
824
+ }
825
+ }
826
+ updateDav(doc, ds, is, callbackFunction) {
827
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
828
+ let kb = this.store;
829
+ // The code below is derived from Kenny's UpdateCenter.js
830
+ var request = kb.any(doc, this.ns.link('request'));
831
+ if (!request) {
832
+ throw new Error('No record of our HTTP GET request for document: ' + doc);
833
+ } // should not happen
834
+ var response = kb.any(request, this.ns.link('response'));
835
+ if (!response) {
836
+ return null; // throw "No record HTTP GET response for document: "+doc
1025
837
  }
1026
- }, {
1027
- key: "updateDav",
1028
- value: function updateDav(doc, ds, is, callbackFunction) {
1029
- var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
1030
- var kb = this.store; // The code below is derived from Kenny's UpdateCenter.js
1031
-
1032
- var request = kb.any(doc, this.ns.link('request'));
1033
-
1034
- if (!request) {
1035
- throw new Error('No record of our HTTP GET request for document: ' + doc);
1036
- } // should not happen
1037
-
1038
-
1039
- var response = kb.any(request, this.ns.link('response'));
1040
-
1041
- if (!response) {
1042
- return null; // throw "No record HTTP GET response for document: "+doc
1043
- }
1044
838
 
1045
- var contentType = kb.the(response, this.ns.httph('content-type')).value; // prepare contents of revised document
839
+ var contentType = kb.the(response, this.ns.httph('content-type')).value;
1046
840
 
1047
- var newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy!
841
+ // prepare contents of revised document
842
+ let newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy!
843
+ for (let i = 0; i < ds.length; i++) {
844
+ Util.RDFArrayRemove(newSts, ds[i]);
845
+ }
846
+ for (let i = 0; i < is.length; i++) {
847
+ newSts.push(is[i]);
848
+ }
849
+ const documentString = this.serialize(doc.value, newSts, contentType);
1048
850
 
1049
- for (var i = 0; i < ds.length; i++) {
1050
- Util.RDFArrayRemove(newSts, ds[i]);
851
+ // Write the new version back
852
+ var candidateTarget = kb.the(response, this.ns.httph('content-location'));
853
+ var targetURI;
854
+ if (candidateTarget) {
855
+ targetURI = (0, _uri.join)(candidateTarget.value, targetURI);
856
+ }
857
+ options.contentType = contentType;
858
+ options.noMeta = true;
859
+ options.body = documentString;
860
+ return kb.fetcher.webOperation('PUT', targetURI, options).then(response => {
861
+ if (!response.ok) {
862
+ throw new Error(response.error);
1051
863
  }
1052
-
1053
- for (var _i9 = 0; _i9 < is.length; _i9++) {
1054
- newSts.push(is[_i9]);
864
+ for (let i = 0; i < ds.length; i++) {
865
+ kb.remove(ds[i]);
1055
866
  }
1056
-
1057
- var documentString = this.serialize(doc.value, newSts, contentType); // Write the new version back
1058
-
1059
- var candidateTarget = kb.the(response, this.ns.httph('content-location'));
1060
- var targetURI;
1061
-
1062
- if (candidateTarget) {
1063
- targetURI = (0, _uri.join)(candidateTarget.value, targetURI);
867
+ for (let i = 0; i < is.length; i++) {
868
+ kb.add(is[i].subject, is[i].predicate, is[i].object, doc);
1064
869
  }
870
+ callbackFunction(doc.value, response.ok, response.responseText, response);
871
+ }).catch(err => {
872
+ callbackFunction(doc.value, false, err.message, err);
873
+ });
874
+ }
1065
875
 
1066
- options.contentType = contentType;
1067
- options.noMeta = true;
1068
- options.body = documentString;
1069
- return kb.fetcher.webOperation('PUT', targetURI, options).then(function (response) {
1070
- if (!response.ok) {
1071
- throw new Error(response.error);
1072
- }
1073
-
1074
- for (var _i10 = 0; _i10 < ds.length; _i10++) {
1075
- kb.remove(ds[_i10]);
1076
- }
1077
-
1078
- for (var _i11 = 0; _i11 < is.length; _i11++) {
1079
- kb.add(is[_i11].subject, is[_i11].predicate, is[_i11].object, doc);
1080
- }
1081
-
1082
- callbackFunction(doc.value, response.ok, response.responseText, response);
1083
- }).catch(function (err) {
1084
- callbackFunction(doc.value, false, err.message, err);
1085
- });
876
+ /**
877
+ * Likely deprecated, since this lib no longer deals with browser extension
878
+ *
879
+ * @param doc
880
+ * @param ds
881
+ * @param is
882
+ * @param callbackFunction
883
+ * @param options
884
+ */
885
+ updateLocalFile(doc, ds, is, callbackFunction) {
886
+ let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
887
+ const kb = this.store;
888
+ // console.log('Writing back to local file\n')
889
+
890
+ // prepare contents of revised document
891
+ let newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy!
892
+
893
+ for (let i = 0; i < ds.length; i++) {
894
+ Util.RDFArrayRemove(newSts, ds[i]);
1086
895
  }
1087
- /**
1088
- * Likely deprecated, since this lib no longer deals with browser extension
1089
- *
1090
- * @param doc
1091
- * @param ds
1092
- * @param is
1093
- * @param callbackFunction
1094
- * @param options
1095
- */
1096
-
1097
- }, {
1098
- key: "updateLocalFile",
1099
- value: function updateLocalFile(doc, ds, is, callbackFunction) {
1100
- var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
1101
- var kb = this.store; // console.log('Writing back to local file\n')
1102
- // prepare contents of revised document
1103
-
1104
- var newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy!
1105
-
1106
- for (var i = 0; i < ds.length; i++) {
1107
- Util.RDFArrayRemove(newSts, ds[i]);
1108
- }
1109
-
1110
- for (var _i12 = 0; _i12 < is.length; _i12++) {
1111
- newSts.push(is[_i12]);
1112
- } // serialize to the appropriate format
1113
-
1114
-
1115
- var dot = doc.value.lastIndexOf('.');
1116
-
1117
- if (dot < 1) {
1118
- throw new Error('Rewriting file: No filename extension: ' + doc.value);
896
+ for (let i = 0; i < is.length; i++) {
897
+ newSts.push(is[i]);
898
+ }
899
+ // serialize to the appropriate format
900
+ var dot = doc.value.lastIndexOf('.');
901
+ if (dot < 1) {
902
+ throw new Error('Rewriting file: No filename extension: ' + doc.value);
903
+ }
904
+ var ext = doc.value.slice(dot + 1);
905
+ let contentType = _fetcher.default.CONTENT_TYPE_BY_EXT[ext];
906
+ if (!contentType) {
907
+ throw new Error('File extension .' + ext + ' not supported for data write');
908
+ }
909
+ options.body = this.serialize(doc.value, newSts, contentType);
910
+ options.contentType = contentType;
911
+ kb.fetcher.webOperation('PUT', doc.value, options).then(response => {
912
+ if (!response.ok) return callbackFunction(doc.value, false, response.error);
913
+ for (let i = 0; i < ds.length; i++) {
914
+ kb.remove(ds[i]);
1119
915
  }
1120
-
1121
- var ext = doc.value.slice(dot + 1);
1122
- var contentType = _fetcher.default.CONTENT_TYPE_BY_EXT[ext];
1123
-
1124
- if (!contentType) {
1125
- throw new Error('File extension .' + ext + ' not supported for data write');
916
+ for (let i = 0; i < is.length; i++) {
917
+ kb.add(is[i].subject, is[i].predicate, is[i].object, doc);
1126
918
  }
919
+ callbackFunction(doc.value, true, ''); // success!
920
+ });
921
+ }
1127
922
 
1128
- options.body = this.serialize(doc.value, newSts, contentType);
1129
- options.contentType = contentType;
1130
- kb.fetcher.webOperation('PUT', doc.value, options).then(function (response) {
1131
- if (!response.ok) return callbackFunction(doc.value, false, response.error);
1132
-
1133
- for (var _i13 = 0; _i13 < ds.length; _i13++) {
1134
- kb.remove(ds[_i13]);
1135
- }
1136
-
1137
- for (var _i14 = 0; _i14 < is.length; _i14++) {
1138
- kb.add(is[_i14].subject, is[_i14].predicate, is[_i14].object, doc);
1139
- }
1140
-
1141
- callbackFunction(doc.value, true, ''); // success!
1142
- });
923
+ /**
924
+ * @throws {Error} On unsupported content type
925
+ *
926
+ * @returns {string}
927
+ */
928
+ serialize(uri, data, contentType) {
929
+ const kb = this.store;
930
+ let documentString;
931
+ if (typeof data === 'string') {
932
+ return data;
1143
933
  }
1144
- /**
1145
- * @throws {Error} On unsupported content type
1146
- *
1147
- * @returns {string}
1148
- */
1149
-
1150
- }, {
1151
- key: "serialize",
1152
- value: function serialize(uri, data, contentType) {
1153
- var kb = this.store;
1154
- var documentString;
1155
-
1156
- if (typeof data === 'string') {
1157
- return data;
1158
- } // serialize to the appropriate format
1159
-
1160
-
1161
- var sz = (0, _serializer.default)(kb);
1162
- sz.suggestNamespaces(kb.namespaces);
1163
- sz.setBase(uri);
1164
-
1165
- switch (contentType) {
1166
- case 'text/xml':
1167
- case 'application/rdf+xml':
1168
- documentString = sz.statementsToXML(data);
1169
- break;
1170
-
1171
- case 'text/n3':
1172
- case 'text/turtle':
1173
- case 'application/x-turtle': // Legacy
1174
-
1175
- case 'application/n3':
1176
- // Legacy
1177
- documentString = sz.statementsToN3(data);
1178
- break;
1179
-
1180
- default:
1181
- throw new Error('Content-type ' + contentType + ' not supported for data serialization');
1182
- }
1183
934
 
1184
- return documentString;
935
+ // serialize to the appropriate format
936
+ var sz = (0, _serializer.default)(kb);
937
+ sz.suggestNamespaces(kb.namespaces);
938
+ sz.setBase(uri);
939
+ switch (contentType) {
940
+ case 'text/xml':
941
+ case 'application/rdf+xml':
942
+ documentString = sz.statementsToXML(data);
943
+ break;
944
+ case 'text/n3':
945
+ case 'text/turtle':
946
+ case 'application/x-turtle': // Legacy
947
+ case 'application/n3':
948
+ // Legacy
949
+ documentString = sz.statementsToN3(data);
950
+ break;
951
+ default:
952
+ throw new Error('Content-type ' + contentType + ' not supported for data serialization');
1185
953
  }
1186
- /**
1187
- * This is suitable for an initial creation of a document.
1188
- */
1189
-
1190
- }, {
1191
- key: "put",
1192
- value: function put(doc, data, contentType, callback) {
1193
- var _this4 = this;
1194
-
1195
- var kb = this.store;
1196
- var documentString;
1197
- return Promise.resolve().then(function () {
1198
- documentString = _this4.serialize(doc.value, data, contentType);
1199
- return kb.fetcher.webOperation('PUT', doc.value, {
1200
- contentType: contentType,
1201
- body: documentString
1202
- });
1203
- }).then(function (response) {
1204
- if (!response.ok) {
1205
- return callback(doc.value, response.ok, response.error, response);
1206
- }
1207
-
1208
- delete kb.fetcher.nonexistent[doc.value];
1209
- delete kb.fetcher.requested[doc.value]; // @@ could this mess with the requested state machine? if a fetch is in progress
1210
-
1211
- if (typeof data !== 'string') {
1212
- data.map(function (st) {
1213
- kb.addStatement(st);
1214
- });
1215
- }
954
+ return documentString;
955
+ }
1216
956
 
1217
- callback(doc.value, response.ok, '', response);
1218
- }).catch(function (err) {
1219
- callback(doc.value, false, err.message);
957
+ /**
958
+ * This is suitable for an initial creation of a document.
959
+ */
960
+ put(doc, data, contentType, callback) {
961
+ const kb = this.store;
962
+ let documentString;
963
+ return Promise.resolve().then(() => {
964
+ documentString = this.serialize(doc.value, data, contentType);
965
+ return kb.fetcher.webOperation('PUT', doc.value, {
966
+ contentType,
967
+ body: documentString
1220
968
  });
1221
- }
1222
- /**
1223
- * Reloads a document.
1224
- *
1225
- * Fast and cheap, no metadata. Measure times for the document.
1226
- * Load it provisionally.
1227
- * Don't delete the statements before the load, or it will leave a broken
1228
- * document in the meantime.
1229
- *
1230
- * @param kb
1231
- * @param doc {RDFlibNamedNode}
1232
- * @param callbackFunction
1233
- */
969
+ }).then(response => {
970
+ if (!response.ok) {
971
+ return callback(doc.value, response.ok, response.error, response);
972
+ }
973
+ delete kb.fetcher.nonexistent[doc.value];
974
+ delete kb.fetcher.requested[doc.value]; // @@ could this mess with the requested state machine? if a fetch is in progress
1234
975
 
1235
- }, {
1236
- key: "reload",
1237
- value: function reload(kb, doc, callbackFunction) {
1238
- var startTime = Date.now(); // force sets no-cache and
976
+ if (typeof data !== 'string') {
977
+ data.map(st => {
978
+ kb.addStatement(st);
979
+ });
980
+ }
981
+ callback(doc.value, response.ok, '', response);
982
+ }).catch(err => {
983
+ callback(doc.value, false, err.message);
984
+ });
985
+ }
1239
986
 
1240
- var options = {
1241
- force: true,
1242
- noMeta: true,
1243
- clearPreviousData: true
1244
- };
1245
- kb.fetcher.nowOrWhenFetched(doc.value, options, function (ok, body, response) {
1246
- if (!ok) {
1247
- // console.log(' ERROR reloading data: ' + body)
1248
- callbackFunction(false, 'Error reloading data: ' + body, response); //@ts-ignore Where does onErrorWasCalled come from?
1249
- } else if (response.onErrorWasCalled || response.status !== 200) {
1250
- // console.log(' Non-HTTP error reloading data! onErrorWasCalled=' +
1251
- //@ts-ignore Where does onErrorWasCalled come from?
1252
- // response.onErrorWasCalled + ' status: ' + response.status)
1253
- callbackFunction(false, 'Non-HTTP error reloading data: ' + body, response);
1254
- } else {
1255
- var elapsedTimeMs = Date.now() - startTime;
1256
- if (!doc.reloadTimeTotal) doc.reloadTimeTotal = 0;
1257
- if (!doc.reloadTimeCount) doc.reloadTimeCount = 0;
1258
- doc.reloadTimeTotal += elapsedTimeMs;
1259
- doc.reloadTimeCount += 1; // console.log(' Fetch took ' + elapsedTimeMs + 'ms, av. of ' +
1260
- // doc.reloadTimeCount + ' = ' +
1261
- // (doc.reloadTimeTotal / doc.reloadTimeCount) + 'ms.')
987
+ /**
988
+ * Reloads a document.
989
+ *
990
+ * Fast and cheap, no metadata. Measure times for the document.
991
+ * Load it provisionally.
992
+ * Don't delete the statements before the load, or it will leave a broken
993
+ * document in the meantime.
994
+ *
995
+ * @param kb
996
+ * @param doc {RDFlibNamedNode}
997
+ * @param callbackFunction
998
+ */
999
+ reload(kb, doc, callbackFunction) {
1000
+ var startTime = Date.now();
1001
+ // force sets no-cache and
1002
+ const options = {
1003
+ force: true,
1004
+ noMeta: true,
1005
+ clearPreviousData: true
1006
+ };
1007
+ kb.fetcher.nowOrWhenFetched(doc.value, options, function (ok, body, response) {
1008
+ if (!ok) {
1009
+ // console.log(' ERROR reloading data: ' + body)
1010
+ callbackFunction(false, 'Error reloading data: ' + body, response);
1011
+ //@ts-ignore Where does onErrorWasCalled come from?
1012
+ } else if (response.onErrorWasCalled || response.status !== 200) {
1013
+ // console.log(' Non-HTTP error reloading data! onErrorWasCalled=' +
1014
+ //@ts-ignore Where does onErrorWasCalled come from?
1015
+ // response.onErrorWasCalled + ' status: ' + response.status)
1016
+ callbackFunction(false, 'Non-HTTP error reloading data: ' + body, response);
1017
+ } else {
1018
+ var elapsedTimeMs = Date.now() - startTime;
1019
+ if (!doc.reloadTimeTotal) doc.reloadTimeTotal = 0;
1020
+ if (!doc.reloadTimeCount) doc.reloadTimeCount = 0;
1021
+ doc.reloadTimeTotal += elapsedTimeMs;
1022
+ doc.reloadTimeCount += 1;
1262
1023
 
1263
- callbackFunction(true);
1264
- }
1265
- });
1266
- }
1267
- }]);
1268
- return UpdateManager;
1269
- }();
1024
+ // console.log(' Fetch took ' + elapsedTimeMs + 'ms, av. of ' +
1025
+ // doc.reloadTimeCount + ' = ' +
1026
+ // (doc.reloadTimeTotal / doc.reloadTimeCount) + 'ms.')
1270
1027
 
1028
+ callbackFunction(true);
1029
+ }
1030
+ });
1031
+ }
1032
+ }
1271
1033
  exports.default = UpdateManager;