From 8924ae81610399e968faf5b83a2f5669db70c87c Mon Sep 17 00:00:00 2001 From: bourgeoa Date: Sun, 16 Apr 2023 13:28:51 +0200 Subject: [PATCH] update dependencies --- dist/solid-ui.js | 115315 ++++++++++++---------------- dist/solid-ui.js.map | 2 +- dist/solid-ui.min.js | 2 +- dist/solid-ui.min.js.LICENSE.txt | 63 - dist/solid-ui.min.js.map | 2 +- package-lock.json | 1212 +- package.json | 9 +- test/helpers/setup.ts | 1 + 8 files changed, 50184 insertions(+), 66422 deletions(-) diff --git a/dist/solid-ui.js b/dist/solid-ui.js index 56469a208..e43863945 100644 --- a/dist/solid-ui.js +++ b/dist/solid-ui.js @@ -11,40974 +11,25056 @@ return /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ "../rdflib/esm/blank-node.js": -/*!***********************************!*\ - !*** ../rdflib/esm/blank-node.js ***! - \***********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./lib/acl/access-controller.js": +/*!**************************************!*\ + !*** ./lib/acl/access-controller.js ***! + \**************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ BlankNode) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); - - - - - - - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.AccessController = void 0; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); +var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); +var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); +var _acl = __webpack_require__(/*! ./acl */ "./lib/acl/acl.js"); +var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); +var _accessGroups = __webpack_require__(/*! ./access-groups */ "./lib/acl/access-groups.js"); +var _aclControl = __webpack_require__(/*! ./acl-control */ "./lib/acl/acl-control.js"); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); +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); } +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; } /** - * An RDF blank node is a Node without a URI - * @link https://rdf.js.org/data-model-spec/#blanknode-interface + * Contains the [[AccessController]] class + * @packageDocumentation */ -var BlankNode = /*#__PURE__*/function (_Node) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(BlankNode, _Node); - var _super = _createSuper(BlankNode); - /** - * Initializes this node - * @param [id] The identifier for the blank node - */ - function BlankNode(id) { - var _this; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, BlankNode); - _this = _super.call(this, BlankNode.getId(id)); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.BlankNodeTermType); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_8__["default"].BlankNode); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isBlank", 1); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 1); - return _this; +/** + * Rendered HTML component used in the databrowser's Sharing pane. + */ +var AccessController = /*#__PURE__*/function () { + function AccessController(subject, noun, context, statusElement, targetIsProtected, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc, prospectiveDefaultHolder, store, dom) { + (0, _classCallCheck2["default"])(this, AccessController); + this.subject = subject; + this.noun = noun; + this.context = context; + this.statusElement = statusElement; + this.targetIsProtected = targetIsProtected; + this.targetDoc = targetDoc; + this.targetACLDoc = targetACLDoc; + this.defaultHolder = defaultHolder; + this.defaultACLDoc = defaultACLDoc; + this.prospectiveDefaultHolder = prospectiveDefaultHolder; + this.store = store; + this.dom = dom; + (0, _defineProperty2["default"])(this, "mainCombo", void 0); + (0, _defineProperty2["default"])(this, "defaultsCombo", void 0); + (0, _defineProperty2["default"])(this, "isContainer", void 0); + (0, _defineProperty2["default"])(this, "defaultsDiffer", void 0); + (0, _defineProperty2["default"])(this, "rootElement", void 0); + (0, _defineProperty2["default"])(this, "isUsingDefaults", void 0); + this.rootElement = dom.createElement('div'); + this.rootElement.setAttribute('style', style.aclGroupContent); + this.isContainer = targetDoc.uri.slice(-1) === '/'; // Give default for all directories + if (defaultHolder && defaultACLDoc) { + this.isUsingDefaults = true; + var aclDefaultStore = (0, _acl.adoptACLDefault)(this.targetDoc, targetACLDoc, defaultHolder, defaultACLDoc); + this.mainCombo = new _accessGroups.AccessGroups(targetDoc, targetACLDoc, this, aclDefaultStore, { + defaults: this.isContainer + }); + this.defaultsCombo = null; + this.defaultsDiffer = false; + } else { + this.isUsingDefaults = false; + this.mainCombo = new _accessGroups.AccessGroups(targetDoc, targetACLDoc, this, store); + this.defaultsCombo = new _accessGroups.AccessGroups(targetDoc, targetACLDoc, this, store, { + defaults: this.isContainer + }); + this.defaultsDiffer = !(0, _acl.sameACL)(this.mainCombo.aclMap, this.defaultsCombo.aclMap); + } } - - /** - * The identifier for the blank node - */ - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(BlankNode, [{ - key: "id", + (0, _createClass2["default"])(AccessController, [{ + key: "isEditable", get: function get() { - return this.value; - }, - set: function set(value) { - this.value = value; + return !this.isUsingDefaults; } }, { - key: "compareTerm", - value: function compareTerm(other) { - if (this.classOrder < other.classOrder) { - return -1; - } - if (this.classOrder > other.classOrder) { - return +1; + key: "render", + value: function render() { + this.rootElement.innerHTML = ''; + if (this.isUsingDefaults) { + this.renderStatus("The sharing for this ".concat(this.noun, " is the default for folder ")); + if (this.defaultHolder) { + var defaultHolderLink = this.statusElement.appendChild(this.dom.createElement('a')); + defaultHolderLink.href = this.defaultHolder.uri; + defaultHolderLink.innerText = (0, _aclControl.shortNameForFolder)(this.defaultHolder); + } + } else if (!this.defaultsDiffer && this.isContainer) { + this.renderStatus('This is also the default for things in this folder.'); + } else { + this.renderStatus(''); } - if (this.id < other.id) { - return -1; + this.rootElement.appendChild(this.mainCombo.render()); + if (this.defaultsCombo && this.defaultsDiffer) { + this.rootElement.appendChild(this.renderRemoveDefaultsController()); + this.rootElement.appendChild(this.defaultsCombo.render()); + } else if (this.isEditable && this.isContainer) { + this.rootElement.appendChild(this.renderAddDefaultsController()); } - if (this.id > other.id) { - return +1; + if (!this.targetIsProtected && this.isUsingDefaults) { + this.rootElement.appendChild(this.renderAddAclsController()); + } else if (!this.targetIsProtected) { + this.rootElement.appendChild(this.renderRemoveAclsController()); } - return 0; + return this.rootElement; } - - /** - * Gets a copy of this blank node in the specified formula - * @param formula The formula - */ }, { - key: "copy", - value: function copy(formula) { - // depends on the formula - var bnodeNew = new BlankNode(); - formula.copyTo(this, bnodeNew); - return bnodeNew; + key: "renderRemoveAclsController", + value: function renderRemoveAclsController() { + var _this = this; + var useDefaultButton = this.dom.createElement('button'); + useDefaultButton.innerText = "Remove custom sharing settings for this ".concat(this.noun, " -- just use default").concat(this.prospectiveDefaultHolder ? " for ".concat(utils.label(this.prospectiveDefaultHolder)) : ''); + useDefaultButton.setAttribute('style', style.bigButton); + useDefaultButton.addEventListener('click', function () { + return _this.removeAcls().then(function () { + return _this.render(); + })["catch"](function (error) { + return _this.renderStatus(error); + }); + }); + return useDefaultButton; } }, { - key: "toCanonical", - value: function toCanonical() { - return BlankNode.NTAnonymousNodePrefix + this.value; + key: "renderAddAclsController", + value: function renderAddAclsController() { + var _this2 = this; + var addAclButton = this.dom.createElement('button'); + addAclButton.innerText = "Set specific sharing for this ".concat(this.noun); + addAclButton.setAttribute('style', style.bigButton); + addAclButton.addEventListener('click', function () { + return _this2.addAcls().then(function () { + return _this2.render(); + })["catch"](function (error) { + return _this2.renderStatus(error); + }); + }); + return addAclButton; } }, { - key: "toString", - value: function toString() { - return BlankNode.NTAnonymousNodePrefix + this.id; + key: "renderAddDefaultsController", + value: function renderAddDefaultsController() { + var _this3 = this; + var containerElement = this.dom.createElement('div'); + containerElement.setAttribute('style', style.defaultsController); + var noticeElement = containerElement.appendChild(this.dom.createElement('div')); + noticeElement.innerText = 'Sharing for things within the folder currently tracks sharing for the folder.'; + noticeElement.setAttribute('style', style.defaultsControllerNotice); + var button = containerElement.appendChild(this.dom.createElement('button')); + button.innerText = 'Set the sharing of folder contents separately from the sharing for the folder'; + button.setAttribute('style', style.bigButton); + button.addEventListener('click', function () { + return _this3.addDefaults().then(function () { + return _this3.render(); + }); + }); + return containerElement; } - }], [{ - key: "getId", - value: - /** - * The next unique identifier for blank nodes - */ - - function getId(id) { - if (id) { - if (typeof id !== 'string') { - throw new Error('Bad id argument to new blank node: ' + id); - } - if (id.includes('#')) { - // Is a URI with hash fragment - var fragments = id.split('#'); - return fragments[fragments.length - 1]; - } - return id; + }, { + key: "renderRemoveDefaultsController", + value: function renderRemoveDefaultsController() { + var _this4 = this; + var containerElement = this.dom.createElement('div'); + containerElement.setAttribute('style', style.defaultsController); + var noticeElement = containerElement.appendChild(this.dom.createElement('div')); + noticeElement.innerText = 'Access to things within this folder:'; + noticeElement.setAttribute('style', style.defaultsControllerNotice); + var button = containerElement.appendChild(this.dom.createElement('button')); + button.innerText = 'Set default for folder contents to just track the sharing for the folder'; + button.setAttribute('style', style.bigButton); + button.addEventListener('click', function () { + return _this4.removeDefaults().then(function () { + return _this4.render(); + })["catch"](function (error) { + return _this4.renderStatus(error); + }); + }); + return containerElement; + } + }, { + key: "renderTemporaryStatus", + value: function renderTemporaryStatus(message) { + var _this5 = this; + // @@ TODO Introduce better system for error notification to user https://github.com/solidos/mashlib/issues/87 + this.statusElement.setAttribute('style', style.aclControlBoxStatusRevealed); + this.statusElement.innerText = message; + this.statusElement.setAttribute('style', style.temporaryStatusInit); + setTimeout(function () { + _this5.statusElement.setAttribute('style', style.temporaryStatusEnd); + }); + setTimeout(function () { + _this5.statusElement.innerText = ''; + }, 5000); + } + }, { + key: "renderStatus", + value: function renderStatus(message) { + // @@ TODO Introduce better system for error notification to user https://github.com/solidos/mashlib/issues/87 + if (!message) { + this.statusElement.setAttribute('style', style.aclControlBoxStatusRevealed); } - return 'n' + BlankNode.nextId++; + this.statusElement.innerText = message; } - }]); - return BlankNode; -}(_node_internal__WEBPACK_IMPORTED_MODULE_9__["default"]); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(BlankNode, "nextId", 0); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(BlankNode, "NTAnonymousNodePrefix", '_:'); - - -/***/ }), + }, { + key: "addAcls", + value: function () { + var _addAcls = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var _this6 = this; + var message, aclGraph, _message; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(!this.defaultHolder || !this.defaultACLDoc)) { + _context.next = 4; + break; + } + message = 'Unable to find defaults to copy'; + debug.error(message); + return _context.abrupt("return", Promise.reject(message)); + case 4: + aclGraph = (0, _acl.adoptACLDefault)(this.targetDoc, this.targetACLDoc, this.defaultHolder, this.defaultACLDoc); + aclGraph.statements.forEach(function (st) { + return _this6.store.add(st.subject, st.predicate, st.object, _this6.targetACLDoc); + }); + _context.prev = 6; + _context.next = 9; + return this.store.fetcher.putBack(this.targetACLDoc); + case 9: + this.isUsingDefaults = false; + return _context.abrupt("return", Promise.resolve()); + case 13: + _context.prev = 13; + _context.t0 = _context["catch"](6); + _message = " Error writing back access control file! ".concat(_context.t0); + debug.error(_message); + return _context.abrupt("return", Promise.reject(_message)); + case 18: + case "end": + return _context.stop(); + } + }, _callee, this, [[6, 13]]); + })); + function addAcls() { + return _addAcls.apply(this, arguments); + } + return addAcls; + }() + }, { + key: "addDefaults", + value: function () { + var _addDefaults = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + this.defaultsCombo = new _accessGroups.AccessGroups(this.targetDoc, this.targetACLDoc, this, this.store, { + defaults: true + }); + this.defaultsDiffer = true; + case 2: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function addDefaults() { + return _addDefaults.apply(this, arguments); + } + return addDefaults; + }() + }, { + key: "removeAcls", + value: function () { + var _removeAcls = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var message; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.prev = 0; + _context3.next = 3; + return this.store.fetcher["delete"](this.targetACLDoc.uri, {}); + case 3: + this.isUsingDefaults = true; + _context3.prev = 4; + _context3.next = 7; + return (0, _acl.getProspectiveHolder)(this.targetDoc.uri); + case 7: + this.prospectiveDefaultHolder = _context3.sent; + _context3.next = 13; + break; + case 10: + _context3.prev = 10; + _context3.t0 = _context3["catch"](4); + // No need to show this error in status, but good to warn about it in console + debug.warn(_context3.t0); + case 13: + _context3.next = 20; + break; + case 15: + _context3.prev = 15; + _context3.t1 = _context3["catch"](0); + message = "Error deleting access control file: ".concat(this.targetACLDoc, ": ").concat(_context3.t1); + debug.error(message); + return _context3.abrupt("return", Promise.reject(message)); + case 20: + case "end": + return _context3.stop(); + } + }, _callee3, this, [[0, 15], [4, 10]]); + })); + function removeAcls() { + return _removeAcls.apply(this, arguments); + } + return removeAcls; + }() + }, { + key: "removeDefaults", + value: function () { + var _removeDefaults = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var fallbackCombo; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + fallbackCombo = this.defaultsCombo; + _context4.prev = 1; + this.defaultsCombo = null; + this.defaultsDiffer = false; + _context4.next = 6; + return this.save(); + case 6: + _context4.next = 14; + break; + case 8: + _context4.prev = 8; + _context4.t0 = _context4["catch"](1); + this.defaultsCombo = fallbackCombo; + this.defaultsDiffer = true; + debug.error(_context4.t0); + return _context4.abrupt("return", Promise.reject(_context4.t0)); + case 14: + case "end": + return _context4.stop(); + } + }, _callee4, this, [[1, 8]]); + })); + function removeDefaults() { + return _removeDefaults.apply(this, arguments); + } + return removeDefaults; + }() + }, { + key: "save", + value: function save() { + var _this7 = this; + // build graph + var newAClGraph = (0, _rdflib.graph)(); + if (!this.isContainer) { + (0, _acl.makeACLGraphbyCombo)(newAClGraph, this.targetDoc, this.mainCombo.byCombo, this.targetACLDoc, true); + } else if (this.defaultsCombo && this.defaultsDiffer) { + // Pair of controls + (0, _acl.makeACLGraphbyCombo)(newAClGraph, this.targetDoc, this.mainCombo.byCombo, this.targetACLDoc, true); + (0, _acl.makeACLGraphbyCombo)(newAClGraph, this.targetDoc, this.defaultsCombo.byCombo, this.targetACLDoc, false, true); + } else { + // Linked controls + (0, _acl.makeACLGraphbyCombo)(newAClGraph, this.targetDoc, this.mainCombo.byCombo, this.targetACLDoc, true, true); + } -/***/ "../rdflib/esm/class-order.js": -/*!************************************!*\ - !*** ../rdflib/esm/class-order.js ***! - \************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + // add authenticated fetcher + newAClGraph.fetcher = (0, _rdflib.fetcher)(newAClGraph, { + fetch: this.store.fetcher._fetch + }); + var updater = newAClGraph.updater || new _rdflib.UpdateManager(newAClGraph); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/** -* Class orders -*/ -var ClassOrder = { - 'Literal': 1, - 'Collection': 3, - 'Graph': 4, - 'NamedNode': 5, - 'BlankNode': 6, - 'Variable': 7 -}; -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ClassOrder); + // save ACL resource + return new Promise(function (resolve, reject) { + updater.put(_this7.targetACLDoc, newAClGraph.statementsMatching(undefined, undefined, undefined, _this7.targetACLDoc), 'text/turtle', function (uri, ok, message) { + if (!ok) { + return reject(new Error("ACL file save failed: ".concat(message))); + } + _this7.store.fetcher.unload(_this7.targetACLDoc); + _this7.store.add(newAClGraph.statements); + _this7.store.fetcher.requested[_this7.targetACLDoc.uri] = 'done'; // missing: save headers + _this7.mainCombo.store = _this7.store; + if (_this7.defaultsCombo) { + _this7.defaultsCombo.store = _this7.store; + } + _this7.defaultsDiffer = !!_this7.defaultsCombo && !(0, _acl.sameACL)(_this7.mainCombo.aclMap, _this7.defaultsCombo.aclMap); + debug.log('ACL modification: success!'); + resolve(); + }); + }); + } + }]); + return AccessController; +}(); +exports.AccessController = AccessController; +//# sourceMappingURL=access-controller.js.map /***/ }), -/***/ "../rdflib/esm/collection.js": -/*!***********************************!*\ - !*** ../rdflib/esm/collection.js ***! - \***********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./lib/acl/access-groups.js": +/*!**********************************!*\ + !*** ./lib/acl/access-groups.js ***! + \**********************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Collection), -/* harmony export */ "fromValue": () => (/* binding */ fromValue) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./blank-node */ "../rdflib/esm/blank-node.js"); -/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); -/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./literal */ "../rdflib/esm/literal.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); - - - - - - - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - - - - -/** - * Creates an RDF Node from a native javascript value. - * RDF Nodes are returned unchanged, undefined returned as itself. - * Arrays return Collections. - * Strings, numbers and booleans return Literals. - * @param value {Node|Date|String|Number|Boolean|Undefined} - * @return {Node|Collection} - */ -function fromValue(value) { - if (typeof value === 'undefined' || value === null) { - return value; - } - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_7__.isTerm)(value)) { - // a Node subclass or a Collection - return value; - } - if (Array.isArray(value)) { - return new Collection(value); - } - return _literal__WEBPACK_IMPORTED_MODULE_8__["default"].fromValue(value); -} +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.AccessGroups = void 0; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "./node_modules/@babel/runtime/helpers/slicedToArray.js")); +var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); +var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); +var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); +var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); +var _acl = __webpack_require__(/*! ./acl */ "./lib/acl/acl.js"); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var _addAgentButtons = __webpack_require__(/*! ./add-agent-buttons */ "./lib/acl/add-agent-buttons.js"); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); +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); } +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; } +/** + * Contains the [[AccessGroups]] + * and [[AccessGroupsOptions]] classes + * @packageDocumentation + */ + +var ACL = ns.acl; +var COLLOQUIAL = { + 13: 'Owners', + 9: 'Owners (write locked)', + 5: 'Editors', + 3: 'Posters', + 2: 'Submitters', + 1: 'Viewers' +}; +var RECOMMENDED = { + 13: true, + 5: true, + 3: true, + 2: true, + 1: true +}; +var EXPLANATION = { + 13: 'can read, write, and control sharing.', + 9: 'can read and control sharing, currently write-locked.', + 5: 'can read and change information', + 3: 'can add new information, and read but not change existing information', + 2: 'can add new information but not read any', + 1: 'can read but not change information' +}; /** - * A collection of other RDF nodes - * - * Use generic T to control the contents of the array. + * Type for the options parameter of [[AccessGroups]] */ -var Collection = /*#__PURE__*/function (_Node) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Collection, _Node); - var _super = _createSuper(Collection); - /** - * The nodes in this collection - */ +/** + * Renders the table of Owners, Editors, Posters, Submitters, Viewers + * for https://github.com/solidos/userguide/blob/main/views/sharing/userguide.md + */ +var AccessGroups = /*#__PURE__*/function () { + // @@ was LiveStore but does not need to be connected to web - function Collection(initial) { - var _this; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Collection); - _this = _super.call(this, (_blank_node__WEBPACK_IMPORTED_MODULE_9__["default"].nextId++).toString()); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_10__.CollectionTermType); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_11__["default"].Collection); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "closed", false); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "compareTerm", _blank_node__WEBPACK_IMPORTED_MODULE_9__["default"].prototype.compareTerm); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "elements", []); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 0); - if (initial && initial.length > 0) { - initial.forEach(function (element) { - _this.elements.push(fromValue(element)); - }); - } - return _this; + function AccessGroups(doc, aclDoc, controller, store) { + var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + (0, _classCallCheck2["default"])(this, AccessGroups); + this.doc = doc; + this.aclDoc = aclDoc; + this.controller = controller; + this.options = options; + (0, _defineProperty2["default"])(this, "defaults", void 0); + (0, _defineProperty2["default"])(this, "byCombo", void 0); + (0, _defineProperty2["default"])(this, "aclMap", void 0); + (0, _defineProperty2["default"])(this, "addAgentButton", void 0); + (0, _defineProperty2["default"])(this, "rootElement", void 0); + (0, _defineProperty2["default"])(this, "_store", void 0); + this.defaults = options.defaults || false; + this._store = store; + this.aclMap = (0, _acl.readACL)(doc, aclDoc, store, this.defaults); + this.byCombo = (0, _acl.ACLbyCombination)(this.aclMap); + this.addAgentButton = new _addAgentButtons.AddAgentButtons(this); + this.rootElement = this.controller.dom.createElement('div'); + this.rootElement.setAttribute('style', style.accessGroupList); } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Collection, [{ - key: "id", + (0, _createClass2["default"])(AccessGroups, [{ + key: "store", get: function get() { - return this.value; + return this._store; }, - set: function set(value) { - this.value = value; + set: function set(store) { + this._store = store; + this.aclMap = (0, _acl.readACL)(this.doc, this.aclDoc, store, this.defaults); + this.byCombo = (0, _acl.ACLbyCombination)(this.aclMap); } - - /** - * Appends an element to this collection - * @param element - The new element - */ }, { - key: "append", - value: function append(element) { - return this.elements.push(element); + key: "render", + value: function render() { + var _this = this; + this.rootElement.innerHTML = ''; + this.renderGroups().forEach(function (group) { + return _this.rootElement.appendChild(group); + }); + if (this.controller.isEditable) { + this.rootElement.appendChild(this.addAgentButton.render()); + } + return this.rootElement; } - - /** - * Closes this collection - */ }, { - key: "close", - value: function close() { - this.closed = true; - return this.closed; + key: "renderGroups", + value: function renderGroups() { + var groupElements = []; + for (var comboIndex = 15; comboIndex > 0; comboIndex--) { + var combo = kToCombo(comboIndex); + if (this.controller.isEditable && RECOMMENDED[comboIndex] || this.byCombo[combo]) { + groupElements.push(this.renderGroup(comboIndex, combo)); + } + } + return groupElements; } - - /** - * Removes the first element from the collection (and return it) - */ }, { - key: "shift", - value: function shift() { - return this.elements.shift(); + key: "renderGroup", + value: function renderGroup(comboIndex, combo) { + var _this2 = this; + var groupRow = this.controller.dom.createElement('div'); + groupRow.setAttribute('style', style.accessGroupListItem); + widgets.makeDropTarget(groupRow, function (uris) { + return _this2.handleDroppedUris(uris, combo).then(function () { + return _this2.controller.render(); + })["catch"](function (error) { + return _this2.controller.renderStatus(error); + }); + }); + var groupColumns = this.renderGroupElements(comboIndex, combo); + groupColumns.forEach(function (column) { + return groupRow.appendChild(column); + }); + return groupRow; } - - /** - * Creates a new Collection with the substituting bindings applied - * @param bindings - The bindings to substitute - */ }, { - key: "substitute", - value: function substitute(bindings) { - var elementsCopy = this.elements.map(function (ea) { - return ea.substitute(bindings); + key: "renderGroupElements", + value: function renderGroupElements(comboIndex, combo) { + var _this3 = this; + var groupNameColumn = this.controller.dom.createElement('div'); + groupNameColumn.setAttribute('style', style.group); + if (this.controller.isEditable) { + switch (comboIndex) { + case 1: + groupNameColumn.setAttribute('style', style.group1); + break; + case 2: + groupNameColumn.setAttribute('style', style.group2); + break; + case 3: + groupNameColumn.setAttribute('style', style.group3); + break; + case 5: + groupNameColumn.setAttribute('style', style.group5); + break; + case 9: + groupNameColumn.setAttribute('style', style.group9); + break; + case 13: + groupNameColumn.setAttribute('style', style.group13); + break; + default: + groupNameColumn.setAttribute('style', style.group); + } + } + groupNameColumn.innerText = COLLOQUIAL[comboIndex] || ktToList(comboIndex); + var groupAgentsColumn = this.controller.dom.createElement('div'); + groupAgentsColumn.setAttribute('style', style.group); + if (this.controller.isEditable) { + switch (comboIndex) { + case 1: + groupAgentsColumn.setAttribute('style', style.group1); + break; + case 2: + groupAgentsColumn.setAttribute('style', style.group2); + break; + case 3: + groupAgentsColumn.setAttribute('style', style.group3); + break; + case 5: + groupAgentsColumn.setAttribute('style', style.group5); + break; + case 9: + groupAgentsColumn.setAttribute('style', style.group9); + break; + case 13: + groupAgentsColumn.setAttribute('style', style.group13); + break; + default: + groupAgentsColumn.setAttribute('style', style.group); + } + } + var groupAgentsTable = groupAgentsColumn.appendChild(this.controller.dom.createElement('table')); + var combos = this.byCombo[combo] || []; + combos.map(function (_ref) { + var _ref2 = (0, _slicedToArray2["default"])(_ref, 2), + pred = _ref2[0], + obj = _ref2[1]; + return _this3.renderAgent(groupAgentsTable, combo, pred, obj); + }).forEach(function (agentElement) { + return groupAgentsTable.appendChild(agentElement); }); - return new Collection(elementsCopy); + var groupDescriptionElement = this.controller.dom.createElement('div'); + groupDescriptionElement.setAttribute('style', style.group); + if (this.controller.isEditable) { + switch (comboIndex) { + case 1: + groupDescriptionElement.setAttribute('style', style.group1); + break; + case 2: + groupDescriptionElement.setAttribute('style', style.group2); + break; + case 3: + groupDescriptionElement.setAttribute('style', style.group3); + break; + case 5: + groupDescriptionElement.setAttribute('style', style.group5); + break; + case 9: + groupDescriptionElement.setAttribute('style', style.group9); + break; + case 13: + groupDescriptionElement.setAttribute('style', style.group13); + break; + default: + groupDescriptionElement.setAttribute('style', style.group); + } + } + groupDescriptionElement.innerText = EXPLANATION[comboIndex] || 'Unusual combination'; + return [groupNameColumn, groupAgentsColumn, groupDescriptionElement]; } }, { - key: "toNT", - value: function toNT() { - return Collection.toNT(this); + key: "renderAgent", + value: function renderAgent(groupAgentsTable, combo, pred, obj) { + var _this4 = this; + var personRow = widgets.personTR(this.controller.dom, ACL(pred), (0, _rdflib.sym)(obj), this.controller.isEditable ? { + deleteFunction: function deleteFunction() { + return _this4.deleteAgent(combo, pred, obj).then(function () { + return groupAgentsTable.removeChild(personRow); + })["catch"](function (error) { + return _this4.controller.renderStatus(error); + }); + } + } : {}); + return personRow; } }, { - key: "toString", - value: - /** - * Serializes the collection to a string. - * Surrounded by (parentheses) and separated by spaces. - */ - function toString() { - return '(' + this.elements.join(' ') + ')'; - } - - /** - * Prepends the specified element to the collection's front - * @param element - The element to prepend - */ + key: "deleteAgent", + value: function () { + var _deleteAgent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(combo, pred, obj) { + var combos, comboToRemove; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + combos = this.byCombo[combo] || []; + comboToRemove = combos.find(function (_ref3) { + var _ref4 = (0, _slicedToArray2["default"])(_ref3, 2), + comboPred = _ref4[0], + comboObj = _ref4[1]; + return comboPred === pred && comboObj === obj; + }); + if (comboToRemove) { + combos.splice(combos.indexOf(comboToRemove), 1); + } + _context.next = 5; + return this.controller.save(); + case 5: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function deleteAgent(_x, _x2, _x3) { + return _deleteAgent.apply(this, arguments); + } + return deleteAgent; + }() }, { - key: "unshift", - value: function unshift(element) { - return this.elements.unshift(element); - } - }], [{ - key: "toNT", - value: function toNT(collection) { - // return '(' + collection.elements.map(x => x.toNT()).join(' ') + ')' - // As lists are not in NT and toNT() must be a reversible function, we kludge it for a list - return _blank_node__WEBPACK_IMPORTED_MODULE_9__["default"].NTAnonymousNodePrefix + collection.id; - } - }]); - return Collection; -}(_node_internal__WEBPACK_IMPORTED_MODULE_12__["default"]); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Collection, "termType", _types__WEBPACK_IMPORTED_MODULE_10__.CollectionTermType); - - -/***/ }), - -/***/ "../rdflib/esm/default-graph.js": -/*!**************************************!*\ - !*** ../rdflib/esm/default-graph.js ***! - \**************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ DefaultGraph), -/* harmony export */ "isDefaultGraph": () => (/* binding */ isDefaultGraph) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/default-graph-uri */ "../rdflib/esm/utils/default-graph-uri.js"); - - - - - - - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - - - - -/** The RDF default graph */ -var DefaultGraph = /*#__PURE__*/function (_Node) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(DefaultGraph, _Node); - var _super = _createSuper(DefaultGraph); - function DefaultGraph() { - var _this; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, DefaultGraph); - _this = _super.call(this, ''); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "value", ''); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.DefaultGraphTermType); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "uri", _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_8__.defaultGraphURI); - return _this; - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(DefaultGraph, [{ - key: "toCanonical", - value: function toCanonical() { - return this.value; + key: "addNewURI", + value: function () { + var _addNewURI = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(uri) { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.handleDroppedUri(uri, kToCombo(1)); + case 2: + _context2.next = 4; + return this.controller.save(); + case 4: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function addNewURI(_x4) { + return _addNewURI.apply(this, arguments); + } + return addNewURI; + }() + }, { + key: "handleDroppedUris", + value: function () { + var _handleDroppedUris = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(uris, combo) { + var _this5 = this; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.prev = 0; + _context3.next = 3; + return Promise.all(uris.map(function (uri) { + return _this5.handleDroppedUri(uri, combo); + })); + case 3: + _context3.next = 5; + return this.controller.save(); + case 5: + _context3.next = 10; + break; + case 7: + _context3.prev = 7; + _context3.t0 = _context3["catch"](0); + return _context3.abrupt("return", Promise.reject(_context3.t0)); + case 10: + case "end": + return _context3.stop(); + } + }, _callee3, this, [[0, 7]]); + })); + function handleDroppedUris(_x5, _x6) { + return _handleDroppedUris.apply(this, arguments); + } + return handleDroppedUris; + }() + }, { + key: "handleDroppedUri", + value: function () { + var _handleDroppedUri = (0, _asyncToGenerator2["default"])(function (uri, combo) { + var _this6 = this; + var secondAttempt = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + return /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var agent, thing, _this6$_store, _this6$_store$fetcher, message, error; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + agent = findAgent(uri, _this6.store); // eg 'agent', 'origin', agentClass' + thing = (0, _rdflib.sym)(uri); + if (!(!agent && !secondAttempt)) { + _context4.next = 17; + break; + } + debug.log(" Not obvious: looking up dropped thing ".concat(thing)); + _context4.prev = 4; + _context4.next = 7; + return (_this6$_store = _this6._store) === null || _this6$_store === void 0 ? void 0 : (_this6$_store$fetcher = _this6$_store.fetcher) === null || _this6$_store$fetcher === void 0 ? void 0 : _this6$_store$fetcher.load(thing.doc()); + case 7: + _context4.next = 14; + break; + case 9: + _context4.prev = 9; + _context4.t0 = _context4["catch"](4); + message = "Ignore error looking up dropped thing: ".concat(_context4.t0); + debug.error(message); + return _context4.abrupt("return", Promise.reject(new Error(message))); + case 14: + return _context4.abrupt("return", _this6.handleDroppedUri(uri, combo, true)); + case 17: + if (agent) { + _context4.next = 21; + break; + } + error = " Error: Drop fails to drop appropriate thing! ".concat(uri); + debug.error(error); + return _context4.abrupt("return", Promise.reject(new Error(error))); + case 21: + _this6.setACLCombo(combo, uri, agent, _this6.controller.subject); + case 22: + case "end": + return _context4.stop(); + } + }, _callee4, null, [[4, 9]]); + })(); + }); + function handleDroppedUri(_x7, _x8) { + return _handleDroppedUri.apply(this, arguments); + } + return handleDroppedUri; + }() + }, { + key: "setACLCombo", + value: function setACLCombo(combo, uri, res, subject) { + if (!(combo in this.byCombo)) { + this.byCombo[combo] = []; + } + this.removeAgentFromCombos(uri); // Combos are mutually distinct + this.byCombo[combo].push([res.pred, res.obj.uri]); + debug.log("ACL: setting access to ".concat(subject, " by ").concat(res.pred, ": ").concat(res.obj)); } }, { - key: "toString", - value: function toString() { - return 'DefaultGraph'; + key: "removeAgentFromCombos", + value: function removeAgentFromCombos(uri) { + for (var k = 0; k < 16; k++) { + var combos = this.byCombo[kToCombo(k)]; + if (combos) { + for (var i = 0; i < combos.length; i++) { + while (i < combos.length && combos[i][1] === uri) { + combos.splice(i, 1); + } + } + } + } } }]); - return DefaultGraph; -}(_node_internal__WEBPACK_IMPORTED_MODULE_9__["default"]); + return AccessGroups; +}(); +exports.AccessGroups = AccessGroups; +function kToCombo(k) { + var y = ['Read', 'Append', 'Write', 'Control']; + var combo = []; + for (var i = 0; i < 4; i++) { + if (k & 1 << i) { + combo.push('http://www.w3.org/ns/auth/acl#' + y[i]); + } + } + combo.sort(); + return combo.join('\n'); +} +function ktToList(k) { + var list = ''; + var y = ['Read', 'Append', 'Write', 'Control']; + for (var i = 0; i < 4; i++) { + if (k & 1 << i) { + list += y[i]; + } + } + return list; +} +function findAgent(uri, kb) { + var obj = (0, _rdflib.sym)(uri); + var types = kb.findTypeURIs(obj); + for (var ty in types) { + debug.log(' drop object type includes: ' + ty); + } + // An Origin URI is one like https://fred.github.io eith no trailing slash + if (uri.startsWith('http') && uri.split('/').length === 3) { + // there is no third slash + return { + pred: 'origin', + obj: obj + }; // The only way to know an origin alas + } + // @@ This is an almighty kludge needed because drag and drop adds extra slashes to origins + if (uri.startsWith('http') && uri.split('/').length === 4 && uri.endsWith('/')) { + // there IS third slash + debug.log('Assuming final slash on dragged origin URI was unintended!'); + return { + pred: 'origin', + obj: (0, _rdflib.sym)(uri.slice(0, -1)) + }; // Fix a URI where the drag and drop system has added a spurious slash + } -function isDefaultGraph(object) { - return !!object && object.termType === _types__WEBPACK_IMPORTED_MODULE_7__.DefaultGraphTermType; + if (ns.vcard('WebID').uri in types) return { + pred: 'agent', + obj: obj + }; + if (ns.vcard('Group').uri in types) { + return { + pred: 'agentGroup', + obj: obj + }; // @@ note vcard membership not RDFs + } + + if (obj.sameTerm(ns.foaf('Agent')) || obj.sameTerm(ns.acl('AuthenticatedAgent')) || + // AuthenticatedAgent + obj.sameTerm(ns.rdf('Resource')) || obj.sameTerm(ns.owl('Thing'))) { + return { + pred: 'agentClass', + obj: obj + }; + } + if (ns.vcard('Individual').uri in types || ns.foaf('Person').uri in types || ns.foaf('Agent').uri in types) { + var pref = kb.any(obj, ns.foaf('preferredURI')); + if (pref) return { + pred: 'agent', + obj: (0, _rdflib.sym)(pref) + }; + return { + pred: 'agent', + obj: obj + }; + } + if (ns.solid('AppProvider').uri in types) { + return { + pred: 'origin', + obj: obj + }; + } + if (ns.solid('AppProviderClass').uri in types) { + return { + pred: 'originClass', + obj: obj + }; + } + debug.log(' Triage fails for ' + uri); + return null; } +//# sourceMappingURL=access-groups.js.map /***/ }), -/***/ "../rdflib/esm/empty.js": -/*!******************************!*\ - !*** ../rdflib/esm/empty.js ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./lib/acl/acl-control.js": +/*!********************************!*\ + !*** ./lib/acl/acl-control.js ***! + \********************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Empty) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ACLControlBox5 = ACLControlBox5; +exports.handleDrop = handleDrop; +exports.preventBrowserDropEvents = preventBrowserDropEvents; +exports.preventDrag = preventDrag; +exports.setGlobalWindow = setGlobalWindow; +exports.shortNameForFolder = shortNameForFolder; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var _acl = __webpack_require__(/*! ./acl */ "./lib/acl/acl.js"); +var _accessController = __webpack_require__(/*! ./access-controller */ "./lib/acl/access-controller.js"); +var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); +var _debug = __webpack_require__(/*! ../debug */ "./lib/debug.js"); +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); } +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; } +/** + * Functions for rendering the ACL User Interface. + * See https://github.com/solidos/userguide/blob/main/views/sharing/userguide.md#view + * for a screenshot. + * @packageDocumentation + */ + +var global = window; +var preventBrowserDropEventsDone = Symbol('prevent double triggering of drop event'); +/** + * See https://coshx.com/preventing-drag-and-drop-disasters-with-a-chrome-userscript + * Without this dropping anything onto a browser page will cause chrome etc to jump to diff page + * throwing away all the user's work. + * + * In apps which may use drag and drop, this utility takes care of the fact + * by default in a browser, an uncaught user drop into a browser window + * causes the browser to lose all its work in that window and navigate to another page + * + * @param document The DOM + * @returns void + */ +function preventBrowserDropEvents(document) { + (0, _debug.log)('preventBrowserDropEvents called.'); + if (typeof global !== 'undefined') { + if (global[preventBrowserDropEventsDone]) return; + global[preventBrowserDropEventsDone] = true; + } + document.addEventListener('drop', handleDrop, false); + document.addEventListener('dragenter', preventDrag, false); + document.addEventListener('dragover', preventDrag, false); +} +/** @internal */ +function preventDrag(e) { + e.stopPropagation(); + e.preventDefault(); +} +/** @internal */ +function handleDrop(e) { + if (e.dataTransfer.files.length > 0) { + if (!global.confirm('Are you sure you want to drop this file here? (Cancel opens it in a new tab)')) { + e.stopPropagation(); + e.preventDefault(); + (0, _debug.log)('@@@@ document-level DROP suppressed: ' + e.dataTransfer.dropEffect); + } + } +} +/** + * Get a folder's own filename in the directory tree. Also works for + * domain names; the URL protocol ('https://') acts as the tree root + * with short name '/' (see also test/unit/acl/acl-control.test.ts). + * + * ```typescript + * shortNameForFolder($rdf.namedNode('http://example.com/some/folder/')) + * // 'folder' + * + * shortNameForFolder($rdf.namedNode('http://example.com/some/folder')) + * // 'folder' + * + * shortNameForFolder($rdf.namedNode('http://example.com/')) + * // 'example.com' + * + * shortNameForFolder($rdf.namedNode('http://example.com')) + * // 'example.com' + * + * shortNameForFolder($rdf.namedNode('http://')) + * // '/' + * ``` + * + * It also works with relative URLs: + * ```typescript + * shortNameForFolder($rdf.namedNode('../folder/')) + * // 'folder' + * ``` + * + * @param x RDF Node for the folder URL + * @returns Short name for the folder + */ +function shortNameForFolder(x) { + var str = x.uri; -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + // Strip the trailing slash + if (str.slice(-1) === '/') { + str = str.slice(0, -1); + } + // Remove the path if present, keeping only the part + // after the last slash. + var slash = str.lastIndexOf('/'); + if (slash >= 0) { + str = str.slice(slash + 1); + } + // Return the folder's filename, or '/' if nothing found + // (but see https://github.com/solidos/solid-ui/issues/196 + // regarding whether this happens at the domain root or + // not) + return str || '/'; +} /** -* An empty node -*/ -var Empty = /*#__PURE__*/function (_Node) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Empty, _Node); - var _super = _createSuper(Empty); - function Empty() { - var _this; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Empty); - _this = _super.call(this, ''); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.EmptyTermType); - return _this; + * A wrapper that retrieves ACL data and uses it + * to render an [[AccessController]] component. + * Presumably the '5' is a version number of some sort, + * but all we know is it was already called ACLControlBox5 + * when it was introduced into solid-ui in + * https://github.com/solidos/solid-ui/commit/948b874bd93e7bf5160e6e224821b888f07d15f3#diff-4192a29f38a0ababd563b36b47eba5bbR54 + */ +function ACLControlBox5(subject, context, noun, kb) { + var dom = context.dom; + var doc = subject.doc(); // The ACL is actually to the doc describing the thing + + var container = dom.createElement('div'); + container.setAttribute('style', style.aclControlBoxContainer); + var header = container.appendChild(dom.createElement('h1')); + header.textContent = "Sharing for ".concat(noun, " ").concat(utils.label(subject)); + header.setAttribute('style', style.aclControlBoxHeader); + var status = container.appendChild(dom.createElement('div')); + status.setAttribute('style', style.aclControlBoxStatus); + try { + loadController(doc, kb, subject, noun, context, dom, status).then(function (controller) { + return container.appendChild(controller.render()); + }); + } catch (error) { + status.innerText = error; } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Empty, [{ - key: "toString", - value: function toString() { - return '()'; - } - }]); - return Empty; -}(_node_internal__WEBPACK_IMPORTED_MODULE_8__["default"]); + return container; +} +function loadController(_x, _x2, _x3, _x4, _x5, _x6, _x7) { + return _loadController.apply(this, arguments); +} +function _loadController() { + _loadController = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(doc, kb, subject, noun, context, dom, status) { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + return _context2.abrupt("return", new Promise(function (resolve, reject) { + return (0, _acl.getACLorDefault)(doc, /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(ok, isDirectACL, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc) { + var targetDirectory, targetIsProtected, prospectiveDefaultHolder, getController; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + getController = function _getController(prospectiveDefaultHolder) { + return new _accessController.AccessController(subject, noun, context, status, targetIsProtected, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc, prospectiveDefaultHolder, kb, dom); + }; + if (ok) { + _context.next = 3; + break; + } + return _context.abrupt("return", reject(new Error("Error reading ".concat(isDirectACL ? '' : ' default ', "ACL. status ").concat(targetDoc, ": ").concat(targetACLDoc)))); + case 3: + targetDirectory = getDirectory(targetDoc); + targetIsProtected = isStorage(targetDoc, targetACLDoc, kb) || hasProtectedAcl(targetDoc); + if (!(!targetIsProtected && targetDirectory)) { + _context.next = 16; + break; + } + _context.prev = 6; + _context.next = 9; + return (0, _acl.getProspectiveHolder)(targetDirectory); + case 9: + prospectiveDefaultHolder = _context.sent; + return _context.abrupt("return", resolve(getController(prospectiveDefaultHolder))); + case 13: + _context.prev = 13; + _context.t0 = _context["catch"](6); + // No need to show this error in status, but good to warn about it in console + (0, _debug.warn)(_context.t0); + case 16: + return _context.abrupt("return", resolve(getController())); + case 17: + case "end": + return _context.stop(); + } + }, _callee, null, [[6, 13]]); + })); + return function (_x8, _x9, _x10, _x11, _x12, _x13) { + return _ref.apply(this, arguments); + }; + }()); + })); + case 1: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _loadController.apply(this, arguments); +} +function getDirectory(doc) { + var str = doc.uri.split('#')[0]; + var p = str.slice(0, -1).lastIndexOf('/'); + var q = str.indexOf('//'); + return q >= 0 && p < q + 2 || p < 0 ? null : str.slice(0, p + 1); +} +function isStorage(doc, aclDoc, store) { + // @@ TODO: The methods used for targetIsStorage are HACKs - it should not be relied upon, and work is + // @@ underway to standardize a behavior that does not rely upon this hack + // @@ hopefully fixed as part of https://github.com/solidos/data-interoperability-panel/issues/10 + return store.holds(doc, ns.rdf('type'), ns.space('Storage'), aclDoc); +} +function hasProtectedAcl(targetDoc) { + // @@ TODO: This is hacky way of knowing whether or not a certain ACL file can be removed + // Hopefully we'll find a better, standardized solution to this - https://github.com/solidos/specification/issues/37 + return targetDoc.uri === targetDoc.site().uri; +} +/** @internal */ +function setGlobalWindow(window) { + global = window; +} +//# sourceMappingURL=acl-control.js.map /***/ }), -/***/ "../rdflib/esm/factories/canonical-data-factory.js": -/*!*********************************************************!*\ - !*** ../rdflib/esm/factories/canonical-data-factory.js ***! - \*********************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./lib/acl/acl.js": +/*!************************!*\ + !*** ./lib/acl/acl.js ***! + \************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), -/* harmony export */ "defaultGraphURI": () => (/* reexport safe */ _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_1__.defaultGraphURI) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../blank-node */ "../rdflib/esm/blank-node.js"); -/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../literal */ "../rdflib/esm/literal.js"); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../named-node */ "../rdflib/esm/named-node.js"); -/* harmony import */ var _statement__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../statement */ "../rdflib/esm/statement.js"); -/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../variable */ "../rdflib/esm/variable.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types */ "../rdflib/esm/types.js"); -/* harmony import */ var _default_graph__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../default-graph */ "../rdflib/esm/default-graph.js"); -/* harmony import */ var _factory_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./factory-types */ "../rdflib/esm/factories/factory-types.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/terms */ "../rdflib/esm/utils/terms.js"); -/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/default-graph-uri */ "../rdflib/esm/utils/default-graph-uri.js"); - -var _supports; - - - +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ACLToString = ACLToString; +exports.ACLbyCombination = ACLbyCombination; +exports.ACLunion = ACLunion; +exports.adoptACLDefault = adoptACLDefault; +exports.comboToString = comboToString; +exports.fixIndividualACL = fixIndividualACL; +exports.fixIndividualCardACL = fixIndividualCardACL; +exports.getACL = getACL; +exports.getACLorDefault = getACLorDefault; +exports.getProspectiveHolder = getProspectiveHolder; +exports.loadUnionACL = loadUnionACL; +exports.makeACLGraph = makeACLGraph; +exports.makeACLGraphbyCombo = makeACLGraphbyCombo; +exports.makeACLString = makeACLString; +exports.putACLObject = putACLObject; +exports.putACLbyCombo = putACLbyCombo; +exports.readACL = readACL; +exports.sameACL = sameACL; +exports.setACL = setACL; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); +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); } +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; } +/** + * Non-UI functions for access control. + * See https://github.com/solidos/web-access-control-spec + * for the spec that defines how ACL documents work. + * @packageDocumentation + */ +var kb = _solidLogic.solidLogicSingleton.store; +/** + * Take the "default" ACL and convert it into the equivalent ACL + * which the resource would have had. Return it as a new separate store. + * The "defaultForNew" predicate is also accepted, as a deprecated + * synonym for "default". + */ +function adoptACLDefault(doc, aclDoc, defaultResource, defaultACLDoc) { + var ACL = ns.acl; + var isContainer = doc.uri.slice(-1) === '/'; // Give default for all directories + var defaults = kb.each(undefined, ACL('default'), defaultResource, defaultACLDoc).concat(kb.each(undefined, ACL('defaultForNew'), defaultResource, defaultACLDoc)); + var proposed = defaults.reduce(function (accumulatedStatements, da) { + return accumulatedStatements.concat(kb.statementsMatching(da, ns.rdf('type'), ACL('Authorization'), defaultACLDoc)).concat(kb.statementsMatching(da, ACL('agent'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('agentClass'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('agentGroup'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('origin'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('originClass'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('mode'), undefined, defaultACLDoc)).concat((0, _rdflib.st)(da, ACL('accessTo'), doc, defaultACLDoc)).concat(isContainer ? (0, _rdflib.st)(da, ACL('default'), doc, defaultACLDoc) : []); + }, []); + var kb2 = (0, _rdflib.graph)(); // Potential - derived is kept apart + proposed.forEach(function (st) { + return kb2.add(move(st.subject), move(st.predicate), move(st.object), (0, _rdflib.sym)(aclDoc.uri)); + }); + return kb2; + function move(symbol) { + var y = defaultACLDoc.uri.length; // The default ACL file + return (0, _rdflib.sym)(symbol.uri.slice(0, y) === defaultACLDoc.uri ? aclDoc.uri + symbol.uri.slice(y) : symbol.uri); + } +} +/** + * Read and canonicalize the ACL for x in aclDoc + * + * Accumulate the access rights which each agent or class has + */ +function readACL(doc, aclDoc) { + var kb2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : kb; + var getDefaults = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; + var auths = getDefaults ? getDefaultsFallback(kb2, ns) : kb2.each(undefined, ns.acl('accessTo'), doc); + var ACL = ns.acl; + var ac = { + agent: {}, + agentClass: {}, + agentGroup: {}, + origin: {}, + originClass: {} + }; + Object.keys(ac).forEach(function (pred) { + auths.forEach(function (a) { + kb2.each(a, ACL('mode')).forEach(function (mode) { + kb2.each(a, ACL(pred)).forEach(function (agent) { + ac[pred][agent.uri] = ac[pred][agent.uri] || {}; + ac[pred][agent.uri][mode.uri] = a; // could be "true" but leave pointer just in case + }); + }); + }); + }); + return ac; + function getDefaultsFallback(kb, ns) { + return kb.each(undefined, ns.acl('default'), doc).concat(kb.each(undefined, ns.acl('defaultForNew'), doc)); + } +} /** - * Gets the default graph + * Compare two ACLs */ -var _defaultGraph = new _default_graph__WEBPACK_IMPORTED_MODULE_2__["default"](); - -/** A basic internal RDFlib datafactory, which does not support Collections */ -var CanonicalDataFactory = { - supports: (_supports = {}, (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.collections, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.defaultGraphType, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.equalsMethod, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.identity, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.id, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.reversibleId, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.variableType, true), _supports), - /** - * Creates a new blank node - * @param value - The blank node's identifier - */ - blankNode: function blankNode(value) { - return new _blank_node__WEBPACK_IMPORTED_MODULE_4__["default"](value); - }, - defaultGraph: function defaultGraph() { - return _defaultGraph; - }, - /** - * Compares to (rdf) objects for equality. - */ - equals: function equals(a, b) { - if (a === b || !a || !b) { - return true; - } - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(a) || (0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(b)) { - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(a) && (0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(b)) { - return this.equals(a.subject, b.subject) && this.equals(a.predicate, b.predicate) && this.equals(a.object, b.object) && this.equals(a.graph, b.graph); +function sameACL(a, b) { + var contains = function contains(a, b) { + for (var pred in { + agent: true, + agentClass: true, + agentGroup: true, + origin: true, + originClass: true + }) { + if (a[pred]) { + for (var agent in a[pred]) { + for (var mode in a[pred][agent]) { + if (!b[pred][agent] || !b[pred][agent][mode]) { + return false; + } + } + } } - return false; - } - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isTerm)(a) && (0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isTerm)(b)) { - return this.id(a) === this.id(b); } - return false; - }, - /** - * Generates a uniquely identifiably *idempotent* string for the given {term}. - * - * Equivalent to [[Term.hashString]] - * - * @example Use this to associate data with a term in an object - * { obj[id(term)] = "myData" } - */ - id: function id(term) { - if (!term) { - return 'undefined'; - } - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(term)) { - return this.quadToNQ(term); - } - switch (term.termType) { - case _types__WEBPACK_IMPORTED_MODULE_6__.DefaultGraphTermType: - return 'defaultGraph'; - case _types__WEBPACK_IMPORTED_MODULE_6__.VariableTermType: - return _variable__WEBPACK_IMPORTED_MODULE_7__["default"].toString(term); - default: - var nq = this.termToNQ(term); - if (nq) { - return nq; + return true; + }; + return contains(a, b) && contains(b, a); +} + +/** + * Union N ACLs + */ +function ACLunion(list) { + var b = list[0]; + var a, ag; + var _loop = function _loop(k) { + ; + ['agent', 'agentClass', 'agentGroup', 'origin', 'originClass'].forEach(function (pred) { + a = list[k]; + if (a[pred]) { + for (ag in a[pred]) { + for (var mode in a[pred][ag]) { + if (!b[pred][ag]) b[pred][ag] = []; + b[pred][ag][mode] = true; + } } - throw new Error("Can't id term with type '".concat(term.termType, "'")); - } - }, - isQuad: function isQuad(obj) { - return obj instanceof _statement__WEBPACK_IMPORTED_MODULE_8__["default"]; - }, - /** - * Creates a new literal node. Does some JS literal parsing for ease of use. - * @param value - The lexical value - * @param languageOrDatatype - Either the language or the datatype - */ - literal: function literal(value, languageOrDatatype) { - if (typeof value !== "string" && !languageOrDatatype) { - return _literal__WEBPACK_IMPORTED_MODULE_9__["default"].fromValue(value); - } - var strValue = typeof value === 'string' ? value : '' + value; - if (typeof languageOrDatatype === 'string') { - if (languageOrDatatype.indexOf(':') === -1) { - return new _literal__WEBPACK_IMPORTED_MODULE_9__["default"](strValue, languageOrDatatype); - } else { - return new _literal__WEBPACK_IMPORTED_MODULE_9__["default"](strValue, null, this.namedNode(languageOrDatatype)); } + }); + }; + for (var k = 1; k < list.length; k++) { + _loop(k); + } + return b; +} +/** + * Merge ACLs lists from things to form union + */ +function loadUnionACL(subjectList, callbackFunction) { + var aclList = []; + var doList = function doList(list) { + if (list.length) { + var doc = list.shift().doc(); + getACLorDefault(doc, function (ok, p2, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc) { + var defa = !p2; + if (!ok || !defaultHolder || !defaultACLDoc) return callbackFunction(ok, targetACLDoc); + var acl = defa ? readACL(defaultHolder, defaultACLDoc) : readACL(targetDoc, targetACLDoc); + aclList.push(acl); + doList(list.slice(1)); + }); } else { - return new _literal__WEBPACK_IMPORTED_MODULE_9__["default"](strValue, null, languageOrDatatype); - } - }, - /** - * Creates a new named node - * @param value - The new named node - */ - namedNode: function namedNode(value) { - return new _named_node__WEBPACK_IMPORTED_MODULE_10__["default"](value); - }, - /** - * Creates a new statement - * @param subject - The subject - * @param predicate - The predicate - * @param object - The object - * @param graph - The containing graph - */ - quad: function quad(subject, predicate, object, graph) { - return new _statement__WEBPACK_IMPORTED_MODULE_8__["default"](subject, predicate, object, graph || _defaultGraph); - }, - /** - * Creates a new statement - * @param subject - The subject - * @param predicate - The predicate - * @param object - The object - * @param graph - The containing graph - */ - triple: function triple(subject, predicate, object, graph) { - return this.quad(subject, predicate, object, graph); - }, - quadToNQ: function quadToNQ(q) { - return "".concat(this.termToNQ(q.subject), " ").concat(this.termToNQ(q.predicate), " ").concat(this.termToNQ(q.object), " ").concat(this.termToNQ(q.graph), " ."); - }, - /** Stringify a {term} to n-quads serialization. */termToNQ: function termToNQ(term) { - var _this = this; - switch (term.termType) { - case _types__WEBPACK_IMPORTED_MODULE_6__.BlankNodeTermType: - return '_:' + term.value; - case _types__WEBPACK_IMPORTED_MODULE_6__.DefaultGraphTermType: - return ''; - case _types__WEBPACK_IMPORTED_MODULE_6__.EmptyTermType: - return ''; - case _types__WEBPACK_IMPORTED_MODULE_6__.LiteralTermType: - return _literal__WEBPACK_IMPORTED_MODULE_9__["default"].toNT(term); - case _types__WEBPACK_IMPORTED_MODULE_6__.GraphTermType: - case _types__WEBPACK_IMPORTED_MODULE_6__.NamedNodeTermType: - return '<' + term.value + '>'; - case _types__WEBPACK_IMPORTED_MODULE_6__.CollectionTermType: - return '(' + term.elements.map(function (t) { - return _this.termToNQ(t); - }).join(' ') + ')'; - default: - throw new Error("Can't serialize nonstandard term type (was '".concat(term.termType, "')")); - } - }, - /** Convert an rdf object (term or quad) to n-quads serialization. */toNQ: function toNQ(term) { - if (this.isQuad(term)) { - return this.quadToNQ(term); + // all gone + callbackFunction(true, ACLunion(aclList)); } - return this.termToNQ(term); - }, - /** - * Creates a new variable - * @param name - The name for the variable - */ - variable: function variable(name) { - return new _variable__WEBPACK_IMPORTED_MODULE_7__["default"](name); - } -}; - -/** Contains the factory methods as defined in the spec, plus id */ -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CanonicalDataFactory); - -/***/ }), - -/***/ "../rdflib/esm/factories/extended-term-factory.js": -/*!********************************************************!*\ - !*** ../rdflib/esm/factories/extended-term-factory.js ***! - \********************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../collection */ "../rdflib/esm/collection.js"); -/* harmony import */ var _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./canonical-data-factory */ "../rdflib/esm/factories/canonical-data-factory.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types */ "../rdflib/esm/types.js"); -/* harmony import */ var _factory_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./factory-types */ "../rdflib/esm/factories/factory-types.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/terms */ "../rdflib/esm/utils/terms.js"); -/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../variable */ "../rdflib/esm/variable.js"); - -var _supports; -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } - - - + }; + doList(subjectList); +} +/** + * Represents these as an RDF graph by combination of modes + * + * Each agent can only be in one place in this model, one combination of modes. + * Combos are like full control, read append, read only etc. + */ +function ACLbyCombination(ac) { + var byCombo = {}; + ['agent', 'agentClass', 'agentGroup', 'origin', 'originClass'].forEach(function (pred) { + for (var agent in ac[pred]) { + var combo = []; + for (var mode in ac[pred][agent]) { + combo.push(mode); + } + combo.sort(); + var combo2 = combo.join('\n'); + if (!byCombo[combo2]) byCombo[combo2] = []; + byCombo[combo2].push([pred, agent]); + } + }); + return byCombo; +} +/** + * Write ACL graph to store from AC + */ +function makeACLGraph(kb, x, ac, aclDoc) { + var byCombo = ACLbyCombination(ac); + return makeACLGraphbyCombo(kb, x, byCombo, aclDoc); +} /** - * Data factory which also supports Collections - * - * Necessary for preventing circular dependencies. + * Write ACL graph to store from combo */ -var ExtendedTermFactory = _objectSpread(_objectSpread({}, _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"]), {}, { - supports: (_supports = {}, (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.collections, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.defaultGraphType, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.equalsMethod, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.identity, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.id, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.reversibleId, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.variableType, true), _supports), - /** - * Creates a new collection - * @param elements - The initial element - */ - collection: function collection(elements) { - return new _collection__WEBPACK_IMPORTED_MODULE_3__["default"](elements); - }, - id: function id(term) { - var _this = this; - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_4__.isCollection)(term)) { - return "( ".concat(term.elements.map(function (e) { - return _this.id(e); - }).join(', '), " )"); +function makeACLGraphbyCombo(kb, x, byCombo, aclDoc, main, defa) { + var ACL = ns.acl; + for (var combo in byCombo) { + var pairs = byCombo[combo]; + if (!pairs.length) continue; // do not add to store when no agent + var modeURIs = combo.split('\n'); + var _short = modeURIs.map(function (u) { + return u.split('#')[1]; + }).join(''); + if (defa && !main) _short += 'Default'; // don't muddle authorizations + var _a = kb.sym(aclDoc.uri + '#' + _short); + kb.add(_a, ns.rdf('type'), ACL('Authorization'), aclDoc); + if (main) { + kb.add(_a, ACL('accessTo'), x, aclDoc); } - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_4__.isVariable)(term)) { - return _variable__WEBPACK_IMPORTED_MODULE_5__["default"].toString(term); + if (defa) { + kb.add(_a, ACL('default'), x, aclDoc); } - return _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"].id(term); - }, - termToNQ: function termToNQ(term) { - if (term.termType === _types__WEBPACK_IMPORTED_MODULE_6__.CollectionTermType) { - return _collection__WEBPACK_IMPORTED_MODULE_3__["default"].toNT(term); + for (var i = 0; i < modeURIs.length; i++) { + kb.add(_a, ACL('mode'), kb.sym(modeURIs[i]), aclDoc); + } + for (var _i = 0; _i < pairs.length; _i++) { + var pred = pairs[_i][0]; + var ag = pairs[_i][1]; + kb.add(_a, ACL(pred), kb.sym(ag), aclDoc); } - return _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"].termToNQ(term); } -}); -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ExtendedTermFactory); - -/***/ }), - -/***/ "../rdflib/esm/factories/factory-types.js": -/*!************************************************!*\ - !*** ../rdflib/esm/factories/factory-types.js ***! - \************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Feature": () => (/* binding */ Feature) -/* harmony export */ }); -/** A set of features that may be supported by a Data Factory */ - -var Feature; +} /** - * Defines a DataFactory as used in rdflib, based on the RDF/JS: Data model specification, - * but with additional extensions - * - * bnIndex is optional but useful. + * Debugging short strings for dumping ACL + * and possibly in the UI */ -(function (Feature) { - Feature["collections"] = "COLLECTIONS"; - Feature["defaultGraphType"] = "DEFAULT_GRAPH_TYPE"; - Feature["equalsMethod"] = "EQUALS_METHOD"; - Feature["id"] = "ID"; - Feature["identity"] = "IDENTITY"; - Feature["reversibleId"] = "REVERSIBLE_ID"; - Feature["variableType"] = "VARIABLE_TYPE"; -})(Feature || (Feature = {})); - -/***/ }), - -/***/ "../rdflib/esm/factories/rdflib-data-factory.js": -/*!******************************************************!*\ - !*** ../rdflib/esm/factories/rdflib-data-factory.js ***! - \******************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../store */ "../rdflib/esm/store.js"); -/* harmony import */ var _fetcher__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../fetcher */ "../rdflib/esm/fetcher.js"); -/* harmony import */ var _extended_term_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./extended-term-factory */ "../rdflib/esm/factories/extended-term-factory.js"); - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } - - +function ACLToString(ac) { + return comboToString(ACLbyCombination(ac)); +} -/** Full RDFLib.js Data Factory */ -var RDFlibDataFactory = _objectSpread(_objectSpread({}, _extended_term_factory__WEBPACK_IMPORTED_MODULE_1__["default"]), {}, { - /** - * Creates a new fetcher - * @param store - The store to use - * @param options - The options - */ - fetcher: function fetcher(store, options) { - return new _fetcher__WEBPACK_IMPORTED_MODULE_2__["default"](store, options); - }, - /** - * Creates a new graph (store) - */ - graph: function graph() { - var features = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - return new _store__WEBPACK_IMPORTED_MODULE_3__["default"](features, opts || { - rdfFactory: _extended_term_factory__WEBPACK_IMPORTED_MODULE_1__["default"] - }); - }, - /** - * Creates a new literal node - * @param val The lexical value - * @param lang The language - * @param dt The datatype - */ - lit: function lit(val, lang, dt) { - return this.literal('' + val, lang || dt); - }, - /** - * Creates a new statement - * @param subject The subject - * @param predicate The predicate - * @param object The object - * @param graph The containing graph - */ - st: function st(subject, predicate, object, graph) { - return this.quad(subject, predicate, object, graph); +/** + * Convert a [[ComboList]] to a string + */ +function comboToString(byCombo) { + var str = ''; + for (var combo in byCombo) { + var modeURIs = combo.split('\n'); + var initials = modeURIs.map(function (u) { + return u.split('#')[1][0]; + }).join(''); + str += initials + ':'; + var pairs = byCombo[combo]; + for (var i = 0; i < pairs.length; i++) { + var pred = pairs[i][0]; + var ag = (0, _rdflib.sym)(pairs[i][1]); + str += pred === 'agent' ? '@' : ''; + str += ag.sameTerm(ns.foaf('Agent')) ? '*' : utils.label(ag); + if (i < pairs.length - 1) str += ','; + } + str += ';'; } -}); -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (RDFlibDataFactory); - -/***/ }), - -/***/ "../rdflib/esm/fetcher.js": -/*!********************************!*\ - !*** ../rdflib/esm/fetcher.js ***! - \********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Fetcher) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../rdflib/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/regenerator */ "../rdflib/node_modules/@babel/runtime/regenerator/index.js"); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./store */ "../rdflib/esm/store.js"); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); -/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./n3parser */ "../rdflib/esm/n3parser.js"); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); -/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); -/* harmony import */ var _parse__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./parse */ "../rdflib/esm/parse.js"); -/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./rdfaparser */ "../rdflib/esm/rdfaparser.js"); -/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./rdfxmlparser */ "../rdflib/esm/rdfxmlparser.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); -/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./serialize */ "../rdflib/esm/serialize.js"); -/* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! cross-fetch */ "../rdflib/node_modules/cross-fetch/dist/browser-ponyfill.js"); -/* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(cross_fetch__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./utils/termValue */ "../rdflib/esm/utils/termValue.js"); -/* harmony import */ var _jsonldparser__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./jsonldparser */ "../rdflib/esm/jsonldparser.js"); - - - - + return '{' + str.slice(0, -1) + '}'; // drop extra semicolon +} +/** + * Write ACL graph as Turtle + */ +function makeACLString(x, ac, aclDoc) { + var kb2 = (0, _rdflib.graph)(); + makeACLGraph(kb2, x, ac, aclDoc); + return (0, _rdflib.serialize)(aclDoc, kb2, aclDoc.uri, 'text/turtle') || ''; +} +/** + * Write ACL graph to web + */ +function putACLObject(kb, x, ac, aclDoc, callbackFunction) { + var byCombo = ACLbyCombination(ac); + return putACLbyCombo(kb, x, byCombo, aclDoc, callbackFunction); +} +/** + * Write ACL graph to web from a [[ComboList]] + */ +function putACLbyCombo(kb, x, byCombo, aclDoc, callbackFunction) { + var _kb$updater; + var kb2 = (0, _rdflib.graph)(); + makeACLGraphbyCombo(kb2, x, byCombo, aclDoc, true); -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; } } }; } -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); } -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; } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -/* global $SolidTestEnvironment */ + // const str = makeACLString = function(x, ac, aclDoc) + (_kb$updater = kb.updater) === null || _kb$updater === void 0 ? void 0 : _kb$updater.put(aclDoc, kb2.statementsMatching(undefined, undefined, undefined, aclDoc), 'text/turtle', function (uri, ok, message) { + if (!ok) { + callbackFunction(ok, message); + } else { + var _kb$fetcher; + (_kb$fetcher = kb.fetcher) === null || _kb$fetcher === void 0 ? void 0 : _kb$fetcher.unload(aclDoc); + makeACLGraphbyCombo(kb, x, byCombo, aclDoc, true); + kb.fetcher.requested[aclDoc.uri] = 'done'; // missing: save headers + callbackFunction(ok); + } + }); +} /** + * Fix the ACl for an individual card as a function of the groups it is in * - * Project: rdflib.js - * - * @file: fetcher.js - * - * Description: contains functions for requesting/fetching/retracting - * This implements quite a lot of the web architecture. - * A fetcher is bound to a specific quad store, into which - * it loads stuff and into which it writes its metadata - * @@ The metadata could be optionally a separate graph - * - * - implements semantics of HTTP headers, Internet Content Types - * - selects parsers for rdf/xml, n3, rdfa, grddl - * - * TO do: - * - Implement a runtime registry for parsers and serializers - * - + * All group files must be loaded first */ +function fixIndividualCardACL(person, log, callbackFunction) { + var groups = kb.each(undefined, ns.vcard('hasMember'), person); + // const doc = person.doc() + if (groups) { + fixIndividualACL(person, groups, log, callbackFunction); + } else { + log('This card is in no groups'); + callbackFunction(true); // fine, no requirements to access. default should be ok + } + // @@ if no groups, then use default for People container or the book top container.? +} /** - * Things to test: callbacks on request, refresh, retract - * loading from HTTP, HTTPS, FTP, FILE, others? - * To do: - * Firing up a mail client for mid: (message:) URLs + * This function is used by [[fixIndividualCardACL]] */ +function fixIndividualACL(item, subjects, log, callbackFunction) { + log = log || debug.log; + var doc = item.doc(); + getACLorDefault(doc, function (ok, exists, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc) { + if (!ok || !defaultHolder || !defaultACLDoc) return callbackFunction(false, targetACLDoc); // ie message + var ac = exists ? readACL(targetDoc, targetACLDoc) : readACL(defaultHolder, defaultACLDoc); + loadUnionACL(subjects, function (ok, union) { + if (!ok) return callbackFunction(false, union); + if (sameACL(union, ac)) { + log('Nice - same ACL. no change ' + utils.label(item) + ' ' + doc); + } else { + log('Group ACLs differ for ' + utils.label(item) + ' ' + doc); + // log("Group ACLs: " + makeACLString(targetDoc, union, targetACLDoc)) + // log((exists ? "Previous set" : "Default") + " ACLs: " + + // makeACLString(targetDoc, ac, targetACLDoc)) + putACLObject(kb, targetDoc, union, targetACLDoc, callbackFunction); + } + }); + }); +} - - - - - - - - - - - - - -var Parsable = { - 'text/n3': true, - 'text/turtle': true, - 'application/rdf+xml': true, - 'application/xhtml+xml': true, - 'text/html': true, - 'application/ld+json': true -}; - -// This is a minimal set to allow the use of damaged servers if necessary -var CONTENT_TYPE_BY_EXT = { - 'rdf': _types__WEBPACK_IMPORTED_MODULE_9__.RDFXMLContentType, - 'owl': _types__WEBPACK_IMPORTED_MODULE_9__.RDFXMLContentType, - 'n3': 'text/n3', - 'ttl': 'text/turtle', - 'nt': 'text/n3', - 'acl': 'text/n3', - 'html': 'text/html', - 'xml': 'text/xml' -}; - -// Convenience namespaces needed in this module. -// These are deliberately not exported as the user application should -// make its own list and not rely on the prefixes used here, -// and not be tempted to add to them, and them clash with those of another -// application. -var getNS = function getNS(factory) { - return { - link: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2007/ont/link#', factory), - http: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2007/ont/http#', factory), - httph: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2007/ont/httph#', factory), - // headers - rdf: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#', factory), - rdfs: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2000/01/rdf-schema#', factory), - dc: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://purl.org/dc/elements/1.1/', factory), - ldp: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/ns/ldp#', factory) - }; -}; -var ns = getNS(); -var Handler = /*#__PURE__*/(0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])( -// TODO: Document, type - -// TODO: Document, type - -function Handler(response, dom) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, Handler); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "response", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "dom", void 0); - this.response = response; - // The type assertion operator here might need to be removed. - this.dom = dom; -}); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Handler, "pattern", void 0); -var RDFXMLHandler = /*#__PURE__*/function (_Handler) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(RDFXMLHandler, _Handler); - var _super = _createSuper(RDFXMLHandler); - function RDFXMLHandler() { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, RDFXMLHandler); - return _super.apply(this, arguments); +/** + * Set an ACL + */ +function setACL(docURI, aclText, callbackFunction) { + var aclDoc = kb.any(docURI, _solidLogic.ACL_LINK); // @@ check that this get set by web.js + if (!kb.fetcher) { + throw new Error('Store has no fetcher'); } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(RDFXMLHandler, [{ - key: "parse", - value: function parse(fetcher, /** An XML String */ - responseText, /** Requires .original */ - options) { - var kb = fetcher.store; - if (!this.dom) { - this.dom = _utils_js__WEBPACK_IMPORTED_MODULE_11__.parseXML(responseText); - } - var root = this.dom.documentElement; - if (root.nodeName === 'parsererror') { - // Mozilla only See issue/issue110 - // have to fail the request - return fetcher.failFetch(options, 'Badly formed XML in ' + options.resource.value, 'parse_error'); - } - var parser = new _rdfxmlparser__WEBPACK_IMPORTED_MODULE_12__["default"](kb); - try { - parser.parse(this.dom, options.original.value, options.original); - } catch (err) { - return fetcher.failFetch(options, 'Syntax error parsing RDF/XML! ' + err, 'parse_error'); - } - if (!options.noMeta) { - kb.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode); + if (aclDoc) { + // Great we already know where it is + kb.fetcher.webOperation('PUT', aclDoc.value, { + data: aclText, + contentType: 'text/turtle' + }).then(function (res) { + callbackFunction(res.ok, res.error || ''); + }); // @@@ check params + } else { + kb.fetcher.nowOrWhenFetched(docURI, undefined, function (ok, body) { + if (!ok) return callbackFunction(ok, 'Gettting headers for ACL: ' + body); + var aclDoc = kb.any(docURI, _solidLogic.ACL_LINK); // @@ check that this get set by web.js + if (!aclDoc) { + // complainIfBad(false, "No Link rel=ACL header for " + docURI) + callbackFunction(false, 'No Link rel=ACL header for ' + docURI); + } else { + if (!kb.fetcher) { + throw new Error('Store has no fetcher'); + } + kb.fetcher.webOperation('PUT', aclDoc.value, { + data: aclText, + contentType: 'text/turtle' + }).then(function (res) { + callbackFunction(res.ok, res.error || ''); + }); } - return fetcher.doneFetch(options, this.response); - } - }], [{ - key: "toString", - value: function toString() { - return 'RDFXMLHandler'; - } - }, { - key: "register", - value: function register(fetcher) { - fetcher.mediatypes[_types__WEBPACK_IMPORTED_MODULE_9__.RDFXMLContentType] = { - 'q': 0.9 - }; - } - }]); - return RDFXMLHandler; -}(Handler); -RDFXMLHandler.pattern = new RegExp('application/rdf\\+xml'); -var XHTMLHandler = /*#__PURE__*/function (_Handler2) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(XHTMLHandler, _Handler2); - var _super2 = _createSuper(XHTMLHandler); - function XHTMLHandler() { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, XHTMLHandler); - return _super2.apply(this, arguments); + }); } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(XHTMLHandler, [{ - key: "parse", - value: function parse(fetcher, responseText, options) { - var relation, reverse; - if (!this.dom) { - this.dom = _utils_js__WEBPACK_IMPORTED_MODULE_11__.parseXML(responseText); - } - var kb = fetcher.store; +} - // dc:title - var title = this.dom.getElementsByTagName('title'); - if (title.length > 0) { - kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(title[0].textContent), options.resource); - // log.info("Inferring title of " + xhr.resource) - } +/** + * Get ACL file or default if necessary + * + * @param callbackFunction Will be called in the following ways, in the following cases: + * * `callbackFunction(true, true, doc, aclDoc)` if the ACL did exist + * * `callbackFunction(true, false, doc, aclDoc, defaultHolder, defaultACLDoc)` if the ACL file did not exist but a default did + * * `callbackFunction(false, false, status, message)` when there was an error getting the original + * * `callbackFunction(false, true, status, message)` when there was an error getting the default + */ +function getACLorDefault(doc, callbackFunction) { + getACL(doc, function (ok, status, aclDoc, message) { + var ACL = ns.acl; + if (!ok) return callbackFunction(false, false, status, message); - // link rel - var links = this.dom.getElementsByTagName('link'); - for (var x = links.length - 1; x >= 0; x--) { - // @@ rev - relation = links[x].getAttribute('rel'); - reverse = false; - if (!relation) { - relation = links[x].getAttribute('rev'); - reverse = true; + // Recursively search for the ACL file which gives default access + var tryParent = function tryParent(uri) { + if (uri.slice(-1) === '/') { + uri = uri.slice(0, -1); + } + var right = uri.lastIndexOf('/'); + var left = uri.indexOf('/', uri.indexOf('//') + 2); + if (left > right) { + return callbackFunction(false, true, 404, 'Found no ACL resource'); + } + uri = uri.slice(0, right + 1); + var doc2 = (0, _rdflib.sym)(uri); + getACL(doc2, function (ok, status, defaultACLDoc) { + if (!ok) { + return callbackFunction(false, true, status, "( No ACL pointer ".concat(uri, " ").concat(status, ")").concat(defaultACLDoc)); + } else if (status === 403) { + return callbackFunction(false, true, status, "( default ACL file FORBIDDEN. Stop.".concat(uri, ")")); + } else if (status === 404) { + return tryParent(uri); + } else if (status !== 200) { + return callbackFunction(false, true, status, "Error status '".concat(status, "' searching for default for ").concat(doc2)); } - if (relation) { - fetcher.linkData(options.original, relation, links[x].getAttribute('href'), options.resource, reverse); + // 200 + // statusBlock.textContent += (" ACCESS set at " + uri + ". End search.") + var defaults = kb.each(undefined, ACL('default'), kb.sym(uri), defaultACLDoc).concat(kb.each(undefined, ACL('defaultForNew'), kb.sym(uri), defaultACLDoc)); + if (!defaults.length) { + return tryParent(uri); // Keep searching } - } - // Data Islands - var scripts = this.dom.getElementsByTagName('script'); - for (var i = 0; i < scripts.length; i++) { - var contentType = scripts[i].getAttribute('type'); - if (Parsable[contentType]) { - // @ts-ignore incompatibility between Store.add and Formula.add - (0,_parse__WEBPACK_IMPORTED_MODULE_13__["default"])(scripts[i].textContent, kb, options.original.value, contentType); - // @ts-ignore incompatibility between Store.add and Formula.add - (0,_parse__WEBPACK_IMPORTED_MODULE_13__["default"])(scripts[i].textContent, kb, options.original.value, contentType); - } + var defaultHolder = kb.sym(uri); + return callbackFunction(true, false, doc, aclDoc, defaultHolder, defaultACLDoc); + }); + }; // tryParent + + if (!ok) { + return callbackFunction(false, false, status, "Error accessing Access Control information for ".concat(doc, ") ").concat(message)); + } else if (status === 404) { + tryParent(doc.uri); // @@ construct default one - the server should do that + } else if (status === 403) { + return callbackFunction(false, false, status, "(Sharing not available to you)".concat(message)); + } else if (status !== 200) { + return callbackFunction(false, false, status, "Error ".concat(status, " accessing Access Control information for ").concat(doc, ": ").concat(message)); + } else { + // 200 + return callbackFunction(true, true, doc, aclDoc); + } + }); // Call to getACL +} + +/** + * Calls back `(ok, status, acldoc, message)` as follows + * + * * `(false, 900, errormessage)` if no link header + * * `(true, 403, documentSymbol, fileaccesserror)` if not authorized + * * `(true, 404, documentSymbol, fileaccesserror)` if does not exist + * * `(true, 200, documentSymbol)` if file exists and read OK + */ +function getACL(doc, callbackFunction) { + if (!kb.fetcher) { + throw new Error('kb has no fetcher'); + } + kb.fetcher.nowOrWhenFetched(doc, undefined, function (ok, body) { + if (!ok) { + return callbackFunction(ok, "Can't get headers to find ACL for ".concat(doc, ": ").concat(body)); + } + var aclDoc = kb.any(doc, _solidLogic.ACL_LINK); // @@ check that this get set by web.js + if (!aclDoc) { + callbackFunction(false, 900, "No Link rel=ACL header for ".concat(doc)); + } else { + if (!kb.fetcher) { + throw new Error('kb has no fetcher'); } - if (!options.noMeta) { - kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode); + if (kb.fetcher.nonexistent[aclDoc.value]) { + return callbackFunction(true, 404, aclDoc, "ACL file ".concat(aclDoc, " does not exist.")); } - if (!options.noRDFa && _rdfaparser__WEBPACK_IMPORTED_MODULE_14__.parseRDFaDOM) { - // enable by default - try { - (0,_rdfaparser__WEBPACK_IMPORTED_MODULE_14__.parseRDFaDOM)(this.dom, kb, options.original.value); - } catch (err) { - // @ts-ignore - var msg = 'Error trying to parse ' + options.resource + ' as RDFa:\n' + err + ':\n' + err.stack; - return fetcher.failFetch(options, msg, 'parse_error'); + kb.fetcher.nowOrWhenFetched(aclDoc, undefined, function (ok, message, response) { + if (!ok) { + callbackFunction(true, response.status, aclDoc, "Can't read Access Control File ".concat(aclDoc, ": ").concat(message)); + } else { + callbackFunction(true, 200, aclDoc); } - } - return fetcher.doneFetch(options, this.response); - } - }], [{ - key: "toString", - value: function toString() { - return 'XHTMLHandler'; - } - }, { - key: "register", - value: function register(fetcher) { - fetcher.mediatypes[_types__WEBPACK_IMPORTED_MODULE_9__.XHTMLContentType] = {}; + }); } - }]); - return XHTMLHandler; -}(Handler); -XHTMLHandler.pattern = new RegExp('application/xhtml'); -var XMLHandler = /*#__PURE__*/function (_Handler3) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(XMLHandler, _Handler3); - var _super3 = _createSuper(XMLHandler); - function XMLHandler() { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, XMLHandler); - return _super3.apply(this, arguments); - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(XMLHandler, [{ - key: "parse", - value: function parse(fetcher, responseText, options) { - var dom = _utils_js__WEBPACK_IMPORTED_MODULE_11__.parseXML(responseText); - - // XML Semantics defined by root element namespace - // figure out the root element - for (var c = 0; c < dom.childNodes.length; c++) { - var node = dom.childNodes[c]; - // is this node an element? - if (XMLHandler.isElement(node)) { - // We've found the first element, it's the root - var _ns = node.namespaceURI; + }); +} - // Is it RDF/XML? - if (_ns && _ns === _ns['rdf']) { - fetcher.addStatus(options.req, 'Has XML root element in the RDF namespace, so assume RDF/XML.'); - var rdfHandler = new RDFXMLHandler(this.response, dom); - return rdfHandler.parse(fetcher, responseText, options); - } - break; - } +/** + * Calls [[getACLorDefault]] and then (?) + */ +function getProspectiveHolder(_x) { + return _getProspectiveHolder.apply(this, arguments); +} +function _getProspectiveHolder() { + _getProspectiveHolder = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(targetDirectory) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + return _context.abrupt("return", new Promise(function (resolve, reject) { + return getACLorDefault((0, _rdflib.sym)(targetDirectory), function (ok, isDirectACL, targetDoc, targetACLDoc, defaultHolder) { + if (ok) { + return resolve(isDirectACL ? targetDoc : defaultHolder); + } + return reject(new Error("Error loading ".concat(targetDirectory))); + }); + })); + case 1: + case "end": + return _context.stop(); } + }, _callee); + })); + return _getProspectiveHolder.apply(this, arguments); +} +//# sourceMappingURL=acl.js.map - // Or it could be XHTML? - // Maybe it has an XHTML DOCTYPE? - if (dom.doctype) { - // log.info("We found a DOCTYPE in " + xhr.resource) - if (dom.doctype.name === 'html' && dom.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/) && dom.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)) { - fetcher.addStatus(options.req, 'Has XHTML DOCTYPE. Switching to XHTML Handler.\n'); - var xhtmlHandler = new XHTMLHandler(this.response, dom); - return xhtmlHandler.parse(fetcher, responseText, options); - } - } +/***/ }), - // Or what about an XHTML namespace? - var html = dom.getElementsByTagName('html')[0]; - if (html) { - var xmlns = html.getAttribute('xmlns'); - if (xmlns && xmlns.match(/^http:\/\/www.w3.org\/1999\/xhtml/)) { - fetcher.addStatus(options.req, 'Has a default namespace for ' + 'XHTML. Switching to XHTMLHandler.\n'); - var _xhtmlHandler = new XHTMLHandler(this.response, dom); - return _xhtmlHandler.parse(fetcher, responseText, options); - } - } +/***/ "./lib/acl/add-agent-buttons.js": +/*!**************************************!*\ + !*** ./lib/acl/add-agent-buttons.js ***! + \**************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - // At this point we should check the namespace document (cache it!) and - // look for a GRDDL transform - // @@ Get namespace document , parse it, look for grddl:namespaceTransform ?y - // Apply ?y to dom - // We give up. What dialect is this? - return fetcher.failFetch(options, 'Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n' + responseText.slice(0, 80), 901); - } - }], [{ - key: "toString", - value: function toString() { - return 'XMLHandler'; +"use strict"; + + +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.AddAgentButtons = void 0; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); +var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); +var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); +var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); +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); } +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; } +/** + * Contains the [[AddAgentButtons]] class + * @packageDocumentation + */ +/** + * Renders the Sharing pane's "+" button and the menus behind it, + * see https://github.com/solidos/userguide/blob/main/views/sharing/userguide.md#add + */ +var AddAgentButtons = /*#__PURE__*/function () { + function AddAgentButtons(groupList) { + (0, _classCallCheck2["default"])(this, AddAgentButtons); + this.groupList = groupList; + (0, _defineProperty2["default"])(this, "rootElement", void 0); + (0, _defineProperty2["default"])(this, "barElement", void 0); + (0, _defineProperty2["default"])(this, "isExpanded", false); + this.rootElement = groupList.controller.dom.createElement('div'); + this.barElement = groupList.controller.dom.createElement('div'); + } + (0, _createClass2["default"])(AddAgentButtons, [{ + key: "render", + value: function render() { + this.rootElement.innerHTML = ''; + this.rootElement.appendChild(this.renderAddButton()); + this.rootElement.appendChild(this.barElement); + return this.rootElement; } }, { - key: "register", - value: function register(fetcher) { - fetcher.mediatypes['text/xml'] = { - 'q': 0.5 - }; - fetcher.mediatypes['application/xml'] = { - 'q': 0.5 - }; + key: "renderAddButton", + value: function renderAddButton() { + var _this = this; + return widgets.button(this.groupList.controller.dom, "".concat(_iconBase.icons.iconBase, "noun_34653_green.svg"), 'Add ...', function () { + _this.toggleBar(); + _this.renderBar(); + }); } }, { - key: "isElement", - value: function isElement(node) { - return node.nodeType === Node.ELEMENT_NODE; - } - }]); - return XMLHandler; -}(Handler); -XMLHandler.pattern = new RegExp('(text|application)/(.*)xml'); -var HTMLHandler = /*#__PURE__*/function (_Handler4) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(HTMLHandler, _Handler4); - var _super4 = _createSuper(HTMLHandler); - function HTMLHandler() { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, HTMLHandler); - return _super4.apply(this, arguments); - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(HTMLHandler, [{ - key: "parse", - value: function parse(fetcher, responseText, options) { - var kb = fetcher.store; - - // We only handle XHTML so we have to figure out if this is XML - // log.info("Sniffing HTML " + xhr.resource + " for XHTML.") - if (isXML(responseText)) { - fetcher.addStatus(options.req, "Has an XML declaration. We'll assume " + "it's XHTML as the content-type was text/html.\n"); - var xhtmlHandler = new XHTMLHandler(this.response); - return xhtmlHandler.parse(fetcher, responseText, options); - } - - // DOCTYPE html - if (isXHTML(responseText)) { - fetcher.addStatus(options.req, 'Has XHTML DOCTYPE. Switching to XHTMLHandler.\n'); - var _xhtmlHandler2 = new XHTMLHandler(this.response); - return _xhtmlHandler2.parse(fetcher, responseText, options); - } - - // xmlns - if (isXMLNS(responseText)) { - fetcher.addStatus(options.req, 'Has default namespace for XHTML, so switching to XHTMLHandler.\n'); - var _xhtmlHandler3 = new XHTMLHandler(this.response); - return _xhtmlHandler3.parse(fetcher, responseText, options); - } - - // dc:title - // no need to escape '/' here - var titleMatch = new RegExp('([\\s\\S]+?)', 'im').exec(responseText); - if (titleMatch) { - kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(titleMatch[1]), options.resource); // think about xml:lang later + key: "renderBar", + value: function renderBar() { + this.barElement.innerHTML = ''; + if (!this.isExpanded) { + return; } - - kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode); - fetcher.addStatus(options.req, 'non-XML HTML document, not parsed for data.'); - return fetcher.doneFetch(options, this.response); - } - }], [{ - key: "toString", - value: function toString() { - return 'HTMLHandler'; + this.barElement.appendChild(this.renderPersonButton()); + this.barElement.appendChild(this.renderGroupButton()); + this.barElement.appendChild(this.renderPublicButton()); + this.barElement.appendChild(this.renderAuthenticatedAgentButton()); + this.barElement.appendChild(this.renderBotButton()); + this.barElement.appendChild(this.renderAppsButton()); } }, { - key: "register", - value: function register(fetcher) { - fetcher.mediatypes['text/html'] = { - 'q': 0.9 - }; + key: "renderSimplifiedBar", + value: function renderSimplifiedBar(button) { + var _this2 = this; + Array.from(this.barElement.children).filter(function (element) { + return element !== button; + }).forEach(function (element) { + return _this2.barElement.removeChild(element); + }); } - }]); - return HTMLHandler; -}(Handler); -HTMLHandler.pattern = new RegExp('text/html'); -var JsonLdHandler = /*#__PURE__*/function (_Handler5) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(JsonLdHandler, _Handler5); - var _super5 = _createSuper(JsonLdHandler); - function JsonLdHandler() { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, JsonLdHandler); - return _super5.apply(this, arguments); - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(JsonLdHandler, [{ - key: "parse", - value: function parse(fetcher, responseText, options, response) { - var kb = fetcher.store; - return new Promise(function (resolve, reject) { - try { - (0,_jsonldparser__WEBPACK_IMPORTED_MODULE_15__["default"])(responseText, kb, options.original.value, function () { - resolve(fetcher.doneFetch(options, response)); - }); - } catch (err) { - var msg = 'Error trying to parse ' + options.resource + ' as JSON-LD:\n' + err; // not err.stack -- irrelevant - resolve(fetcher.failFetch(options, msg, 'parse_error', response)); - } + }, { + key: "renderPersonButton", + value: function renderPersonButton() { + var _this3 = this; + return widgets.button(this.groupList.controller.dom, _iconBase.icons.iconBase + widgets.iconForClass['vcard:Individual'], 'Add Person', function (event) { + _this3.renderSimplifiedBar(event.target); + _this3.renderNameForm(ns.vcard('Individual'), 'person').then(function (name) { + return _this3.addPerson(name); + }).then(function () { + return _this3.renderCleanup(); + })["catch"](function (error) { + return _this3.groupList.controller.renderStatus(error); + }); }); } - }], [{ - key: "toString", - value: function toString() { - return 'JsonLdHandler'; - } }, { - key: "register", - value: function register(fetcher) { - fetcher.mediatypes['application/ld+json'] = { - 'q': 0.9 - }; - } - }]); - return JsonLdHandler; -}(Handler); -JsonLdHandler.pattern = /application\/ld\+json/; -var TextHandler = /*#__PURE__*/function (_Handler6) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(TextHandler, _Handler6); - var _super6 = _createSuper(TextHandler); - function TextHandler() { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, TextHandler); - return _super6.apply(this, arguments); - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(TextHandler, [{ - key: "parse", - value: function parse(fetcher, responseText, options) { - // We only speak dialects of XML right now. Is this XML? - - // Look for an XML declaration - if (isXML(responseText)) { - fetcher.addStatus(options.req, 'Warning: ' + options.resource + " has an XML declaration. We'll assume " + "it's XML but its content-type wasn't XML.\n"); - var xmlHandler = new XMLHandler(this.response); - return xmlHandler.parse(fetcher, responseText, options); - } - - // Look for an XML declaration - if (responseText.slice(0, 500).match(/xmlns:/)) { - fetcher.addStatus(options.req, "May have an XML namespace. We'll assume " + "it's XML but its content-type wasn't XML.\n"); - var _xmlHandler = new XMLHandler(this.response); - return _xmlHandler.parse(fetcher, responseText, options); - } - - // We give up finding semantics - this is not an error, just no data - fetcher.addStatus(options.req, 'Plain text document, no known RDF semantics.'); - return fetcher.doneFetch(options, this.response); - } - }], [{ - key: "toString", - value: function toString() { - return 'TextHandler'; + key: "renderGroupButton", + value: function renderGroupButton() { + var _this4 = this; + return widgets.button(this.groupList.controller.dom, _iconBase.icons.iconBase + widgets.iconForClass['vcard:Group'], 'Add Group', function (event) { + _this4.renderSimplifiedBar(event.target); + _this4.renderNameForm(ns.vcard('Group'), 'group').then(function (name) { + return _this4.addGroup(name); + }).then(function () { + return _this4.renderCleanup(); + })["catch"](function (error) { + return _this4.groupList.controller.renderStatus(error); + }); + }); } }, { - key: "register", - value: function register(fetcher) { - fetcher.mediatypes['text/plain'] = { - 'q': 0.5 - }; - } - }]); - return TextHandler; -}(Handler); -TextHandler.pattern = new RegExp('text/plain'); -var N3Handler = /*#__PURE__*/function (_Handler7) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(N3Handler, _Handler7); - var _super7 = _createSuper(N3Handler); - function N3Handler() { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, N3Handler); - return _super7.apply(this, arguments); - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(N3Handler, [{ - key: "parse", - value: function parse(fetcher, responseText, options, response) { - // Parse the text of this N3 file - var kb = fetcher.store; - var p = (0,_n3parser__WEBPACK_IMPORTED_MODULE_16__["default"])(kb, kb, options.original.value, options.original.value, null, null, '', null); - // p.loadBuf(xhr.responseText) - try { - p.loadBuf(responseText); - } catch (err) { - var msg = 'Error trying to parse ' + options.resource + ' as Notation3:\n' + err; // not err.stack -- irrelevant - return fetcher.failFetch(options, msg, 'parse_error', response); - } - fetcher.addStatus(options.req, 'N3 parsed: ' + p.statementCount + ' triples in ' + p.lines + ' lines.'); - fetcher.store.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode); - return fetcher.doneFetch(options, this.response); - } - }], [{ - key: "toString", - value: function toString() { - return 'N3Handler'; + key: "renderNameForm", + value: function renderNameForm(type, noun) { + return widgets.askName(this.groupList.controller.dom, this.groupList.store, this.barElement, ns.vcard('URI'), type, noun); } }, { - key: "register", - value: function register(fetcher) { - fetcher.mediatypes['text/n3'] = { - 'q': '1.0' - }; // as per 2008 spec - /* - fetcher.mediatypes['application/x-turtle'] = { - 'q': 1.0 - } // pre 2008 - */ - fetcher.mediatypes['text/turtle'] = { - 'q': 1.0 - }; // post 2008 + key: "renderPublicButton", + value: function renderPublicButton() { + var _this5 = this; + return widgets.button(this.groupList.controller.dom, _iconBase.icons.iconBase + widgets.iconForClass['foaf:Agent'], 'Add Everyone', function () { + return _this5.addAgent(ns.foaf('Agent').uri).then(function () { + return _this5.groupList.controller.renderTemporaryStatus('Adding the general public to those who can read. Drag the globe to a different level to give them more access.'); + }).then(function () { + return _this5.renderCleanup(); + }); + }); } - }]); - return N3Handler; -}(Handler); -N3Handler.pattern = new RegExp('(application|text)/(x-)?(rdf\\+)?(n3|turtle)'); -var defaultHandlers = { - RDFXMLHandler: RDFXMLHandler, - XHTMLHandler: XHTMLHandler, - XMLHandler: XMLHandler, - HTMLHandler: HTMLHandler, - TextHandler: TextHandler, - N3Handler: N3Handler, - JsonLdHandler: JsonLdHandler -}; -function isXHTML(responseText) { - var docTypeStart = responseText.indexOf(''); - if (docTypeStart === -1 || docTypeEnd === -1 || docTypeStart > docTypeEnd) { - return false; - } - return responseText.substr(docTypeStart, docTypeEnd - docTypeStart).indexOf('XHTML') !== -1; -} -function isXML(responseText) { - var match = responseText.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/); - return !!match; -} -function isXMLNS(responseText) { - var match = responseText.match(/[^(/); - return !!match; -} -/** Fetcher - * - * The Fetcher object is a helper object for a quadstore - * which turns it from an offline store to an online store. - * The fetcher deals with loading data files rom the web, - * figuring how to parse them. It will also refresh, remove, the data - * and put back the data to the web. - */ -var Fetcher = /*#__PURE__*/function () { - /** Denoting this session */ - - /** - * this.requested[uri] states: - * undefined no record of web access or records reset - * true has been requested, fetch in progress - * 'done' received, Ok - * 401 Not logged in - * 403 HTTP status unauthorized - * 404 Resource does not exist. Can be created etc. - * 'redirected' In attempt to counter CORS problems retried. - * 'parse_error' Parse error - * 'unsupported_protocol' URI is not a protocol Fetcher can deal with - * other strings mean various other errors. - */ - - /** List of timeouts associated with a requested URL */ - - /** Redirected from *key uri* to *value uri* */ - - /** fetchCallbacks[uri].push(callback) */ - - /** Keep track of explicit 404s -> we can overwrite etc */ - - // TODO: Document this - - /** Methods added by calling Util.callbackify in the constructor*/ - - function Fetcher(store) { - var _this = this; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, Fetcher); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "store", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "timeout", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "_fetch", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "mediatypes", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "appNode", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "requested", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "timeouts", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "redirectedTo", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "fetchQueue", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "fetchCallbacks", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "nonexistent", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "lookedUp", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "handlers", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "ns", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "fireCallbacks", void 0); - this.store = store || new _store__WEBPACK_IMPORTED_MODULE_17__["default"](); - this.ns = getNS(this.store.rdfFactory); - this.timeout = options.timeout || 30000; - - // solidFetcher is deprecated - this._fetch = options.fetch || typeof __webpack_require__.g !== 'undefined' && (__webpack_require__.g.solidFetcher || __webpack_require__.g.solidFetch) || typeof window !== 'undefined' && (window.solidFetcher || window.solidFetch) || (cross_fetch__WEBPACK_IMPORTED_MODULE_8___default()); - if (!this._fetch) { - throw new Error('No _fetch function available for Fetcher'); + }, { + key: "renderAuthenticatedAgentButton", + value: function renderAuthenticatedAgentButton() { + var _this6 = this; + return widgets.button(this.groupList.controller.dom, "".concat(_iconBase.icons.iconBase, "noun_99101.svg"), 'Anyone logged In', function () { + return _this6.addAgent(ns.acl('AuthenticatedAgent').uri).then(function () { + return _this6.groupList.controller.renderTemporaryStatus('Adding anyone logged in to those who can read. Drag the ID icon to a different level to give them more access.'); + }).then(function () { + return _this6.renderCleanup(); + }); + }); } - // This is the name of the graph we store all the HTTP metadata in - this.appNode = this.store.sym('chrome://TheCurrentSession'); - // this.appNode = this.store.rdfFactory.blankNode() // Needs to have a URI in tests - this.store.fetcher = this; // Bi-linked - this.requested = {}; - this.timeouts = {}; - this.redirectedTo = {}; - this.fetchQueue = {}; - this.fetchCallbacks = {}; - this.nonexistent = {}; - this.lookedUp = {}; - this.handlers = []; - this.mediatypes = { - 'image/*': { - 'q': 0.9 - }, - '*/*': { - 'q': 0.1 - } // Must allow access to random content - }; - - // Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail', - // 'refresh', 'retract', 'done']) - // In switching to fetch(), 'recv', 'headers' and 'load' do not make sense - _utils_js__WEBPACK_IMPORTED_MODULE_11__.callbackify(this, ['request', 'fail', 'refresh', 'retract', 'done']); - Object.keys(options.handlers || defaultHandlers).map(function (key) { - return _this.addHandler(defaultHandlers[key]); - }); - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(Fetcher, [{ - key: "load", - value: - /** - * Promise-based load function - * - * Loads a web resource or resources into the store. - * - * A resource may be given as NamedNode object, or as a plain URI. - * an array of resources will be given, in which they will be fetched in parallel. - * By default, the HTTP headers are recorded also, in the same store, in a separate graph. - * This allows code like editable() for example to test things about the resource. - * - * @param uri {Array|Array|RDFlibNamedNode|string} - * - * @param [options={}] {Object} - * - * @param [options.fetch] {Function} - * - * @param [options.referringTerm] {RDFlibNamedNode} Referring term, the resource which - * referred to this (for tracking bad links) - * - * @param [options.contentType] {string} Provided content type (for writes) - * - * @param [options.forceContentType] {string} Override the incoming header to - * force the data to be treated as this content-type (for reads) - * - * @param [options.force] {boolean} Load the data even if loaded before. - * Also sets the `Cache-Control:` header to `no-cache` - * - * @param [options.baseURI=docuri] {Node|string} Original uri to preserve - * through proxying etc (`xhr.original`). - * - * @param [options.proxyUsed] {boolean} Whether this request is a retry via - * a proxy (generally done from an error handler) - * - * @param [options.withCredentials] {boolean} flag for XHR/CORS etc - * - * @param [options.clearPreviousData] {boolean} Before we parse new data, - * clear old, but only on status 200 responses - * - * @param [options.noMeta] {boolean} Prevents the addition of various metadata - * triples (about the fetch request) to the store - * - * @param [options.noRDFa] {boolean} - * - * @returns {Promise} - */ - function load(uri) { - var _this2 = this; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - options = Object.assign({}, options); // Take a copy as we add stuff to the options!! - if (uri instanceof Array) { - return Promise.all(uri.map(function (x) { - return _this2.load(x, Object.assign({}, options)); - })); - } - var uriIn = uri; - var docuri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uriIn); - docuri = docuri.split('#')[0]; - options = this.initFetchOptions(docuri, options); - // if metadata flaged clear cache and removeDocument - var meta = this.appNode; - var kb = this.store; - var requests = kb.statementsMatching(undefined, this.ns.link('requestedURI'), kb.sym(docuri), meta).map(function (st) { - return st.subject; + }, { + key: "renderBotButton", + value: function renderBotButton() { + var _this7 = this; + return widgets.button(this.groupList.controller.dom, _iconBase.icons.iconBase + 'noun_Robot_849764.svg', 'A Software Agent (bot)', function (event) { + _this7.renderSimplifiedBar(event.target); + _this7.renderNameForm(ns.schema('Application'), 'bot').then(function (name) { + return _this7.addBot(name); + }).then(function () { + return _this7.renderCleanup(); + }); }); - var _iterator = _createForOfIteratorHelper(requests), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var request = _step.value; - var _response = kb.any(request, this.ns.link('response'), null, meta); - if (_response !== undefined) { - // ts - var quad = kb.statementsMatching(_response, this.ns.link('outOfDate'), true, meta); - kb.remove(quad); - options.force = true; - options.clearPreviousData = true; + } + }, { + key: "renderAppsButton", + value: function renderAppsButton() { + var _this8 = this; + return widgets.button(this.groupList.controller.dom, "".concat(_iconBase.icons.iconBase, "noun_15177.svg"), 'A Web App (origin)', function (event) { + _this8.renderSimplifiedBar(event.target); + var eventContext = { + div: _this8.barElement, + dom: _this8.groupList.controller.dom + }; + var existingApps = _this8.renderAppsTable(eventContext)["catch"](function (error) { + return _this8.groupList.controller.renderStatus(error); + }); + _this8.renderAppsView(); + var newApp = _this8.renderNameForm(ns.schema('WebApplication'), 'webapp domain').then(function (name) { + return _this8.getOriginFromName(name); + }); + Promise.race([existingApps, newApp]).then(function (origin) { + if (origin) { + _this8.groupList.addNewURI(origin); } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); + }).then(function () { + return _this8.renderCleanup(); + }); + }); + } + }, { + key: "renderAppsView", + value: function renderAppsView() { + var _this9 = this; + var trustedApplications = this.groupList.controller.context.session.paneRegistry.byName('trustedApplications'); + if (trustedApplications) { + var trustedApplicationsElement = trustedApplications.render(null, this.groupList.controller.context); + trustedApplicationsElement.setAttribute('style', style.trustedAppController); + var cancelButton = widgets.cancelButton(this.groupList.controller.dom, function () { + return _this9.renderCleanup(); + }); + cancelButton.setAttribute('style', style.trustedAppCancelButton); + trustedApplicationsElement.insertBefore(cancelButton, trustedApplicationsElement.firstChild); + this.barElement.appendChild(trustedApplicationsElement); } - var initialisedOptions = this.initFetchOptions(docuri, options); - return this.pendingFetchPromise(docuri, initialisedOptions.baseURI, initialisedOptions); } }, { - key: "pendingFetchPromise", + key: "renderAppsTable", value: function () { - var _pendingFetchPromise = (0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().mark(function _callee(uri, originalUri, options) { - var _this3 = this; - var pendingPromise; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().wrap(function _callee$(_context) { + var _renderAppsTable = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(eventContext) { + var _this10 = this; + var trustedApps, trustedOrigins; + return _regenerator["default"].wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: - _context.t0 = !options.force; - if (!_context.t0) { - _context.next = 5; - break; - } - _context.next = 4; - return this.fetchQueue[originalUri]; - case 4: - _context.t0 = _context.sent; - case 5: - if (!_context.t0) { - _context.next = 9; - break; - } - pendingPromise = this.fetchQueue[originalUri]; - _context.next = 12; - break; - case 9: - pendingPromise = Promise.race([this.setRequestTimeout(uri, options), this.fetchUri(uri, options)]); - this.fetchQueue[originalUri] = pendingPromise; - - // Clean up the queued promise after a time, if it's resolved - this.cleanupFetchRequest(originalUri, undefined, this.timeout); - case 12: - return _context.abrupt("return", pendingPromise.then(function (x) { - if (uri in _this3.timeouts) { - _this3.timeouts[uri].forEach(clearTimeout); - delete _this3.timeouts[uri]; - } - return x; + _context.next = 2; + return (0, _login.ensureLoadedProfile)(eventContext); + case 2: + trustedApps = this.groupList.store.each(eventContext.me, ns.acl('trustedApp')); // @@ TODO fix as + trustedOrigins = trustedApps.flatMap(function (app) { + return _this10.groupList.store.each(app, ns.acl('origin')); + }); // @@ TODO fix as + this.barElement.appendChild(this.groupList.controller.dom.createElement('p')).textContent = "You have ".concat(trustedOrigins.length, " selected web apps."); + return _context.abrupt("return", new Promise(function (resolve, reject) { + var appsTable = _this10.barElement.appendChild(_this10.groupList.controller.dom.createElement('table')); + appsTable.setAttribute('style', style.trustedAppAddApplicationsTable); + trustedApps.forEach(function (app) { + var origin = _this10.groupList.store.any(app, ns.acl('origin')); // @@ TODO fix as + if (!origin) { + reject(new Error("Unable to pick app: ".concat(app.value))); + } + var thingTR = widgets.personTR(_this10.groupList.controller.dom, ns.acl('origin'), origin, {}); + var innerTable = _this10.groupList.controller.dom.createElement('table'); + var innerRow = innerTable.appendChild(_this10.groupList.controller.dom.createElement('tr')); + var innerLeftColumn = innerRow.appendChild(_this10.groupList.controller.dom.createElement('td')); + innerLeftColumn.appendChild(thingTR); + var innerMiddleColumn = innerRow.appendChild(_this10.groupList.controller.dom.createElement('td')); + innerMiddleColumn.textContent = "Give access to ".concat(_this10.groupList.controller.noun, " ").concat(utils.label(_this10.groupList.controller.subject), "?"); + var innerRightColumn = innerRow.appendChild(_this10.groupList.controller.dom.createElement('td')); + innerRightColumn.appendChild(widgets.continueButton(_this10.groupList.controller.dom, function () { + return resolve(origin.value); + })); + appsTable.appendChild(innerTable); + }); })); - case 13: + case 6: case "end": return _context.stop(); } }, _callee, this); })); - function pendingFetchPromise(_x, _x2, _x3) { - return _pendingFetchPromise.apply(this, arguments); + function renderAppsTable(_x) { + return _renderAppsTable.apply(this, arguments); } - return pendingFetchPromise; + return renderAppsTable; }() - /** - * @param _options - DEPRECATED - */ }, { - key: "cleanupFetchRequest", - value: function cleanupFetchRequest(originalUri, _options, timeout) { - var _this4 = this; - if (_options !== undefined) { - console.warn("_options is deprecated"); - } - this.timeouts[originalUri] = (this.timeouts[originalUri] || []).concat(setTimeout(function () { - if (!_this4.isPending(originalUri)) { - delete _this4.fetchQueue[originalUri]; - } - }, timeout)); + key: "renderCleanup", + value: function renderCleanup() { + this.renderBar(); + this.groupList.render(); } }, { - key: "initFetchOptions", - value: function initFetchOptions(uri, options) { - var kb = this.store; - var isGet = !options.method || options.method.toUpperCase() === 'GET'; - if (!isGet) { - options.force = true; - } - options.resource = kb.rdfFactory.namedNode(uri); // This might be proxified - options.baseURI = options.baseURI || uri; // Preserve though proxying etc - options.original = kb.rdfFactory.namedNode(options.baseURI); - options.req = kb.bnode(); - options.headers = options.headers || new cross_fetch__WEBPACK_IMPORTED_MODULE_8__.Headers(); - if (options.contentType) { - // @ts-ignore - options.headers['content-type'] = options.contentType; - } - if (options.force) { - options.cache = 'no-cache'; - } - var acceptString = this.acceptString(); - // @ts-ignore - options.headers['accept'] = acceptString; - var requestedURI = Fetcher.offlineOverride(uri); - options.requestedURI = requestedURI; - Fetcher.setCredentials(requestedURI, options); - var actualProxyURI = Fetcher.proxyIfNecessary(requestedURI); - if (requestedURI !== actualProxyURI) { - options.proxyUsed = true; + key: "addPerson", + value: function () { + var _addPerson = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(name) { + var domainNameRegexp; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (name) { + _context2.next = 2; + break; + } + return _context2.abrupt("return", this.toggleBar()); + case 2: + // user cancelled + domainNameRegexp = /^https?:/i; + if (name.match(domainNameRegexp)) { + _context2.next = 5; + break; + } + return _context2.abrupt("return", Promise.reject(new Error('Not a http URI'))); + case 5: + // @@ check it actually is a person and has an owner who agrees they own it + debug.log("Adding to ACL person: ".concat(name)); + _context2.next = 8; + return this.groupList.addNewURI(name); + case 8: + this.toggleBar(); + case 9: + case "end": + return _context2.stop(); + } + }, _callee2, this); + })); + function addPerson(_x2) { + return _addPerson.apply(this, arguments); } - options.actualProxyURI = actualProxyURI; - return options; - } - - /** - * (The promise chain ends in either a `failFetch()` or a `doneFetch()`) - * - * @param docuri {string} - * @param options {Object} - * - * @returns {Promise} fetch() result or an { error, status } object - */ + return addPerson; + }() }, { - key: "fetchUri", - value: function fetchUri(docuri, options) { - var _this5 = this; - if (!docuri) { - return Promise.reject(new Error('Cannot fetch an empty uri')); - } - if (Fetcher.unsupportedProtocol(docuri)) { - return this.failFetch(options, 'fetcher: Unsupported protocol', 'unsupported_protocol'); - } - var state = this.getState(docuri); - if (!options.force) { - if (state === 'fetched') { - // URI already fetched and added to store - return Promise.resolve( - // @ts-ignore This is not a valid response object - this.doneFetch(options, { - status: 200, - ok: true, - statusText: 'Already loaded into quadstore.' - })); - } - if (state === 'failed' && this.requested[docuri] === 404) { - // Remember nonexistence - var _message = 'Previously failed: ' + this.requested[docuri]; - // @ts-ignore This is not a valid response object - var dummyResponse = { - url: docuri, - // This does not comply to Fetch spec, it can be a string value in rdflib - status: this.requested[docuri], - statusText: _message, - responseText: _message, - headers: new cross_fetch__WEBPACK_IMPORTED_MODULE_8__.Headers(), - // Headers() ??? - ok: false, - body: null, - bodyUsed: false, - size: 0, - timeout: 0 - }; - return this.failFetch(options, _message, this.requested[docuri], dummyResponse); - } - } else { - // options.force == true - delete this.nonexistent[docuri]; - } - this.fireCallbacks('request', [docuri]); - this.requested[docuri] = true; // mark this uri as 'requested' - - if (!options.noMeta) { - this.saveRequestMetadata(docuri, options); + key: "addGroup", + value: function () { + var _addGroup = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(name) { + var domainNameRegexp; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (name) { + _context3.next = 2; + break; + } + return _context3.abrupt("return", this.toggleBar()); + case 2: + // user cancelled + domainNameRegexp = /^https?:/i; + if (name.match(domainNameRegexp)) { + _context3.next = 5; + break; + } + return _context3.abrupt("return", Promise.reject(new Error('Not a http URI'))); + case 5: + // @@ check it actually is a group and has an owner who agrees they own it + debug.log('Adding to ACL group: ' + name); + _context3.next = 8; + return this.groupList.addNewURI(name); + case 8: + this.toggleBar(); + case 9: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function addGroup(_x3) { + return _addGroup.apply(this, arguments); } - var actualProxyURI = options.actualProxyURI; - - // Map might get mistakenly added into headers - // error TS2339: Property 'map' does not exist on type 'Headers'. - /* let map - if (options.headers && map in options.headers) { - delete options.headers.map - } */ - - return this._fetch(actualProxyURI, options).then(function (response) { - return _this5.handleResponse(response, docuri, options); - }, function (error) { - // @@ handleError? - // @ts-ignore Invalid response object - var dummyResponse = { - url: actualProxyURI, - status: 999, - // @@ what number/string should fetch failures report? - statusText: (error.name || 'network failure') + ': ' + (error.errno || error.code || error.type), - responseText: error.message, - headers: new cross_fetch__WEBPACK_IMPORTED_MODULE_8__.Headers(), - // Headers() ??? - ok: false, - body: null, - bodyUsed: false, - size: 0, - timeout: 0 - }; - // console.log('Fetcher: <' + actualProxyURI + '> Non-HTTP fetch exception: ' + error) - return _this5.handleError(dummyResponse, docuri, options); // possible credentials retry - // return this.failFetch(options, 'fetch failed: ' + error, 999, dummyResponse) // Fake status code: fetch exception - - // handleError expects a response so we fake some important bits. - /* - this.handleError(, docuri, options) - */ - }); - } - - /** - * Asks for a doc to be loaded if necessary then calls back - * - * Calling methods: - * nowOrWhenFetched (uri, userCallback) - * nowOrWhenFetched (uri, options, userCallback) - * nowOrWhenFetched (uri, referringTerm, userCallback, options) <-- old - * nowOrWhenFetched (uri, referringTerm, userCallback) <-- old - * - * Options include: - * referringTerm The document in which this link was found. - * this is valuable when finding the source of bad URIs - * force boolean. Never mind whether you have tried before, - * load this from scratch. - * forceContentType Override the incoming header to force the data to be - * treated as this content-type. - * - * Callback function takes: - * - * ok True if the fetch worked, and got a 200 response. - * False if any error happened - * - * errmessage Text error message if not OK. - * - * response The fetch Response object (was: XHR) if there was was one - * includes response.status as the HTTP status if any. - */ + return addGroup; + }() }, { - key: "nowOrWhenFetched", - value: function nowOrWhenFetched(uriIn, p2, userCallback) { - var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - var uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uriIn); - if (typeof p2 === 'function') { - // nowOrWhenFetched (uri, userCallback) - userCallback = p2; - } else if (typeof p2 === 'undefined') {// original calling signature - // referringTerm = undefined - } else if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_19__.isNamedNode)(p2)) { - // referringTerm = p2 - options.referringTerm = p2; - } else { - // nowOrWhenFetched (uri, options, userCallback) - options = p2; + key: "addAgent", + value: function () { + var _addAgent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(agentUri) { + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return this.groupList.addNewURI(agentUri); + case 2: + this.toggleBar(); + case 3: + case "end": + return _context4.stop(); + } + }, _callee4, this); + })); + function addAgent(_x4) { + return _addAgent.apply(this, arguments); } - this.load(uri, options).then(function (fetchResponse) { - if (userCallback) { - if (fetchResponse) { - if (fetchResponse.ok) { - userCallback(true, 'OK', fetchResponse); - } else { - var oops = 'HTTP error: Status ' + fetchResponse.status + ' (' + fetchResponse.statusText + ')'; - if (fetchResponse.responseText) { - oops += ' ' + fetchResponse.responseText; // not in 404, dns error, nock failure + return addAgent; + }() + }, { + key: "addBot", + value: function () { + var _addBot = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(name) { + var domainNameRegexp; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (name) { + _context5.next = 2; + break; } - - userCallback(false, oops, fetchResponse); - } - } else { - var _oops = '@@ nowOrWhenFetched: no response object!'; - userCallback(false, _oops); + return _context5.abrupt("return", this.toggleBar()); + case 2: + // user cancelled + domainNameRegexp = /^https?:/i; + if (name.match(domainNameRegexp)) { + _context5.next = 5; + break; + } + return _context5.abrupt("return", Promise.reject(new Error('Not a http URI'))); + case 5: + // @@ check it actually is a bot and has an owner who agrees they own it + debug.log('Adding to ACL bot: ' + name); + _context5.next = 8; + return this.groupList.addNewURI(name); + case 8: + this.toggleBar(); + case 9: + case "end": + return _context5.stop(); } - } - }, function (err) { - var message = err.message || err.statusText; - message = 'Failed to load <' + uri + '> ' + message; - if (err.response && err.response.status) { - message += ' status: ' + err.response.status; - } - userCallback(false, message, err.response); - }); - } - - /** - * Records a status message (as a literal node) by appending it to the - * request's metadata status collection. - * - */ - }, { - key: "addStatus", - value: function addStatus(req, statusMessage) { - // - var now = new Date(); - statusMessage = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '.' + now.getMilliseconds() + '] ' + statusMessage; - // - var kb = this.store; - var statusNode = kb.the(req, this.ns.link('status')); - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_19__.isCollection)(statusNode)) { - statusNode.append(kb.rdfFactory.literal(statusMessage)); - } else { - _log__WEBPACK_IMPORTED_MODULE_20__["default"].warn('web.js: No list to add to: ' + statusNode + ',' + statusMessage); + }, _callee5, this); + })); + function addBot(_x5) { + return _addBot.apply(this, arguments); } - } - - /** - * Records errors in the system on failure: - * - * - Adds an entry to the request status collection - * - Adds an error triple with the fail message to the metadata - * - Fires the 'fail' callback - * - Rejects with an error result object, which has a response object if any - */ + return addBot; + }() }, { - key: "failFetch", - value: function failFetch(options, errorMessage, statusCode, response) { - this.addStatus(options.req, errorMessage); - if (!options.noMeta) { - this.store.add(options.original, this.ns.link('error'), this.store.rdfFactory.literal(errorMessage)); - } - var meth = (options.method || 'GET').toUpperCase(); - var isGet = meth === 'GET' || meth === 'HEAD'; - if (isGet) { - // only cache the status code on GET or HEAD - if (!options.resource.equals(options.original)) { - // console.log('@@ Recording failure ' + meth + ' original ' + options.original +option '( as ' + options.resource + ') : ' + statusCode) - } else { - // console.log('@@ Recording ' + meth + ' failure for ' + options.original + ': ' + statusCode) - } - this.requested[_uri__WEBPACK_IMPORTED_MODULE_21__.docpart(options.original.value)] = statusCode; - this.fireCallbacks('fail', [options.original.value, errorMessage]); + key: "getOriginFromName", + value: function () { + var _getOriginFromName = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(name) { + var domainNameRegexp, origin; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (name) { + _context6.next = 2; + break; + } + return _context6.abrupt("return", Promise.resolve()); + case 2: + // user cancelled + domainNameRegexp = /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i; // https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch08s15.html + if (name.match(domainNameRegexp)) { + _context6.next = 5; + break; + } + return _context6.abrupt("return", Promise.reject(new Error('Not a domain name'))); + case 5: + origin = 'https://' + name; + debug.log('Adding to ACL origin: ' + origin); + this.toggleBar(); + return _context6.abrupt("return", origin); + case 9: + case "end": + return _context6.stop(); + } + }, _callee6, this); + })); + function getOriginFromName(_x6) { + return _getOriginFromName.apply(this, arguments); } - var err = new Error('Fetcher: ' + errorMessage); - - // err.ok = false // Is taken as a response, will work too @@ phase out? - err.status = statusCode; - err.statusText = errorMessage; - err.response = response; - return Promise.reject(err); - } - - // in the why part of the quad distinguish between HTML and HTTP header - // Reverse is set iif the link was rev= as opposed to rel= + return getOriginFromName; + }() }, { - key: "linkData", - value: function linkData(originalUri, rel, uri, why, reverse) { - if (!uri) return; - var kb = this.store; - var predicate; - // See http://www.w3.org/TR/powder-dr/#httplink for describedby 2008-12-10 - var obj = kb.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_21__.join(uri, originalUri.value)); - if (rel === 'alternate' || rel === 'seeAlso' || rel === 'meta' || rel === 'describedby') { - if (obj.value === originalUri.value) { - return; - } - predicate = this.ns.rdfs('seeAlso'); - } else if (rel === 'type') { - predicate = kb.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'); - } else { - // See https://www.iana.org/assignments/link-relations/link-relations.xml - // Alas not yet in RDF yet for each predicate - // encode space in e.g. rel="shortcut icon" - predicate = kb.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_21__.join(encodeURIComponent(rel), 'http://www.iana.org/assignments/link-relations/')); - } - if (reverse) { - kb.add(obj, predicate, originalUri, why); - } else { - kb.add(originalUri, predicate, obj, why); - } + key: "toggleBar", + value: function toggleBar() { + this.isExpanded = !this.isExpanded; } - }, { - key: "parseLinkHeader", - value: function parseLinkHeader(linkHeader, originalUri, reqNode) { - if (!linkHeader) { - return; - } + }]); + return AddAgentButtons; +}(); +exports.AddAgentButtons = AddAgentButtons; +//# sourceMappingURL=add-agent-buttons.js.map - // const linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^()<>@,;:"/[]?={} \t]+)|("[^"]*")))*(,|$)/g - // const paramexp = /[^()<>@,;:"/[]?={} \t]+=(([^()<>@,;:"/[]?={} \t]+)|("[^"]*"))/g +/***/ }), - // From https://www.dcode.fr/regular-expression-simplificator: - // const linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} t]+=["]))*[,$]/g - // const paramexp = /[^\\<>@,;:"\/\[\]?={} \t]+=["])/g - // Original: - var linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g; - var paramexp = /[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g; - var matches = linkHeader.match(linkexp); - if (matches == null) return; - for (var i = 0; i < matches.length; i++) { - var split = matches[i].split('>'); - var href = split[0].substring(1); - var ps = split[1]; - var s = ps.match(paramexp); - if (s == null) return; - for (var j = 0; j < s.length; j++) { - var p = s[j]; - var paramsplit = p.split('='); - // var name = paramsplit[0] - var rel = paramsplit[1].replace(/["']/g, ''); // '" - this.linkData(originalUri, rel, href, reqNode); - } - } - } - }, { - key: "doneFetch", - value: function doneFetch(options, response) { - this.addStatus(options.req, 'Done.'); - this.requested[options.original.value] = 'done'; - this.fireCallbacks('done', [options.original.value]); - response.req = options.req; // Set the request meta blank node +/***/ "./lib/acl/index.js": +/*!**************************!*\ + !*** ./lib/acl/index.js ***! + \**************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - return response; - } +"use strict"; - /** - * Note two nodes are now smushed - * If only one was flagged as looked up, then the new node is looked up again, - * which will make sure all the URIs are dereferenced - */ - }, { - key: "nowKnownAs", - value: function nowKnownAs(was, now) { - if (this.lookedUp[was.value]) { - // Transfer userCallback - if (!this.lookedUp[now.value]) { - this.lookUpThing(now, was); - } - } else if (this.lookedUp[now.value]) { - if (!this.lookedUp[was.value]) { - this.lookUpThing(was, now); - } - } - } - /** - * Writes back to the web what we have in the store for this uri - */ - }, { - key: "putBack", - value: function putBack(uri) { - var _this6 = this; - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var uriSting = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uri); - var doc = new _named_node__WEBPACK_IMPORTED_MODULE_22__["default"](uriSting).doc(); // strip off # - options.contentType = options["content-type"] || options["Content-Type"] || options.contentType || _types__WEBPACK_IMPORTED_MODULE_9__.TurtleContentType; - if (options.contentType === 'application/ld+json') { - return new Promise(function (resolve, reject) { - (0,_serialize__WEBPACK_IMPORTED_MODULE_23__["default"])(doc, _this6.store, doc.uri, options.contentType, function (err, jsonString) { - if (err) { - reject(err); - } else { - // @ts-ignore - options.data = jsonString; - _this6.webOperation('PUT', uri, options).then(function (res) { - return resolve(res); - }).catch(function (error) { - return reject(error); - }); - } - }); - }); - } - options.data = (0,_serialize__WEBPACK_IMPORTED_MODULE_23__["default"])(doc, this.store, doc.value, options.contentType); - return this.webOperation('PUT', uriSting, options); - } - }, { - key: "webCopy", - value: function webCopy(here, there, contentType) { - var _this7 = this; - return this.webOperation('GET', here).then(function (result) { - return _this7.webOperation('PUT', - // change to binary from text - there, { - data: result.responseText, - contentType: contentType - }); - }); - } - }, { - key: "delete", - value: function _delete(uri, options) { - var _this8 = this; - return this.webOperation('DELETE', uri, options).then(function (response) { - _this8.requested[uri] = 404; - _this8.nonexistent[uri] = true; - _this8.unload(_this8.store.rdfFactory.namedNode(uri)); - return response; - }); - } - - /** Create an empty resource if it really does not exist - * Be absolutely sure something does not exist before creating a new empty file - * as otherwise existing could be deleted. - * @param doc - The resource - */ - }, { - key: "createIfNotExists", - value: function () { - var _createIfNotExists = (0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().mark(function _callee2(doc) { - var contentType, - data, - fetcher, - response, - _args2 = arguments; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - contentType = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : _types__WEBPACK_IMPORTED_MODULE_9__.TurtleContentType; - data = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : ''; - fetcher = this; - _context2.prev = 3; - _context2.next = 6; - return fetcher.load(doc); - case 6: - response = _context2.sent; - _context2.next = 26; - break; - case 9: - _context2.prev = 9; - _context2.t0 = _context2["catch"](3); - if (!(_context2.t0.response.status === 404)) { - _context2.next = 25; - break; - } - _context2.prev = 12; - _context2.next = 15; - return fetcher.webOperation('PUT', doc.value, { - data: data, - contentType: contentType - }); - case 15: - response = _context2.sent; - _context2.next = 21; - break; - case 18: - _context2.prev = 18; - _context2.t1 = _context2["catch"](12); - throw _context2.t1; - case 21: - delete fetcher.requested[doc.value]; // delete cached 404 error - // console.log('createIfNotExists doc created ok ' + doc) - return _context2.abrupt("return", response); - case 25: - throw _context2.t0; - case 26: - return _context2.abrupt("return", response); - case 27: - case "end": - return _context2.stop(); - } - }, _callee2, this, [[3, 9], [12, 18]]); - })); - function createIfNotExists(_x4) { - return _createIfNotExists.apply(this, arguments); - } - return createIfNotExists; - }() - /** - * @param parentURI URI of parent container - * @param folderName - Optional folder name (slug) - * @param data - Optional folder metadata - */ - }, { - key: "createContainer", - value: function createContainer(parentURI, folderName, data) { - var headers = { - // Force the right mime type for containers - 'content-type': _types__WEBPACK_IMPORTED_MODULE_9__.TurtleContentType, - 'link': this.ns.ldp('BasicContainer') + '; rel="type"' - }; - if (folderName) { - headers['slug'] = folderName; - } - - // @ts-ignore These headers lack some of the required operators. - var options = { - headers: headers - }; - if (data) { - options.body = data; - } - return this.webOperation('POST', parentURI, options); - } - }, { - key: "invalidateCache", - value: function invalidateCache(iri) { - var uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(iri); - var fetcher = this; - // @ts-ignore - if (fetcher.fetchQueue && fetcher.fetchQueue[uri]) { - // console.log('Internal error - fetchQueue exists ' + uri) - var promise = fetcher.fetchQueue[uri]; - if (promise['PromiseStatus'] === 'resolved') { - delete fetcher.fetchQueue[uri]; - } else { - // pending - delete fetcher.fetchQueue[uri]; - // console.log('*** Fetcher: pending fetchQueue deleted ' + uri) - } - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.aclControl = exports.acl = void 0; +var _acl = __webpack_require__(/*! ./acl */ "./lib/acl/acl.js"); +var _aclControl = __webpack_require__(/*! ./acl-control */ "./lib/acl/acl-control.js"); +/** + * Re-exports all the exports from the various files in the src/acl/ folder + * @packageDocumentation + */ - if (fetcher.requested[uri] && fetcher.requested[uri] !== 'done' && fetcher.requested[uri] !== 'failed' && fetcher.requested[uri] !== 404) { - var msg = "Rdflib: fetcher: Destructive operation on <".concat(fetcher.requested[uri], "> file being fetched! ") + uri; - console.error(msg); - // alert(msg) - } else { - delete fetcher.requested[uri]; // invalidate read cache -- @@ messes up logic if request in progress ?? - delete fetcher.nonexistent[uri]; - } - } +var acl = { + adoptACLDefault: _acl.adoptACLDefault, + readACL: _acl.readACL, + sameACL: _acl.sameACL, + ACLunion: _acl.ACLunion, + loadUnionACL: _acl.loadUnionACL, + ACLbyCombination: _acl.ACLbyCombination, + makeACLGraph: _acl.makeACLGraph, + makeACLGraphbyCombo: _acl.makeACLGraphbyCombo, + ACLToString: _acl.ACLToString, + comboToString: _acl.comboToString, + makeACLString: _acl.makeACLString, + putACLObject: _acl.putACLObject, + putACLbyCombo: _acl.putACLbyCombo, + fixIndividualCardACL: _acl.fixIndividualCardACL, + fixIndividualACL: _acl.fixIndividualACL, + setACL: _acl.setACL, + getACLorDefault: _acl.getACLorDefault, + getACL: _acl.getACL +}; +exports.acl = acl; +var aclControl = { + preventBrowserDropEvents: _aclControl.preventBrowserDropEvents, + shortNameForFolder: _aclControl.shortNameForFolder, + ACLControlBox5: _aclControl.ACLControlBox5 +}; +exports.aclControl = aclControl; +//# sourceMappingURL=index.js.map - /** - * A generic web operation, at the fetch() level. - * does not involve the quad store. - * - * Returns promise of Response - * If data is returned, copies it to response.responseText before returning - */ - }, { - key: "webOperation", - value: function webOperation(method, uriIn) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uriIn); - options.method = method; - options.body = options.data || options.body; - options.force = true; - var fetcher = this; - if (options.body && !options.contentType) { - throw new Error('Web operation sending data must have a defined contentType.'); - } - if (options.contentType) { - options.headers = options.headers || {}; - options.headers['content-type'] = options.contentType; - } - Fetcher.setCredentials(uri, options); - return new Promise(function (resolve, reject) { - fetcher._fetch(uri, options).then(function (response) { - if (response.ok) { - if (method === 'PUT' || method === 'PATCH' || method === 'POST' || method === 'DELETE') { - fetcher.invalidateCache(uri); - } // response.body with Chrome can't be relied on - if (response.text) { - // Was: response.body https://github.com/linkeddata/rdflib.js/issues/506 - response.text().then(function (data) { - response.responseText = data; - resolve(response); - }); - } else { - resolve(response); - } - } else { - var msg = 'Web error: ' + response.status; - if (response.statusText) msg += ' (' + response.statusText + ')'; - msg += ' on ' + method + ' of <' + uri + '>'; - if (response.responseText) msg += ': ' + response.responseText; - var e2 = new Error(msg); - e2.response = response; - reject(e2); - } - }, function (err) { - var msg = 'Fetch error for ' + method + ' of <' + uri + '>:' + err; - reject(new Error(msg)); - }); - }); - } +/***/ }), - /** - * Looks up something. - * Looks up all the URIs a things has. - * - * @param term - canonical term for the thing whose URI is - * to be dereferenced - * @param rterm - the resource which referred to this - * (for tracking bad links) - */ - }, { - key: "lookUpThing", - value: function lookUpThing(term, rterm) { - var _this9 = this; - var uris = this.store.uris(term); // Get all URIs - uris = uris.map(function (u) { - return _uri__WEBPACK_IMPORTED_MODULE_21__.docpart(u); - }); // Drop hash fragments +/***/ "./lib/chat/bookmarks.js": +/*!*******************************!*\ + !*** ./lib/chat/bookmarks.js ***! + \*******************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - uris.forEach(function (u) { - _this9.lookedUp[u] = true; - }); +"use strict"; - // @ts-ignore Recursive type - return this.load(uris, { - referringTerm: rterm - }); - } - /** - * Looks up response header. - * - * @returns {Array|undefined} a list of header values found in a stored HTTP - * response, or [] if response was found but no header found, - * or undefined if no response is available. - * Looks for { [] link:requestedURI ?uri; link:response [ httph:header-name ?value ] } - */ - }, { - key: "getHeader", - value: function getHeader(doc, header) { - var kb = this.store; // look for the URI (AS A STRING NOT A NODE) for a stored request - var docuri = doc.value; - var requests = kb.each(undefined, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri)); - for (var r = 0; r < requests.length; r++) { - var request = requests[r]; - if (request !== undefined) { - var _response2 = kb.any(request, this.ns.link('response')); - if (_response2 !== undefined && kb.anyValue(_response2, this.ns.http('status')) && kb.anyValue(_response2, this.ns.http('status')).startsWith('2')) { - // Only look at success returns - not 401 error messagess etc - var results = kb.each(_response2, this.ns.httph(header.toLowerCase())); - if (results.length) { - return results.map(function (v) { - return v.value; - }); - } - return []; - } - } - } - return undefined; - } - }, { - key: "saveRequestMetadata", - value: function saveRequestMetadata(docuri, options) { - var req = options.req; - var kb = this.store; - var rterm = options.referringTerm; - this.addStatus(options.req, 'Accept: ' + options.headers['accept']); - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_19__.isNamedNode)(rterm)) { - kb.add(kb.rdfFactory.namedNode(docuri), this.ns.link('requestedBy'), rterm, this.appNode); - } - if (options.original && options.original.value !== docuri) { - kb.add(req, this.ns.link('orginalURI'), kb.rdfFactory.literal(options.original.value), this.appNode); - } - var now = new Date(); - var timeNow = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '] '; - kb.add(req, this.ns.rdfs('label'), kb.rdfFactory.literal(timeNow + ' Request for ' + docuri), this.appNode); - // We store the docuri as a string, not as a node, - // see https://github.com/linkeddata/rdflib.js/pull/427#pullrequestreview-447910061 - kb.add(req, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri), this.appNode); - kb.add(req, this.ns.link('status'), kb.collection(), this.appNode); - } - }, { - key: "saveResponseMetadata", - value: function saveResponseMetadata(response, options) { - var _this10 = this; - var kb = this.store; - var responseNode = kb.bnode(); - kb.add(options.req, this.ns.link('response'), responseNode, this.appNode); - kb.add(responseNode, this.ns.http('status'), kb.rdfFactory.literal(response.status), this.appNode); - kb.add(responseNode, this.ns.http('statusText'), kb.rdfFactory.literal(response.statusText), this.appNode); +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.findBookmarkDocument = findBookmarkDocument; +exports.renderBookmarksButton = renderBookmarksButton; +exports.toggleBookmark = toggleBookmark; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); +var _index = __webpack_require__(/*! ../media/index */ "./lib/media/index.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var pad = _interopRequireWildcard(__webpack_require__(/*! ../pad */ "./lib/pad.js")); +var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); +var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); +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); } +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; } +/** + * Functions related to chat and bookmarks + * @packageDocumentation + */ - // Save the response headers - response.headers.forEach(function (value, header) { - kb.add(responseNode, _this10.ns.httph(header), _this10.store.rdfFactory.literal(value), _this10.appNode); - if (header === 'content-type') { - kb.add(options.resource, _this10.ns.rdf('type'), kb.rdfFactory.namedNode(_utils_js__WEBPACK_IMPORTED_MODULE_11__.mediaTypeClass(value).value), _this10.appNode // responseNode - ); - } - }); +/* global alert confirm */ - return responseNode; - } - }, { - key: "objectRefresh", - value: function objectRefresh(term) { - var uris = this.store.uris(term); // Get all URIs - if (typeof uris !== 'undefined') { - for (var i = 0; i < uris.length; i++) { - this.refresh(this.store.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_21__.docpart(uris[i]))); - // what about rterm? - } - } - } +// pull in first avoid cross-refs - /* refresh Reload data from a given document - ** - ** @param term - An RDF Named Node for the eodcument in question - ** @param userCallback - A function userCallback(ok, message, response) - */ - }, { - key: "refresh", - value: function refresh(term, userCallback) { - // sources_refresh - this.fireCallbacks('refresh', arguments); - this.nowOrWhenFetched(term, { - force: true, - clearPreviousData: true - }, userCallback); - } +var UI = { + icons: _iconBase.icons, + ns: ns, + media: _index.media, + pad: pad, + rdf: rdf, + style: style, + utils: utils, + widgets: widgets +}; +var $rdf = UI.rdf; +var BOOK = $rdf.Namespace('http://www.w3.org/2002/01/bookmark#'); +var BOOKMARK_ICON = 'noun_45961.svg'; +var label = utils.label; +var dom = window.document || null; - /* refreshIfExpired Conditional refresh if Expired - ** - ** @param term - An RDF Named Node for the eodcument in question - ** @param userCallback - A function userCallback(ok, message, response) - */ - }, { - key: "refreshIfExpired", - value: function refreshIfExpired(term, userCallback) { - var exp = this.getHeader(term, 'Expires'); - if (!exp || new Date(exp[0]).getTime() <= new Date().getTime()) { - this.refresh(term, userCallback); +/** Create a resource if it really does not exist + * Be absolutely sure something does not exist before creating a new empty file + * as otherwise existing could be deleted. + * @param doc {NamedNode} - The resource + */ +function createIfNotExists(doc) { + return new Promise(function (resolve, reject) { + _solidLogic.store.fetcher.load(doc).then(function (response) { + debug.log('createIfNotExists doc exists, all good ' + doc); + // store.fetcher.webOperation('HEAD', doc.uri).then(response => { + resolve(response); + }, function (err) { + if (err.response.status === 404) { + debug.log('createIfNotExists doc does NOT exist, will create... ' + doc); + _solidLogic.store.fetcher.webOperation('PUT', doc.uri, { + data: '', + contentType: 'text/turtle' + }).then(function (response) { + // fetcher.requested[doc.uri] = 'done' // do not need to read ?? but no headers + delete _solidLogic.store.fetcher.requested[doc.uri]; // delete cached 404 error + debug.log('createIfNotExists doc created ok ' + doc); + resolve(response); + }, function (err) { + debug.log('createIfNotExists doc FAILED: ' + doc + ': ' + err); + reject(err); + }); } else { - userCallback(true, 'Not expired', {}); - } - } - }, { - key: "retract", - value: function retract(term) { - // sources_retract - this.store.removeMany(undefined, undefined, undefined, term); - if (term.value) { - delete this.requested[_uri__WEBPACK_IMPORTED_MODULE_21__.docpart(term.value)]; + debug.log('createIfNotExists doc load error NOT 404: ' + doc + ': ' + err); + reject(err); } - this.fireCallbacks('retract', arguments); - } - }, { - key: "getState", - value: function getState(docuri) { - if (typeof this.requested[docuri] === 'undefined') { - return 'unrequested'; - } else if (this.requested[docuri] === true) { - return 'requested'; - } else if (this.requested[docuri] === 'done') { - return 'fetched'; - } else if (this.requested[docuri] === 'redirected') { - return this.getState(this.redirectedTo[docuri]); + }); + }); +} + +// @@@@ use the one in rdflib.js when it is avaiable and delete this +function updatePromise(del, ins) { + return new Promise(function (resolve, reject) { + _solidLogic.store.updater.update(del, ins, function (uri, ok, errorBody) { + if (!ok) { + reject(new Error(errorBody)); } else { - // An non-200 HTTP error status - return 'failed'; + resolve(); } - } - }, { - key: "isPending", - value: function isPending(docuri) { - // sources_pending - // doing anyStatementMatching is wasting time - // if it's not pending: false -> flailed - // 'done' -> done 'redirected' -> redirected - return this.requested[docuri] === true; - } - }, { - key: "unload", - value: function unload(term) { - this.store.removeDocument(term); - delete this.requested[term.value]; // So it can be load2ed again - } - }, { - key: "addHandler", - value: function addHandler(handler) { - this.handlers.push(handler); - handler.register(this); - } - }, { - key: "retryNoCredentials", - value: function retryNoCredentials(docuri, options) { - // console.log('Fetcher: CORS: RETRYING with NO CREDENTIALS for ' + options.resource) - - options.retriedWithNoCredentials = true; // protect against being called twice - - delete this.requested[docuri]; // forget the original request happened - delete this.fetchQueue[docuri]; - // Note: XHR property was withCredentials, but fetch property is just credentials - var newOptions = Object.assign({}, options, { - credentials: 'omit' - }); - this.addStatus(options.req, 'Abort: Will retry with credentials SUPPRESSED to see if that helps'); - return this.load(docuri, newOptions); - } - - /** - * Tests whether a request is being made to a cross-site URI (for purposes - * of retrying with a proxy) - */ - }, { - key: "isCrossSite", - value: function isCrossSite(uri) { - // Mashup situation, not node etc - if (typeof document === 'undefined' || !document.location) { - return false; - } - var hostpart = _uri__WEBPACK_IMPORTED_MODULE_21__.hostpart; - var here = '' + document.location; - return (hostpart(here) && hostpart(uri) && hostpart(here)) !== hostpart(uri); - } - - /** - * Called when there's a network error in fetch(), or a response - * with status of 0. - */ - }, { - key: "handleError", - value: function handleError(response, docuri, options) { - if (this.isCrossSite(docuri)) { - // Make sure we haven't retried already - if (options.credentials && options.credentials === 'include' && !options.retriedWithNoCredentials) { - return this.retryNoCredentials(docuri, options); - } - - // Now attempt retry via proxy - var proxyUri = Fetcher.crossSiteProxy(docuri); - if (proxyUri && !options.proxyUsed) { - // console.log('web: Direct failed so trying proxy ' + proxyUri) - return this.redirectToProxy(proxyUri, options); - } - } - var message; - if (response instanceof Error) { - message = 'Fetch error: ' + response.message; - } else { - message = response.statusText; - if (response.responseText) { - message += " ".concat(response.responseText); - } - } - - // This is either not a CORS error, or retries have been made - return this.failFetch(options, message, response.status || 998, response); - } + }); // callback + }); // promise +} - // deduce some things from the HTTP transaction - }, { - key: "addType", - value: function addType(rdfType, req, kb, locURI) { - // add type to all redirected resources too - var prev = req; - if (locURI) { - var reqURI = kb.any(prev, this.ns.link('requestedURI')); - if (reqURI && reqURI.value !== locURI) { - kb.add(kb.rdfFactory.namedNode(locURI), this.ns.rdf('type'), rdfType, this.appNode); - } - } - for (;;) { - var doc = kb.any(prev, this.ns.link('requestedURI')); - if (doc && doc.value) { - kb.add(kb.rdfFactory.namedNode(doc.value), this.ns.rdf('type'), rdfType, this.appNode); - } // convert Literal - prev = kb.any(undefined, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#redirectedRequest'), prev); - if (!prev) { - break; - } - var response = kb.any(prev, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#response')); - if (!response) { +/* Bookmarking + */ +/** Find a user's bookmarks + */ +function findBookmarkDocument(_x) { + return _findBookmarkDocument.apply(this, arguments); +} +/** Add a bookmark + */ +function _findBookmarkDocument() { + _findBookmarkDocument = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(userContext) { + var theClass, fileTail, isPublic, newBookmarkFile; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + theClass = BOOK('Bookmark'); + fileTail = 'bookmarks.ttl'; + isPublic = true; + _context.next = 5; + return (0, _login.findAppInstances)(userContext, theClass, isPublic); + case 5: + if (!(userContext.instances && userContext.instances.length > 0)) { + _context.next = 10; + break; + } + userContext.bookmarkDocument = userContext.instances[0]; + if (userContext.instances.length > 1) { + alert('More than one bookmark file! ' + userContext.instances); + } + _context.next = 28; break; - } - var redirection = kb.any(response, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/http#status')); - if (!redirection) { + case 10: + if (!userContext.publicProfile) { + _context.next = 27; + break; + } + // publicProfile or preferencesFile + newBookmarkFile = $rdf.sym(userContext.publicProfile.dir().uri + fileTail); + _context.prev = 12; + debug.log('Creating new bookmark file ' + newBookmarkFile); + _context.next = 16; + return createIfNotExists(newBookmarkFile); + case 16: + _context.next = 22; break; - } - // @ts-ignore always true? - if (redirection !== '301' && redirection !== '302') { + case 18: + _context.prev = 18; + _context.t0 = _context["catch"](12); + alert.error("Can't make fresh bookmark file:" + _context.t0); + return _context.abrupt("return", userContext); + case 22: + _context.next = 24; + return (0, _solidLogic.registerInTypeIndex)(newBookmarkFile, userContext.index, theClass); + case 24: + userContext.bookmarkDocument = newBookmarkFile; + _context.next = 28; break; - } - } - } - - /** - * Handle fetch() response - */ - }, { - key: "handleResponse", - value: function handleResponse(response, docuri, options) { - var _this11 = this; - var kb = this.store; - var headers = response.headers; - var reqNode = options.req; - var responseNode = this.saveResponseMetadata(response, options); - var contentType = this.normalizedContentType(options, headers) || ''; - var contentLocation = headers.get('content-location'); - - // this.fireCallbacks('recv', xhr.args) - // this.fireCallbacks('headers', [{uri: docuri, headers: xhr.headers}]) - - // Check for masked errors (CORS, etc) - if (response.status === 0) { - // console.log('Masked error - status 0 for ' + docuri) - return this.handleError(response, docuri, options); + case 27: + alert('You seem to have no bookmark file and not even a profile file.'); + case 28: + return _context.abrupt("return", userContext); + case 29: + case "end": + return _context.stop(); } - if (response.status >= 400) { - if (response.status === 404) { - this.nonexistent[options.original.value] = true; - this.nonexistent[docuri] = true; - } - return this.saveErrorResponse(response, responseNode).then(function () { - var errorMessage = options.resource + ' ' + response.statusText; - return _this11.failFetch(options, errorMessage, response.status, response); - }); + }, _callee, null, [[12, 18]]); + })); + return _findBookmarkDocument.apply(this, arguments); +} +function addBookmark(_x2, _x3) { + return _addBookmark.apply(this, arguments); +} +function _addBookmark() { + _addBookmark = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(context, target) { + var title, me, author, bookmarkDoc, bookmark, ins, msg; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + /* like + @prefix terms: . + @prefix bookm: . + @prefix n0: . + <> terms:references <#0.5534145389246576>. + <#0.5534145389246576> + a bookm:Bookmark; + terms:created "2019-01-26T20:26:44.374Z"^^XML:dateTime; + terms:title "Herons"; + bookm:recalls wiki:Heron; + n0:maker c:me. + */ + title = ''; + me = _solidLogic.authn.currentUser(); // If already logged on + if (me) { + _context2.next = 4; + break; + } + throw new Error('Must be logged on to add Bookmark'); + case 4: + author = _solidLogic.store.any(target, ns.foaf('maker')); + title = label(author) + ': ' + _solidLogic.store.anyValue(target, ns.sioc('content')).slice(0, 80); // @@ add chat title too? + bookmarkDoc = context.bookmarkDocument; + bookmark = UI.widgets.newThing(bookmarkDoc, title); + ins = [$rdf.st(bookmarkDoc, UI.ns.dct('references'), bookmark, bookmarkDoc), $rdf.st(bookmark, UI.ns.rdf('type'), BOOK('Bookmark'), bookmarkDoc), $rdf.st(bookmark, UI.ns.dct('created'), new Date(), bookmarkDoc), $rdf.st(bookmark, BOOK('recalls'), target, bookmarkDoc), $rdf.st(bookmark, UI.ns.foaf('maker'), me, bookmarkDoc), $rdf.st(bookmark, UI.ns.dct('title'), title, bookmarkDoc)]; + _context2.prev = 9; + _context2.next = 12; + return updatePromise([], ins); + case 12: + _context2.next = 19; + break; + case 14: + _context2.prev = 14; + _context2.t0 = _context2["catch"](9); + msg = 'Making bookmark: ' + _context2.t0; + alert.error(msg); + return _context2.abrupt("return", null); + case 19: + return _context2.abrupt("return", bookmark); + case 20: + case "end": + return _context2.stop(); } - var diffLocation = null; - var absContentLocation = null; - if (contentLocation) { - absContentLocation = _uri__WEBPACK_IMPORTED_MODULE_21__.join(contentLocation, docuri); - if (absContentLocation !== docuri) { - diffLocation = absContentLocation; - } + }, _callee2, null, [[9, 14]]); + })); + return _addBookmark.apply(this, arguments); +} +function toggleBookmark(_x4, _x5, _x6) { + return _toggleBookmark.apply(this, arguments); +} +function _toggleBookmark() { + _toggleBookmark = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(userContext, target, bookmarkButton) { + var bookmarks, i, bookmark; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return _solidLogic.store.fetcher.load(userContext.bookmarkDocument); + case 2: + bookmarks = _solidLogic.store.each(null, BOOK('recalls'), target, userContext.bookmarkDocument); + if (!bookmarks.length) { + _context3.next = 24; + break; + } + if (confirm('Delete bookmark on this?' + bookmarks.length)) { + _context3.next = 6; + break; + } + return _context3.abrupt("return"); + case 6: + i = 0; + case 7: + if (!(i < bookmarks.length)) { + _context3.next = 22; + break; + } + _context3.prev = 8; + _context3.next = 11; + return updatePromise(_solidLogic.store.connectedStatements(bookmarks[i]), []); + case 11: + bookmarkButton.style.backgroundColor = 'white'; + debug.log('Bookmark deleted: ' + bookmarks[i]); + _context3.next = 19; + break; + case 15: + _context3.prev = 15; + _context3.t0 = _context3["catch"](8); + debug.error('Cant delete bookmark:' + _context3.t0); + alert('Cant delete bookmark:' + _context3.t0); + case 19: + i++; + _context3.next = 7; + break; + case 22: + _context3.next = 29; + break; + case 24: + _context3.next = 26; + return addBookmark(userContext, target); + case 26: + bookmark = _context3.sent; + bookmarkButton.style.backgroundColor = 'yellow'; + debug.log('Bookmark added: ' + bookmark); + case 29: + case "end": + return _context3.stop(); } - if (response.status === 200) { - this.addType(this.ns.link('Document'), reqNode, kb, docuri); - if (diffLocation) { - this.addType(this.ns.link('Document'), reqNode, kb, diffLocation); - } - - // Before we parse new data clear old but only on 200 - if (options.clearPreviousData) { - kb.removeDocument(options.resource); - } - var isImage = contentType.includes('image/') || contentType.includes('application/pdf'); - if (contentType && isImage) { - this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb, docuri); - if (diffLocation) { - this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb, diffLocation); + }, _callee3, null, [[8, 15]]); + })); + return _toggleBookmark.apply(this, arguments); +} +function renderBookmarksButton(_x7, _x8) { + return _renderBookmarksButton.apply(this, arguments); +} +function _renderBookmarksButton() { + _renderBookmarksButton = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(userContext, target) { + var setBookmarkButtonColor, _setBookmarkButtonColor, bookmarkButton; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _setBookmarkButtonColor = function _setBookmarkButtonCol2() { + _setBookmarkButtonColor = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(bookmarkButton) { + var bookmarked; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _solidLogic.store.fetcher.load(userContext.bookmarkDocument); + case 2: + bookmarked = _solidLogic.store.any(null, BOOK('recalls'), bookmarkButton.target, userContext.bookmarkDocument); + bookmarkButton.style = UI.style.buttonStyle; + if (bookmarked) bookmarkButton.style.backgroundColor = 'yellow'; + case 5: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _setBookmarkButtonColor.apply(this, arguments); + }; + setBookmarkButtonColor = function _setBookmarkButtonCol(_x9) { + return _setBookmarkButtonColor.apply(this, arguments); + }; + if (!userContext.bookmarkDocument) { + _context5.next = 8; + break; } - } + bookmarkButton = UI.widgets.button(dom, UI.icons.iconBase + BOOKMARK_ICON, label(BOOK('Bookmark')), function () { + toggleBookmark(userContext, target, bookmarkButton); + }); + bookmarkButton.target = target; + _context5.next = 7; + return setBookmarkButtonColor(bookmarkButton); + case 7: + return _context5.abrupt("return", bookmarkButton); + case 8: + case "end": + return _context5.stop(); } + }, _callee5); + })); + return _renderBookmarksButton.apply(this, arguments); +} +//# sourceMappingURL=bookmarks.js.map - // If we have already got the thing at this location, abort - if (contentLocation) { - if (!options.force && diffLocation && this.requested[absContentLocation] === 'done') { - // we have already fetched this - // should we smush too? - // log.info("HTTP headers indicate we have already" + " retrieved " + - // xhr.resource + " as " + absContentLocation + ". Aborting.") - return this.doneFetch(options, response); - } - this.requested[absContentLocation] = true; - } - this.parseLinkHeader(headers.get('link'), options.original, reqNode); - var handler = this.handlerForContentType(contentType, response); - if (!handler) { - // Not a problem, we just don't extract data - this.addStatus(reqNode, 'Fetch over. No data handled.'); - return this.doneFetch(options, response); - } - return response.text() - // @ts-ignore Types seem right - .then(function (responseText) { - response.responseText = responseText; - return handler.parse(_this11, responseText, options, response); - }); - } - }, { - key: "saveErrorResponse", - value: function saveErrorResponse(response, responseNode) { - var _this12 = this; - var kb = this.store; - return response.text().then(function (content) { - if (content.length > 10) { - kb.add(responseNode, _this12.ns.http('content'), kb.rdfFactory.literal(content), responseNode); - } - }); - } - }, { - key: "handlerForContentType", - value: function handlerForContentType(contentType, response) { - if (!contentType) { - return null; - } - var Handler = this.handlers.find(function (handler) { - return contentType.match(handler.pattern); - }); +/***/ }), - // @ts-ignore in practice all Handlers have constructors. - return Handler ? new Handler(response) : null; - } - }, { - key: "guessContentType", - value: function guessContentType(uri) { - return CONTENT_TYPE_BY_EXT[uri.split('.').pop()]; - } - }, { - key: "normalizedContentType", - value: function normalizedContentType(options, headers) { - if (options.forceContentType) { - return options.forceContentType; - } - var contentType = headers.get('content-type'); - if (!contentType || contentType.includes('application/octet-stream')) { - var guess = this.guessContentType(options.resource.value); - if (guess) { - return guess; - } - } - var protocol = _uri__WEBPACK_IMPORTED_MODULE_21__.protocol(options.resource.value); - if (!contentType && ['file', 'chrome'].includes(protocol)) { - return 'text/xml'; - } - return contentType; - } +/***/ "./lib/chat/chatLogic.js": +/*!*******************************!*\ + !*** ./lib/chat/chatLogic.js ***! + \*******************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - /** - * Sends a new request to the specified uri. (Extracted from `onerrorFactory()`) - */ - }, { - key: "redirectToProxy", - value: function redirectToProxy(newURI, options) { - var _this13 = this; - this.addStatus(options.req, 'BLOCKED -> Cross-site Proxy to <' + newURI + '>'); - options.proxyUsed = true; - var kb = this.store; - var oldReq = options.req; // request metadata blank node +"use strict"; - if (!options.noMeta) { - kb.add(oldReq, this.ns.link('redirectedTo'), kb.rdfFactory.namedNode(newURI), oldReq); - this.addStatus(oldReq, 'redirected to new request'); // why - } - this.requested[options.resource.value] = 'redirected'; - this.redirectedTo[options.resource.value] = newURI; - var newOptions = Object.assign({}, options); - newOptions.baseURI = options.resource.value; - return this.fetchUri(newURI, newOptions).then(function (response) { - if (!newOptions.noMeta) { - kb.add(oldReq, _this13.ns.link('redirectedRequest'), newOptions.req, _this13.appNode); - } - return response; - }); - } - }, { - key: "setRequestTimeout", - value: function setRequestTimeout(uri, options) { - var _this14 = this; - return new Promise(function (resolve) { - _this14.timeouts[uri] = (_this14.timeouts[uri] || []).concat(setTimeout(function () { - if (_this14.isPending(uri) && !options.retriedWithNoCredentials && !options.proxyUsed) { - resolve(_this14.failFetch(options, "Request to ".concat(uri, " timed out"), 'timeout')); +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ChatChannel = void 0; +exports._createIfNotExists = _createIfNotExists; +exports.isDeleted = isDeleted; +exports.isHidden = isHidden; +exports.isReplaced = isReplaced; +exports.mostRecentVersion = mostRecentVersion; +exports.nick = nick; +exports.originalVersion = originalVersion; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); +var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _dateFolder = __webpack_require__(/*! ./dateFolder */ "./lib/chat/dateFolder.js"); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +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); } +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; } +/** + * Contains the [[ChatChannel]] class and logic for Solid Chat + * @packageDocumentation + */ +// pull in first avoid cross-refs +/* The Solid logic for a 'LongChat' +*/ +/** + * Common code for a chat (discussion area of messages about something) + * This version runs over a series of files for different time periods + * + * Parameters for the whole chat like its title are stored on + * index.ttl#this and the chats messages are stored in YYYY/MM/DD/chat.ttl + * + */ +var ChatChannel = /*#__PURE__*/function () { + function ChatChannel(channel, options) { + (0, _classCallCheck2["default"])(this, ChatChannel); + this.channel = channel; + this.channelRoot = channel.doc(); + this.options = options; + this.dateFolder = new _dateFolder.DateFolder(this.channelRoot, 'chat.ttl'); + this.div = null; // : HTMLElement + } + + /* Store a new message in the web, + */ + (0, _createClass2["default"])(ChatChannel, [{ + key: "createMessage", + value: function () { + var _createMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(text) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + return _context.abrupt("return", this.updateMessage(text)); + case 1: + case "end": + return _context.stop(); } - }, _this14.timeout)); - }); - } - }, { - key: "addFetchCallback", - value: function addFetchCallback(uri, callback) { - if (!this.fetchCallbacks[uri]) { - this.fetchCallbacks[uri] = [callback]; - } else { - this.fetchCallbacks[uri].push(callback); - } - } - }, { - key: "acceptString", - value: function acceptString() { - var acceptstring = ''; - for (var mediaType in this.mediatypes) { - if (acceptstring !== '') { - acceptstring += ', '; - } - acceptstring += mediaType; - for (var property in this.mediatypes[mediaType]) { - acceptstring += ';' + property + '=' + this.mediatypes[mediaType][property]; - } - } - return acceptstring; - } - // var updatesVia = new $rdf.UpdatesVia(this) // Subscribe to headers - // @@@@@@@@ This is turned off because it causes a websocket to be set up for ANY fetch - // whether we want to track it ot not. including ontologies loaed though the XSSproxy - }], [{ - key: "crossSiteProxy", - value: function crossSiteProxy(uri) { - if (Fetcher.crossSiteProxyTemplate) { - return Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); - } else { - return undefined; + }, _callee, this); + })); + function createMessage(_x) { + return _createMessage.apply(this, arguments); } - } + return createMessage; + }() + /* Store a new message in the web, + as a replacement for an existing one. + The old one iis left, and the two are linked + */ }, { - key: "offlineOverride", - value: function offlineOverride(uri) { - // Map the URI to a localhost proxy if we are running on localhost - // This is used for working offline, e.g. on planes. - // Is the script itself is running in localhost, then access all - // data in a localhost mirror. - // Do not remove without checking with TimBL - var requestedURI = uri; - var UI; - if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) && UI.preferences && UI.preferences.get('offlineModeUsingLocalhost')) { - if (requestedURI.slice(0, 7) === 'http://' && requestedURI.slice(7, 17) !== 'localhost/') { - requestedURI = 'http://localhost/' + requestedURI.slice(7); - _log__WEBPACK_IMPORTED_MODULE_20__["default"].warn('Localhost kludge for offline use: actually getting <' + requestedURI + '>'); - } else { - // log.warn("Localhost kludge NOT USED <" + requestedURI + ">") - } - } else { - // log.warn("Localhost kludge OFF offline use: actually getting <" + - // requestedURI + ">") + key: "updateMessage", + value: function () { + var _updateMessage = (0, _asyncToGenerator2["default"])(function (text) { + var _this = this; + var oldMsg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var deleteIt = arguments.length > 2 ? arguments[2] : undefined; + return /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var sts, now, timestamp, dateStamp, chatDocument, message, me, msg; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + sts = []; + now = new Date(); + timestamp = '' + now.getTime(); + dateStamp = $rdf.term(now); + chatDocument = oldMsg ? oldMsg.doc() : _this.dateFolder.leafDocumentFromDate(now); + message = _solidLogic.store.sym(chatDocument.uri + '#' + 'Msg' + timestamp); // const content = store.literal(text) + me = _solidLogic.authn.currentUser(); // If already logged on + if (oldMsg) { + // edit message replaces old one + sts.push($rdf.st(mostRecentVersion(oldMsg), ns.dct('isReplacedBy'), message, chatDocument)); + if (deleteIt) { + sts.push($rdf.st(message, ns.schema('dateDeleted'), dateStamp, chatDocument)); + } + } else { + // link new message to channel + sts.push($rdf.st(_this.channel, ns.wf('message'), message, chatDocument)); + } + sts.push($rdf.st(message, ns.sioc('content'), _solidLogic.store.literal(text), chatDocument)); + sts.push($rdf.st(message, ns.dct('created'), dateStamp, chatDocument)); + if (me) { + sts.push($rdf.st(message, ns.foaf('maker'), me, chatDocument)); + } + _context2.prev = 11; + _context2.next = 14; + return _solidLogic.store.updater.update([], sts); + case 14: + _context2.next = 22; + break; + case 16: + _context2.prev = 16; + _context2.t0 = _context2["catch"](11); + msg = 'Error saving chat message: ' + _context2.t0; + debug.warn(msg); + alert(msg); + throw new Error(msg); + case 22: + return _context2.abrupt("return", message); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2, null, [[11, 16]]); + })(); + }); + function updateMessage(_x2) { + return _updateMessage.apply(this, arguments); } - return requestedURI; - } + return updateMessage; + }() + /* Mark a message as deleted + * Wee add a new version of the message,m witha deletion flag (deletion date) + * so that the deletion can be revoked by adding another non-deleted update + */ }, { - key: "proxyIfNecessary", - value: function proxyIfNecessary(uri) { - var UI; - if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) && UI.isExtension) { - return uri; - } // Extension does not need proxy - - if (typeof $SolidTestEnvironment !== 'undefined' && $SolidTestEnvironment.localSiteMap) { - // nested dictionaries of URI parts from origin down - var hostpath = uri.split('/').slice(2); // the bit after the // - - var lookup = function lookup(parts, index) { - var z = index[parts.shift()]; - if (!z) { - return null; - } - if (typeof z === 'string') { - return z + parts.join('/'); - } - if (!parts) { - return null; + key: "deleteMessage", + value: function () { + var _deleteMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(message) { + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + return _context3.abrupt("return", this.updateMessage('(message deleted)', message, true)); + case 1: + case "end": + return _context3.stop(); } - return lookup(parts, z); - }; - var y = lookup(hostpath, $SolidTestEnvironment.localSiteMap); - if (y) { - return y; - } - } - - // browser does 2014 on as https browser script not trusted - // If the web app origin is https: then the mixed content rules - // prevent it loading insecure http: stuff so we need proxy. - if (Fetcher.crossSiteProxyTemplate && typeof document !== 'undefined' && document.location && ('' + document.location).slice(0, 6) === 'https:' && - // origin is secure - uri.slice(0, 5) === 'http:') { - // requested data is not - return Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); + }, _callee3, this); + })); + function deleteMessage(_x3) { + return _deleteMessage.apply(this, arguments); } - return uri; - } + return deleteMessage; + }() + }]); + return ChatChannel; +}(); // class ChatChannel +exports.ChatChannel = ChatChannel; +function originalVersion(message) { + var msg = message; + while (msg) { + message = msg; + msg = _solidLogic.store.any(null, ns.dct('isReplacedBy'), message, message.doc()); + } + return message; +} +function mostRecentVersion(message) { + var msg = message; + while (msg) { + message = msg; + msg = _solidLogic.store.any(message, ns.dct('isReplacedBy'), null, message.doc()); + } + return message; +} +function isDeleted(message) { + return _solidLogic.store.holds(message, ns.schema('dateDeleted'), null, message.doc()); +} +function isReplaced(message) { + return _solidLogic.store.holds(message, ns.dct('isReplacedBy'), null, message.doc()); +} +function isHidden(message) { + return this.isDeleted(message) || this.isReplaced(message); +} - /** - * Tests whether the uri's protocol is supported by the Fetcher. - * @param uri - */ - }, { - key: "unsupportedProtocol", - value: function unsupportedProtocol(uri) { - var pcol = _uri__WEBPACK_IMPORTED_MODULE_21__.protocol(uri); - return pcol === 'tel' || pcol === 'mailto' || pcol === 'urn'; - } +// A Nickname for a person - /** Decide on credentials using old XXHR api or new fetch() one - * @param requestedURI - * @param options - */ - }, { - key: "setCredentials", - value: function setCredentials(requestedURI) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - // 2014 CORS problem: - // XMLHttpRequest cannot load http://www.w3.org/People/Berners-Lee/card. - // A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' - // header when the credentials flag is true. - // @ Many ontology files under http: and need CORS wildcard -> - // can't have credentials - if (options.credentials === undefined) { - // Caller using new fetch convention - if (options.withCredentials !== undefined) { - // XHR style is what Fetcher specified before - options.credentials = options.withCredentials ? 'include' : 'omit'; - } else { - options.credentials = 'include'; // default is to be logged on +function nick(person) { + var s = _solidLogic.store.any(person, ns.foaf('nick')); + if (s) return '' + s.value; + return '' + utils.label(person); +} +function _createIfNotExists(_x4) { + return _createIfNotExists2.apply(this, arguments); +} // ends +function _createIfNotExists2() { + _createIfNotExists2 = (0, _asyncToGenerator2["default"])(function (doc) { + var contentType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'text/turtle'; + var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + return /*#__PURE__*/_regenerator["default"].mark(function _callee4() { + var response; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.prev = 0; + _context4.next = 3; + return _solidLogic.store.fetcher.load(doc); + case 3: + response = _context4.sent; + _context4.next = 26; + break; + case 6: + _context4.prev = 6; + _context4.t0 = _context4["catch"](0); + if (!(_context4.t0.response.status === 404)) { + _context4.next = 24; + break; + } + debug.log('createIfNotExists: doc does NOT exist, will create... ' + doc); + _context4.prev = 10; + _context4.next = 13; + return _solidLogic.store.fetcher.webOperation('PUT', doc.uri, { + data: data, + contentType: contentType + }); + case 13: + response = _context4.sent; + _context4.next = 20; + break; + case 16: + _context4.prev = 16; + _context4.t1 = _context4["catch"](10); + debug.log('createIfNotExists doc FAILED: ' + doc + ': ' + _context4.t1); + throw _context4.t1; + case 20: + delete _solidLogic.store.fetcher.requested[doc.uri]; // delete cached 404 error + // debug.log('createIfNotExists doc created ok ' + doc) + return _context4.abrupt("return", response); + case 24: + debug.log('createIfNotExists doc load error NOT 404: ' + doc + ': ' + _context4.t0); + throw _context4.t0; + case 26: + return _context4.abrupt("return", response); + case 27: + case "end": + return _context4.stop(); } - } - } - }]); - return Fetcher; -}(); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Fetcher, "HANDLERS", void 0); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Fetcher, "CONTENT_TYPE_BY_EXT", void 0); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Fetcher, "crossSiteProxyTemplate", void 0); - -Fetcher.HANDLERS = defaultHandlers; -Fetcher.CONTENT_TYPE_BY_EXT = CONTENT_TYPE_BY_EXT; + }, _callee4, null, [[0, 6], [10, 16]]); + })(); + }); + return _createIfNotExists2.apply(this, arguments); +} +//# sourceMappingURL=chatLogic.js.map /***/ }), -/***/ "../rdflib/esm/formula.js": +/***/ "./lib/chat/dateFolder.js": /*!********************************!*\ - !*** ../rdflib/esm/formula.js ***! + !*** ./lib/chat/dateFolder.js ***! \********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Formula) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); -/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./collection */ "../rdflib/esm/collection.js"); -/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "../rdflib/esm/factories/canonical-data-factory.js"); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); -/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./serialize */ "../rdflib/esm/serialize.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); -/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./variable */ "../rdflib/esm/variable.js"); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils */ "../rdflib/esm/utils.js"); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); - - - - - - - -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; } } }; } -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); } -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; } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - - - - - - - - - - +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.DateFolder = void 0; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); +var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); +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); } +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; } /** - * A formula, or store of RDF statements + * Contains the [[DateFolder]] class + * This tracks data stored in dated folders and sub-folders + * */ -var Formula = /*#__PURE__*/function (_Node) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Formula, _Node); - var _super = _createSuper(Formula); - /** - * The accompanying fetcher instance. - * - * Is set by the fetcher when initialized. - */ +// pull in first avoid cross-refs +/** + * Track back through the YYYY/MM/DD tree to find the previous/next day + */ +var DateFolder = /*#__PURE__*/function () { + function DateFolder(rootThing, leafFileName, membershipProperty) { + (0, _classCallCheck2["default"])(this, DateFolder); + this.root = rootThing; + this.rootFolder = rootThing.dir(); + this.leafFileName = leafFileName || 'index.ttl'; // typically chat.ttl + this.membershipProperty = membershipProperty || ns.wf('leafObject'); + } - /** - * A namespace for the specified namespace's URI - * @param nsuri The URI for the namespace + /* Generate the leaf document (rdf object) from date + * @returns: - document */ + (0, _createClass2["default"])(DateFolder, [{ + key: "leafDocumentFromDate", + value: function leafDocumentFromDate(date) { + // debug.log('incoming date: ' + date) + var isoDate = date.toISOString(); // Like "2018-05-07T17:42:46.576Z" + var path = isoDate.split('T')[0].replace(/-/g, '/'); // Like "2018/05/07" + path = this.root.dir().uri + path + '/' + this.leafFileName; + return _solidLogic.store.sym(path); + } - /** The factory used to generate statements and terms */ - - /** - * Initializes this formula - * @constructor - * @param statements - Initial array of statements - * @param constraints - initial array of constraints - * @param initBindings - initial bindings used in Query - * @param optional - optional - * @param opts - * @param opts.rdfFactory - The rdf factory that should be used by the store - */ - function Formula() { - var _this; - var statements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var constraints = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var initBindings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; - var optional = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; - var opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Formula); - _this = _super.call(this, ''); - _this.statements = statements; - _this.constraints = constraints; - _this.initBindings = initBindings; - _this.optional = optional; - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.GraphTermType); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_8__["default"].Graph); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "fetcher", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "ns", _namespace__WEBPACK_IMPORTED_MODULE_9__["default"]); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "rdfFactory", void 0); - _this.rdfFactory = opts && opts.rdfFactory || _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_10__["default"]; - // Enable default factory methods on this while preserving factory context. - var _iterator = _createForOfIteratorHelper(_utils__WEBPACK_IMPORTED_MODULE_11__.appliedFactoryMethods), - _step; - try { - var _loop = function _loop() { - var factoryMethod = _step.value; - _this[factoryMethod] = function () { - var _this$rdfFactory; - return (_this$rdfFactory = _this.rdfFactory)[factoryMethod].apply(_this$rdfFactory, arguments); - }; - }; - for (_iterator.s(); !(_step = _iterator.n()).done;) { - _loop(); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - return _this; - } - - /** Add a statement from its parts - * @param subject - the first part of the statement - * @param predicate - the second part of the statement - * @param object - the third part of the statement - * @param graph - the last part of the statement - */ - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Formula, [{ - key: "add", - value: function add(subject, predicate, object, graph) { - var _this2 = this; - if (arguments.length === 1) { - subject.forEach(function (st) { - return _this2.add(st.subject, st.predicate, st.object, st.graph); - }); - } - return this.statements.push(this.rdfFactory.quad(subject, predicate, object, graph)); - } - - /** Add a statment object - * @param {Statement} statement - An existing constructed statement to add - */ - }, { - key: "addStatement", - value: function addStatement(statement) { - return this.add(statement); - } - - /** - * Shortcut for adding blankNodes - * @param [id] + /* Generate a date object from the leaf file name */ }, { - key: "bnode", - value: function bnode(id) { - return this.rdfFactory.blankNode(id); + key: "dateFromLeafDocument", + value: function dateFromLeafDocument(doc) { + var head = this.rootFolder.uri.length; + var str = doc.uri.slice(head, head + 10).replace(/\//g, '-'); + // let date = new Date(str + 'Z') // GMT - but fails in FF - invalid format :-( + var date = new Date(str); // not explicitly UTC but is assumed so in spec + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse + debug.log('Date for ' + doc + ':' + date.toISOString()); + return date; } - - /** - * Adds all the statements to this formula - * @param statements - A collection of statements - */ }, { - key: "addAll", - value: function addAll(statements) { - var _this3 = this; - statements.forEach(function (quad) { - _this3.add(quad.subject, quad.predicate, quad.object, quad.graph); - }); - } - - /** Follow link from one node, using one wildcard, looking for one - * - * For example, any(me, knows, null, profile) - a person I know accoring to my profile . - * any(me, knows, null, null) - a person I know accoring to anything in store . - * any(null, knows, me, null) - a person who know me accoring to anything in store . - * - * @param s - A node to search for as subject, or if null, a wildcard - * @param p - A node to search for as predicate, or if null, a wildcard - * @param o - A node to search for as object, or if null, a wildcard - * @param g - A node to search for as graph, or if null, a wildcard - * @returns A node which match the wildcard position, or null - */ + key: "loadPrevious", + value: function () { + var _loadPrevious = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(date, backwards) { + var thisDateFolder, previousPeriod, _previousPeriod, folder, found, doc; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _previousPeriod = function _previousPeriod3() { + _previousPeriod = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(file, level) { + var younger, suitable, lastNonEmpty, _lastNonEmpty, parent, siblings, _folder, uncle, cousins, result; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _lastNonEmpty = function _lastNonEmpty3() { + _lastNonEmpty = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(siblings) { + var _folder2, leafDocument; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + siblings = siblings.filter(suitable); + siblings.sort(); // chronological order + if (!backwards) siblings.reverse(); + if (!(level !== 3)) { + _context.next = 5; + break; + } + return _context.abrupt("return", siblings.pop()); + case 5: + if (!siblings.length) { + _context.next = 14; + break; + } + _folder2 = siblings.pop(); + leafDocument = _solidLogic.store.sym(_folder2.uri + thisDateFolder.leafFileName); + _context.next = 10; + return _solidLogic.store.fetcher.load(leafDocument); + case 10: + if (!(_solidLogic.store.statementsMatching(null, ns.dct('created'), null, leafDocument).length > 0)) { + _context.next = 12; + break; + } + return _context.abrupt("return", _folder2); + case 12: + _context.next = 5; + break; + case 14: + return _context.abrupt("return", null); + case 15: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _lastNonEmpty.apply(this, arguments); + }; + lastNonEmpty = function _lastNonEmpty2(_x5) { + return _lastNonEmpty.apply(this, arguments); + }; + suitable = function _suitable(x) { + var tail = x.uri.slice(0, -1).split('/').slice(-1)[0]; + if (!'0123456789'.includes(tail[0])) return false; // not numeric + return true; + }; + younger = function _younger(x) { + if (backwards ? x.uri >= file.uri : x.uri <= file.uri) return false; // later than we want or same -- looking for different + return true; + }; + // debug.log(' previousPeriod level' + level + ' file ' + file) + parent = file.dir(); + _context2.prev = 5; + _context2.next = 8; + return _solidLogic.store.fetcher.load(parent); + case 8: + siblings = _solidLogic.store.each(parent, ns.ldp('contains')); + siblings = siblings.filter(younger); + _context2.next = 12; + return lastNonEmpty(siblings); + case 12: + _folder = _context2.sent; + if (!_folder) { + _context2.next = 15; + break; + } + return _context2.abrupt("return", _folder); + case 15: + _context2.next = 25; + break; + case 17: + _context2.prev = 17; + _context2.t0 = _context2["catch"](5); + if (!(_context2.t0.response && _context2.t0.response.status && _context2.t0.response.status === 404)) { + _context2.next = 23; + break; + } + debug.log('Error 404 for chat parent file ' + parent); + _context2.next = 25; + break; + case 23: + debug.log('*** Error NON 404 for chat parent file ' + parent); + // statusTR.appendChild(widgets.errorMessageBlock(dom, err, 'pink')) + throw new Error("*** ".concat(_context2.t0.message, " for chat folder ").concat(parent)); + case 25: + if (!(level === 0)) { + _context2.next = 27; + break; + } + return _context2.abrupt("return", null); + case 27: + _context2.next = 29; + return previousPeriod(parent, level - 1); + case 29: + uncle = _context2.sent; + if (uncle) { + _context2.next = 32; + break; + } + return _context2.abrupt("return", null); + case 32: + _context2.next = 34; + return _solidLogic.store.fetcher.load(uncle); + case 34: + cousins = _solidLogic.store.each(uncle, ns.ldp('contains')); + _context2.next = 37; + return lastNonEmpty(cousins); + case 37: + result = _context2.sent; + return _context2.abrupt("return", result); + case 39: + case "end": + return _context2.stop(); + } + }, _callee2, null, [[5, 17]]); + })); + return _previousPeriod.apply(this, arguments); + }; + previousPeriod = function _previousPeriod2(_x3, _x4) { + return _previousPeriod.apply(this, arguments); + }; + thisDateFolder = this; + // previousPeriod + folder = this.leafDocumentFromDate(date).dir(); + _context3.next = 6; + return previousPeriod(folder, 3); + case 6: + found = _context3.sent; + if (!found) { + _context3.next = 10; + break; + } + doc = _solidLogic.store.sym(found.uri + this.leafFileName); + return _context3.abrupt("return", this.dateFromLeafDocument(doc)); + case 10: + return _context3.abrupt("return", null); + case 11: + case "end": + return _context3.stop(); + } + }, _callee3, this); + })); + function loadPrevious(_x, _x2) { + return _loadPrevious.apply(this, arguments); + } + return loadPrevious; + }() // loadPrevious }, { - key: "any", - value: function any(s, p, o, g) { - var st = this.anyStatementMatching(s, p, o, g); - if (st == null) { - return null; - } else if (s == null) { - return st.subject; - } else if (p == null) { - return st.predicate; - } else if (o == null) { - return st.object; + key: "firstLeaf", + value: function () { + var _firstLeaf = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(backwards) { + var folderStore, folderFetcher, earliestSubfolder, _earliestSubfolder, y, month, d, leafDocument, leafObjects, msg, sortMe; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + _earliestSubfolder = function _earliestSubfolder3() { + _earliestSubfolder = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(parent) { + var suitable, kids; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + suitable = function _suitable2(x) { + var tail = x.uri.slice(0, -1).split('/').slice(-1)[0]; + if (!'0123456789'.includes(tail[0])) return false; // not numeric + return true; + }; + debug.log(' parent ' + parent); + delete folderFetcher.requested[parent.uri]; + // try { + _context4.next = 5; + return folderFetcher.load(parent, { + force: true + }); + case 5: + // Force fetch as will have changed + // }catch (err) { + // } + kids = folderStore.each(parent, ns.ldp('contains')); + kids = kids.filter(suitable); + if (!(kids.length === 0)) { + _context4.next = 9; + break; + } + throw new Error(' @@@ No children to parent2 ' + parent); + case 9: + kids.sort(); + if (backwards) kids.reverse(); + return _context4.abrupt("return", kids[0]); + case 12: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _earliestSubfolder.apply(this, arguments); + }; + earliestSubfolder = function _earliestSubfolder2(_x7) { + return _earliestSubfolder.apply(this, arguments); + }; + // backwards -> last leafObject + folderStore = $rdf.graph(); + folderFetcher = new $rdf.Fetcher(folderStore); + _context5.next = 6; + return earliestSubfolder(this.root.dir()); + case 6: + y = _context5.sent; + _context5.next = 9; + return earliestSubfolder(y); + case 9: + month = _context5.sent; + _context5.next = 12; + return earliestSubfolder(month); + case 12: + d = _context5.sent; + leafDocument = $rdf.sym(d.uri + 'chat.ttl'); + _context5.next = 16; + return folderFetcher.load(leafDocument); + case 16: + leafObjects = folderStore.each(this.root, this.membershipProperty, null, leafDocument); + if (!(leafObjects.length === 0)) { + _context5.next = 21; + break; + } + msg = ' INCONSISTENCY -- no chat leafObject in file ' + leafDocument; + debug.trace(msg); + throw new Error(msg); + case 21: + sortMe = leafObjects.map(function (leafObject) { + return [folderStore.any(leafObject, ns.dct('created')), leafObject]; + }); + sortMe.sort(); + if (backwards) sortMe.reverse(); + debug.log((backwards ? 'Latest' : 'Earliest') + ' leafObject is ' + sortMe[0][1]); + return _context5.abrupt("return", sortMe[0][1]); + case 26: + case "end": + return _context5.stop(); + } + }, _callee5, this); + })); + function firstLeaf(_x6) { + return _firstLeaf.apply(this, arguments); } - return null; - } + return firstLeaf; + }() // firstleafObject + }]); + return DateFolder; +}(); // class +exports.DateFolder = DateFolder; +//# sourceMappingURL=dateFolder.js.map - /** - * Gets the value of a node that matches the specified pattern - * @param s The subject - * @param p The predicate - * @param o The object - * @param g The graph that contains the statement - */ - }, { - key: "anyValue", - value: function anyValue(s, p, o, g) { - var y = this.any(s, p, o, g); - return y ? y.value : void 0; - } +/***/ }), - /** - * Gets the first JavaScript object equivalent to a node based on the specified pattern - * @param s The subject - * @param p The predicate - * @param o The object - * @param g The graph that contains the statement - */ - }, { - key: "anyJS", - value: function anyJS(s, p, o, g) { - var y = this.any(s, p, o, g); - return y ? _node_internal__WEBPACK_IMPORTED_MODULE_12__["default"].toJS(y) : void 0; - } +/***/ "./lib/chat/infinite.js": +/*!******************************!*\ + !*** ./lib/chat/infinite.js ***! + \******************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - /** - * Gets the first statement that matches the specified pattern - */ - }, { - key: "anyStatementMatching", - value: function anyStatementMatching(s, p, o, g) { - var x = this.statementsMatching(s, p, o, g, true); - if (!x || x.length === 0) { - return undefined; - } - return x[0]; - } +"use strict"; - /** - * Returns a unique index-safe identifier for the given term. - * - * Falls back to the rdflib hashString implementation if the given factory doesn't support id. - */ - }, { - key: "id", - value: function id(term) { - return this.rdfFactory.id(term); - } - /** - * Search the Store - * This is really a teaching method as to do this properly you would use IndexedFormula - * - * @param s - A node to search for as subject, or if null, a wildcard - * @param p - A node to search for as predicate, or if null, a wildcard - * @param o - A node to search for as object, or if null, a wildcard - * @param g - A node to search for as graph, or if null, a wildcard - * @param justOne - flag - stop when found one rather than get all of them? - * @returns {Array} - An array of nodes which match the wildcard position - */ - }, { - key: "statementsMatching", - value: function statementsMatching(s, p, o, g, justOne) { - var sts = this.statements.filter(function (st) { - return (!s || s.equals(st.subject)) && (!p || p.equals(st.predicate)) && (!o || o.equals(st.object)) && (!g || g.equals(st.graph)); - }); - if (justOne) { - return sts.length === 0 ? [] : [sts[0]]; - } - return sts; - } +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.desktopNotification = desktopNotification; +exports.infiniteMessageArea = infiniteMessageArea; +exports.insertMessageIntoTable = insertMessageIntoTable; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +var _chatLogic = __webpack_require__(/*! ./chatLogic */ "./lib/chat/chatLogic.js"); +var _message = __webpack_require__(/*! ./message */ "./lib/chat/message.js"); +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); } +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; } +/** + * Contains the [[infiniteMessageArea]] class + * @packageDocumentation + */ +// import { findBookmarkDocument } from './bookmarks' +// pull in first avoid cross-refs - /** - * Finds the types in the list which have no *stored* subtypes - * These are a set of classes which provide by themselves complete - * information -- the other classes are redundant for those who - * know the class DAG. - * @param types A map of the types - */ - }, { - key: "bottomTypeURIs", - value: function bottomTypeURIs(types) { - var bots; - var bottom; - var elt; - var i; - var len; - var ref; - var subs; - var v; - bots = []; - for (var _k in types) { - if (!types.hasOwnProperty(_k)) continue; - v = types[_k]; - subs = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), this.rdfFactory.namedNode(_k)); - bottom = true; - i = 0; - for (len = subs.length; i < len; i++) { - elt = subs[i]; - ref = elt.uri; - if (ref in types) { - // the subclass is one we know - bottom = false; - break; - } - } - if (bottom) { - bots[_k] = v; - } - } - return bots; - } +// import * as style from '../style' +// import * as utils from '../utils' - /** Creates a new collection */ - }, { - key: "collection", - value: function collection() { - return new _collection__WEBPACK_IMPORTED_MODULE_13__["default"](); - } +// import * as pad from '../pad' +// import { DateFolder } from './dateFolder' - /** Follow links from one node, using one wildcard. - * - * For example, each(me, knows, null, profile) - people I know accoring to my profile . - * each(me, knows, null, null) - people I know accoring to anything in store . - * each(null, knows, me, null) - people who know me accoring to anything in store . - * - * @param s - A node to search for as subject, or if null, a wildcard - * @param p - A node to search for as predicate, or if null, a wildcard - * @param o - A node to search for as object, or if null, a wildcard - * @param g - A node to search for as graph, or if null, a wildcard - * @returns {Array} - An array of nodes which match the wildcard position - */ - }, { - key: "each", - value: function each(s, p, o, g) { - var results = []; - var sts = this.statementsMatching(s, p, o, g, false); - if (s == null) { - for (var i = 0, len = sts.length; i < len; i++) { - results.push(sts[i].subject); - } - } else if (p == null) { - for (var l = 0, len1 = sts.length; l < len1; l++) { - results.push(sts[l].predicate); - } - } else if (o == null) { - for (var m = 0, len2 = sts.length; m < len2; m++) { - results.push(sts[m].object); - } - } else if (g == null) { - for (var _q = 0, len3 = sts.length; _q < len3; _q++) { - results.push(new _named_node__WEBPACK_IMPORTED_MODULE_14__["default"](sts[_q].graph.value)); - } - } - return results; - } - - /** - * Test whether this formula is equals to {other} - * @param other - The other formula - */ - }, { - key: "equals", - value: function equals(other) { - if (!other) { - return false; - } - return this.hashString() === other.hashString(); - } +// const UI = { authn, icons, ns, media, pad, $rdf, store, style, utils, widgets } - /** - * For thisClass or any subclass, anything which has it is its type - * or is the object of something which has the type as its range, or subject - * of something which has the type as its domain - * We don't bother doing subproperty (yet?)as it doesn't seeem to be used - * much. - * Get all the Classes of which we can RDFS-infer the subject is a member - * @return a hash of URIs - */ - }, { - key: "findMembersNT", - value: function findMembersNT(thisClass) { - var len2; - var len4; - var m; - var members; - var pred; - var ref; - var ref1; - var ref2; - var ref3; - var ref4; - var ref5; - var seeds; - var st; - var u; - seeds = {}; - seeds[thisClass.toNT()] = true; - members = {}; - ref = this.transitiveClosure(seeds, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true); - for (var t in ref) { - if (!ref.hasOwnProperty(t)) continue; - ref1 = this.statementsMatching(void 0, this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), this.fromNT(t)); - for (var i = 0, len = ref1.length; i < len; i++) { - st = ref1[i]; - members[st.subject.toNT()] = st; - } - ref2 = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain'), this.fromNT(t)); - for (var l = 0, len1 = ref2.length; l < len1; l++) { - pred = ref2[l]; - ref3 = this.statementsMatching(void 0, pred); - for (m = 0, len2 = ref3.length; m < len2; m++) { - st = ref3[m]; - members[st.subject.toNT()] = st; - } - } - ref4 = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range'), this.fromNT(t)); - for (var _q2 = 0, len3 = ref4.length; _q2 < len3; _q2++) { - pred = ref4[_q2]; - ref5 = this.statementsMatching(void 0, pred); - for (u = 0, len4 = ref5.length; u < len4; u++) { - st = ref5[u]; - members[st.object.toNT()] = st; - } - } +function desktopNotification(str) { + // Let's check if the browser supports notifications + if (!('Notification' in window)) { + debug.warn('This browser does no t support desktop notification'); + } else if (Notification.permission === 'granted') { + // Let's check whether notificatio n permissions have already been granted + // eslint-disable-next-line no-new + new Notification(str); + } else if (Notification.permission !== 'denied') { + // Otherwise, we need to ask the user for permission + Notification.requestPermission().then(function (permission) { + // If the user accepts, let's create a notification + if (permission === 'granted') { + // eslint-disable-next-line no-new + new Notification(str); } - return members; - } - - /** - * For thisClass or any subclass, anything which has it is its type - * or is the object of something which has the type as its range, or subject - * of something which has the type as its domain - * We don't bother doing subproperty (yet?)as it doesn't seeem to be used - * much. - * Get all the Classes of which we can RDFS-infer the subject is a member - * @param subject - A named node - */ - }, { - key: "findMemberURIs", - value: function findMemberURIs(subject) { - return this.NTtoURI(this.findMembersNT(subject)); - } + }); + } + // At last, if the user has denied notifications, and you + // want to be respectful there is no need to bother them any more. +} - /** - * Get all the Classes of which we can RDFS-infer the subject is a superclass - * Returns a hash table where key is NT of type and value is statement why we - * think so. - * Does NOT return terms, returns URI strings. - * We use NT representations in this version because they handle blank nodes. - */ - }, { - key: "findSubClassesNT", - value: function findSubClassesNT(subject) { - var types = {}; - types[subject.toNT()] = true; - return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true); - } +/** + * Renders a chat message inside a `messageTable` + */ +function insertMessageIntoTable(channelObject, messageTable, message, fresh, options, userContext) { + var messageRow = (0, _message.renderMessageRow)(channelObject, message, fresh, options, userContext); - /** - * Get all the Classes of which we can RDFS-infer the subject is a subclass - * @param {RDFlibNamedNode} subject - The thing whose classes are to be found - * @returns a hash table where key is NT of type and value is statement why we - * think so. - * Does NOT return terms, returns URI strings. - * We use NT representations in this version because they handle blank nodes. - */ - }, { - key: "findSuperClassesNT", - value: function findSuperClassesNT(subject) { - var types = {}; - types[subject.toNT()] = true; - return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false); + // const message = messageRow.AJAR_subject + if (options.selectedMessage && options.selectedMessage.sameTerm(message)) { + messageRow.style.backgroundColor = 'yellow'; + options.selectedElement = messageRow; + messageTable.selectedElement = messageRow; + } + var done = false; + for (var ele = messageTable.firstChild;; ele = ele.nextSibling) { + if (!ele) { + // empty + break; } - - /** - * Get all the Classes of which we can RDFS-infer the subject is a member - * todo: This will loop is there is a class subclass loop (Sublass loops are - * not illegal) - * @param {RDFlibNamedNode} subject - The thing whose classes are to be found - * @returns a hash table where key is NT of type and value is statement why we think so. - * Does NOT return terms, returns URI strings. - * We use NT representations in this version because they handle blank nodes. - */ - }, { - key: "findTypesNT", - value: function findTypesNT(subject) { - var domain; - var range; - var rdftype; - var ref; - var ref1; - var ref2; - var ref3; - var st; - var types; - rdftype = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'; - types = []; - ref = this.statementsMatching(subject, void 0, void 0); - for (var i = 0, len = ref.length; i < len; i++) { - st = ref[i]; - if (st.predicate.uri === rdftype) { - types[st.object.toNT()] = st; - } else { - ref1 = this.each(st.predicate, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain')); - for (var l = 0, len1 = ref1.length; l < len1; l++) { - range = ref1[l]; - types[range.toNT()] = st; - } - } - } - ref2 = this.statementsMatching(void 0, void 0, subject); - for (var m = 0, len2 = ref2.length; m < len2; m++) { - st = ref2[m]; - ref3 = this.each(st.predicate, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range')); - for (var _q3 = 0, len3 = ref3.length; _q3 < len3; _q3++) { - domain = ref3[_q3]; - types[domain.toNT()] = st; - } - } - return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false); + var newestFirst = options.newestfirst === true; + var dateString = messageRow.AJAR_date; + if (dateString > ele.AJAR_date && newestFirst || dateString < ele.AJAR_date && !newestFirst) { + messageTable.insertBefore(messageRow, ele); + done = true; + break; } + } + if (!done) { + messageTable.appendChild(messageRow); + } +} - /** - * Get all the Classes of which we can RDFS-infer the subject is a member - * todo: This will loop is there is a class subclass loop (Sublass loops are - * not illegal) - * Returns a hash table where key is NT of type and value is statement why we - * think so. - * Does NOT return terms, returns URI strings. - * We use NT representations in this version because they handle blank nodes. - * @param subject - A subject node - */ - }, { - key: "findTypeURIs", - value: function findTypeURIs(subject) { - return this.NTtoURI(this.findTypesNT(subject)); - } +/** + * Common code for a chat (discussion area of messages about something) + * This version runs over a series of files for different time periods + * + * Parameters for the whole chat like its title are stored on + * index.ttl#this and the chats messages are stored in YYYY/MM/DD/chat.ttl + * + * Use to import store as param 2, now ignores it and uses the UI main store + * + * Options include: - /** Trace statements which connect directly, or through bnodes - * - * @param subject - The node to start looking for statments - * @param doc - The document to be searched, or null to search all documents - * @returns an array of statements, duplicate statements are suppresssed. - */ - }, { - key: "connectedStatements", - value: function connectedStatements(subject, doc, excludePredicateURIs) { - excludePredicateURIs = excludePredicateURIs || []; - var todo = [subject]; - var done = {}; - var doneArcs = {}; - var result = []; - var self = this; - var follow = function follow(x) { - var queue = function queue(x) { - if (x.termType === 'BlankNode' && !done[x.value]) { - done[x.value] = true; - todo.push(x); - } - }; - var sts = self.statementsMatching(null, null, x, doc).concat(self.statementsMatching(x, null, null, doc)); - sts = sts.filter(function (st) { - if (excludePredicateURIs[st.predicate.value]) return false; - var hash = st.toNT(); - if (doneArcs[hash]) return false; - doneArcs[hash] = true; - return true; - }); - sts.forEach(function (st) { - queue(st.subject); - queue(st.object); - }); - result = result.concat(sts); - }; - while (todo.length) { - follow(todo.shift()); - } - return result; - } + - shiftEnterSendsMessage: Use shift/enter to send message, Enter to add newline, instead of the reverse. + - authorDateOnLeft: Display the author's anme and date of the message in the left column instead of first above the content + - selectedMessage: Display one message highlighted with the chat around it + - solo: By itelf on a webpage, so user scroll anywhere in the web page scan scroll the chat. + - newestFirst: Arrange the chat messages chronologically newest at the top insted of at the bottom + - infinite: Use infinite scroll + - showDeletedMessages: Show messages which have been delted as "deleted message". Otherwise hide them. + - expandImagesInline: If a URI by itself in a message looks like an image URI, replace it with the image + - inlineImageHeightEms: The height (in ems) of images expaned from their URIs in the chat. - /** - * Creates a new empty formula - * - * @param _features - Not applicable, but necessary for typing to pass - */ - }, { - key: "formula", - value: function formula(_features) { - return new Formula(); - } + */ +function infiniteMessageArea(_x, _x2, _x3, _x4) { + return _infiniteMessageArea.apply(this, arguments); +} +function _infiniteMessageArea() { + _infiniteMessageArea = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(dom, wasStore, chatChannel, options) { + var syncMessages, addMessage, insertPreviousMessages, _insertPreviousMessages, removePreviousMessages, createMessageTable, _createMessageTable, renderMessageTable, addNewChatDocumentIfNewDay, _addNewChatDocumentIfNewDay, appendCurrentMessages, _appendCurrentMessages, loadMoreWhereNeeded, _loadMoreWhereNeeded, loadInitialContent, _loadInitialContent, newestFirst, channelObject, dateFolder, div, statusArea, userContext, liveMessageTable, earliest, latest, lock; + return _regenerator["default"].wrap(function _callee12$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + _loadInitialContent = function _loadInitialContent3() { + _loadInitialContent = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11() { + var yank, fixScroll, live, selectedDocument, now, todayDocument, selectedMessageTable, selectedDate; + return _regenerator["default"].wrap(function _callee11$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + fixScroll = function _fixScroll() { + if (options.selectedElement) { + options.selectedElement.scrollIntoView({ + block: 'center' + }); // align tops or bottoms + } else { + if (liveMessageTable.inputRow.scrollIntoView) { + liveMessageTable.inputRow.scrollIntoView(newestFirst); // align tops or bottoms + } + } + }; + yank = function _yank() { + selectedMessageTable.selectedElement.scrollIntoView({ + block: 'center' + }); + }; + if (options.selectedMessage) { + selectedDocument = options.selectedMessage.doc(); + now = new Date(); + todayDocument = dateFolder.leafDocumentFromDate(now); + live = todayDocument.sameTerm(selectedDocument); + } + if (!(options.selectedMessage && !live)) { + _context11.next = 15; + break; + } + selectedDate = dateFolder.dateFromLeafDocument(selectedDocument); + _context11.next = 7; + return createMessageTable(selectedDate, live); + case 7: + selectedMessageTable = _context11.sent; + div.appendChild(selectedMessageTable); + earliest.messageTable = selectedMessageTable; + latest.messageTable = selectedMessageTable; + yank(); + setTimeout(yank, 1000); // @@ kludge - restore position distubed by other cHANGES + _context11.next = 19; + break; + case 15: + _context11.next = 17; + return appendCurrentMessages(); + case 17: + earliest.messageTable = liveMessageTable; + latest.messageTable = liveMessageTable; + case 19: + _context11.next = 21; + return loadMoreWhereNeeded(null, fixScroll); + case 21: + div.addEventListener('scroll', loadMoreWhereNeeded); + if (options.solo) { + document.body.addEventListener('scroll', loadMoreWhereNeeded); + } + case 23: + case "end": + return _context11.stop(); + } + }, _callee11); + })); + return _loadInitialContent.apply(this, arguments); + }; + loadInitialContent = function _loadInitialContent2() { + return _loadInitialContent.apply(this, arguments); + }; + _loadMoreWhereNeeded = function _loadMoreWhereNeeded3() { + _loadMoreWhereNeeded = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(event, fixScroll) { + var freeze, magicZone, done, scrollBottom, scrollTop; + return _regenerator["default"].wrap(function _callee10$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + if (!lock) { + _context10.next = 2; + break; + } + return _context10.abrupt("return"); + case 2: + lock = true; + freeze = !fixScroll; + magicZone = 150; // const top = div.scrollTop + // const bottom = div.scrollHeight - top - div.clientHeight + case 5: + if (!(div.scrollTop < magicZone && earliest.messageTable && !earliest.messageTable.initial && earliest.messageTable.extendBackwards)) { + _context10.next = 21; + break; + } + if (!(div.scrollHeight === 0)) { + _context10.next = 10; + break; + } + // console.log(' chat/loadMoreWhereNeeded: trying later...') + setTimeout(loadMoreWhereNeeded, 2000); // couple be less + lock = false; + return _context10.abrupt("return"); + case 10: + // console.log(' chat/loadMoreWhereNeeded: Going now') + scrollBottom = div.scrollHeight - div.scrollTop; + debug.log('infinite scroll: adding above: top ' + div.scrollTop); + _context10.next = 14; + return earliest.messageTable.extendBackwards(); + case 14: + done = _context10.sent; + if (freeze) { + div.scrollTop = div.scrollHeight - scrollBottom; + } + if (fixScroll) fixScroll(); + if (!done) { + _context10.next = 19; + break; + } + return _context10.abrupt("break", 21); + case 19: + _context10.next = 5; + break; + case 21: + if (!(options.selectedMessage && + // we started in the middle not at the bottom + div.scrollHeight - div.scrollTop - div.clientHeight < magicZone && + // we are scrolled right to the bottom + latest.messageTable && !latest.messageTable["final"] && + // there is more data to come + latest.messageTable.extendForwards)) { + _context10.next = 33; + break; + } + scrollTop = div.scrollTop; + debug.log('infinite scroll: adding below: bottom: ' + (div.scrollHeight - div.scrollTop - div.clientHeight)); + _context10.next = 26; + return latest.messageTable.extendForwards(); + case 26: + done = _context10.sent; + // then add more data on the bottom + if (freeze) { + div.scrollTop = scrollTop; // while adding below keep same things in view + } - /** - * Transforms an NTriples string format into a Node. - * The blank node bit should not be used on program-external values; designed - * for internal work such as storing a blank node id in an HTML attribute. - * This will only parse the strings generated by the various toNT() methods. - */ - }, { - key: "fromNT", - value: function fromNT(str) { - var dt, k, lang; - switch (str[0]) { - case '<': - return this.sym(str.slice(1, -1)); - case '"': - lang = void 0; - dt = void 0; - k = str.lastIndexOf('"'); - if (k < str.length - 1) { - if (str[k + 1] === '@') { - lang = str.slice(k + 2); - } else if (str.slice(k + 1, k + 3) === '^^') { - dt = this.fromNT(str.slice(k + 3)); - } else { - throw new Error("Can't convert string from NT: " + str); - } - } - str = str.slice(1, k); - str = str.replace(/\\"/g, '"'); - str = str.replace(/\\n/g, '\n'); - str = str.replace(/\\\\/g, '\\'); - return this.rdfFactory.literal(str, lang || dt); - case '_': - return this.rdfFactory.blankNode(str.slice(2)); - case '?': - return new _variable__WEBPACK_IMPORTED_MODULE_15__["default"](str.slice(1)); - } - throw new Error("Can't convert from NT: " + str); - } + if (fixScroll) fixScroll(); + if (!done) { + _context10.next = 31; + break; + } + return _context10.abrupt("break", 33); + case 31: + _context10.next = 21; + break; + case 33: + lock = false; + case 34: + case "end": + return _context10.stop(); + } + }, _callee10); + })); + return _loadMoreWhereNeeded.apply(this, arguments); + }; + loadMoreWhereNeeded = function _loadMoreWhereNeeded2(_x10, _x11) { + return _loadMoreWhereNeeded.apply(this, arguments); + }; + _appendCurrentMessages = function _appendCurrentMessage2() { + _appendCurrentMessages = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9() { + var now, chatDocument, messageTable; + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + now = new Date(); + chatDocument = dateFolder.leafDocumentFromDate(now); /// /////////////////////////////////////////////////////////// + _context9.next = 4; + return createMessageTable(now, true); + case 4: + messageTable = _context9.sent; + div.appendChild(messageTable); + div.refresh = /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() { + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return addNewChatDocumentIfNewDay(new Date()); + case 2: + syncMessages(chatChannel, messageTable); // @@ livemessagetable?? + desktopNotification(chatChannel); + case 4: + case "end": + return _context8.stop(); + } + }, _callee8); + })); // The short chat version the live update listening is done in the pane but we do it in the widget @@ + _solidLogic.store.updater.addDownstreamChangeListener(chatDocument, div.refresh); // Live update + liveMessageTable = messageTable; + latest.messageTable = liveMessageTable; + return _context9.abrupt("return", messageTable); + case 11: + case "end": + return _context9.stop(); + } + }, _callee9); + })); + return _appendCurrentMessages.apply(this, arguments); + }; + appendCurrentMessages = function _appendCurrentMessage() { + return _appendCurrentMessages.apply(this, arguments); + }; + _addNewChatDocumentIfNewDay = function _addNewChatDocumentIf2() { + _addNewChatDocumentIfNewDay = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7() { + var newChatDocument, oldChatDocument, sts; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + // @@ Remove listener from previous table as it is now static + newChatDocument = dateFolder.leafDocumentFromDate(new Date()); + if (newChatDocument.sameTerm(latest.messageTable.chatDocument)) { + _context7.next = 7; + break; + } + // It is a new day + if (liveMessageTable.inputRow) { + liveMessageTable.removeChild(liveMessageTable.inputRow); + delete liveMessageTable.inputRow; + } + oldChatDocument = latest.messageTable.chatDocument; + _context7.next = 6; + return appendCurrentMessages(); + case 6: + // Adding a link in the document will ping listeners to add the new block too + if (!_solidLogic.store.holds(oldChatDocument, ns.rdfs('seeAlso'), newChatDocument, oldChatDocument)) { + sts = [$rdf.st(oldChatDocument, ns.rdfs('seeAlso'), newChatDocument, oldChatDocument)]; + try { + _solidLogic.store.updater.update([], sts); + } catch (err) { + alert('Unable to link old chat file to new one:' + err); + } + } + case 7: + case "end": + return _context7.stop(); + } + }, _callee7); + })); + return _addNewChatDocumentIfNewDay.apply(this, arguments); + }; + addNewChatDocumentIfNewDay = function _addNewChatDocumentIf() { + return _addNewChatDocumentIfNewDay.apply(this, arguments); + }; + renderMessageTable = function _renderMessageTable(date, live) { + var scrollBackbutton; + var scrollForwardButton; - /** Returns true if this formula holds the specified statement(s) */ - }, { - key: "holds", - value: function holds(s, p, o, g) { - var i; - if (arguments.length === 1) { - if (!s) { - return true; - } - if (s instanceof Array) { - for (i = 0; i < s.length; i++) { - if (!this.holds(s[i])) { - return false; + /// ///////////////// Scroll down adding more above + function extendBackwards() { + return _extendBackwards.apply(this, arguments); } - } - return true; - } else if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_16__.isStatement)(s)) { - return this.holds(s.subject, s.predicate, s.object, s.graph); - } else if (s.statements) { - return this.holds(s.statements); - } - } - var st = this.anyStatementMatching(s, p, o, g); - return st != null; - } - - /** - * Returns true if this formula holds the specified {statement} - */ - }, { - key: "holdsStatement", - value: function holdsStatement(statement) { - return this.holds(statement.subject, statement.predicate, statement.object, statement.graph); - } - - /** - * Used by the n3parser to generate list elements - * @param values - The values of the collection - * @param context - The store - * @return {BlankNode|Collection} - The term for the statement - */ - }, { - key: "list", - value: function list(values, context) { - if (context.rdfFactory.supports["COLLECTIONS"]) { - var collection = context.rdfFactory.collection(); - values.forEach(function (val) { - collection.append(val); - }); - return collection; - } else { - var node = context.rdfFactory.blankNode(); - var statements = (0,_utils__WEBPACK_IMPORTED_MODULE_11__.arrayToStatements)(context.rdfFactory, node, values); - context.addAll(statements); - return node; - } - } + function _extendBackwards() { + _extendBackwards = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var done; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return insertPreviousMessages(true); + case 2: + done = _context.sent; + if (done) { + if (scrollBackbutton) { + scrollBackbutton.firstChild.setAttribute('src', _iconBase.icons.iconBase + 'noun_T-Block_1114655_000000.svg'); // T + scrollBackbutton.disabled = true; + } + messageTable.initial = true; + } else { + messageTable.extendedBack = true; + } + setScrollBackbuttonIcon(); + return _context.abrupt("return", done); + case 6: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _extendBackwards.apply(this, arguments); + } + function setScrollBackbuttonIcon() { + if (!scrollBackbutton) { + return; + } + var sense = messageTable.extendedBack ? !newestFirst : newestFirst; + var scrollBackIcon = messageTable.initial ? 'noun_T-Block_1114655_000000.svg' : getScrollbackIcon(sense); + scrollBackbutton.firstChild.setAttribute('src', _iconBase.icons.iconBase + scrollBackIcon); + function getScrollbackIcon(sense) { + return sense ? 'noun_1369241.svg' : 'noun_1369237.svg'; + } + } + function scrollBackbuttonHandler(_x8) { + return _scrollBackbuttonHandler.apply(this, arguments); + } /// ////////////// Scroll up adding more below + function _scrollBackbuttonHandler() { + _scrollBackbuttonHandler = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(_event) { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + if (!messageTable.extendedBack) { + _context2.next = 6; + break; + } + removePreviousMessages(true, messageTable); + messageTable.extendedBack = false; + setScrollBackbuttonIcon(); + _context2.next = 8; + break; + case 6: + _context2.next = 8; + return extendBackwards(); + case 8: + case "end": + return _context2.stop(); + } + }, _callee2); + })); + return _scrollBackbuttonHandler.apply(this, arguments); + } + function extendForwards() { + return _extendForwards.apply(this, arguments); + } + function _extendForwards() { + _extendForwards = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { + var done; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return insertPreviousMessages(false); + case 2: + done = _context3.sent; + if (done) { + scrollForwardButton.firstChild.setAttribute('src', _iconBase.icons.iconBase + 'noun_T-Block_1114655_000000.svg'); + scrollForwardButton.disabled = true; + messageTable["final"] = true; + } else { + messageTable.extendedForwards = true; + } + setScrollForwardButtonIcon(); + return _context3.abrupt("return", done); + case 6: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _extendForwards.apply(this, arguments); + } + function setScrollForwardButtonIcon() { + var sense = messageTable.extendedForwards ? !newestFirst : newestFirst; // noun_T-Block_1114657_000000.svg + var scrollForwardIcon = messageTable["final"] ? 'noun_T-Block_1114657_000000.svg' : getScrollForwardButtonIcon(sense); + scrollForwardButton.firstChild.setAttribute('src', _iconBase.icons.iconBase + scrollForwardIcon); + function getScrollForwardButtonIcon(sense) { + return !sense ? 'noun_1369241.svg' : 'noun_1369237.svg'; + } + } + function scrollForwardButtonHandler(_x9) { + return _scrollForwardButtonHandler.apply(this, arguments); + } /// /////////////////////// + /* + options = options || {} + options.authorDateOnLeft = true + const newestFirst = options.newestFirst === '1' || options.newestFirst === true // hack for now + const channelObject = new ChatChannel(chatChannel, options) + const dateFolder = channelObject.dateFolder + const div = dom.createElement('div') + const statusArea = div.appendChild(dom.createElement('div')) + const userContext = { dom, statusArea, div: statusArea } // logged on state, pointers to user's stuff + */ + function _scrollForwardButtonHandler() { + _scrollForwardButtonHandler = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(_event) { + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!messageTable.extendedForwards) { + _context4.next = 6; + break; + } + removePreviousMessages(false, messageTable); + messageTable.extendedForwards = false; + setScrollForwardButtonIcon(); + _context4.next = 9; + break; + case 6: + _context4.next = 8; + return extendForwards(); + case 8: + // async + latest.messageTable.scrollIntoView(newestFirst); + case 9: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _scrollForwardButtonHandler.apply(this, arguments); + } + var messageTable = dom.createElement('table'); + messageTable.extendBackwards = extendBackwards; // Make function available to scroll stuff + messageTable.extendForwards = extendForwards; // Make function available to scroll stuff - /** - * Transform a collection of NTriple URIs into their URI strings - * @param t - Some iterable collection of NTriple URI strings - * @return A collection of the URIs as strings - * todo: explain why it is important to go through NT - */ - }, { - key: "NTtoURI", - value: function NTtoURI(t) { - var k, v; - var uris = {}; - for (k in t) { - if (!t.hasOwnProperty(k)) continue; - v = t[k]; - if (k[0] === '<') { - uris[k.slice(1, -1)] = v; - } - } - return uris; - } + messageTable.date = date; + var chatDocument = dateFolder.leafDocumentFromDate(date); + messageTable.chatDocument = chatDocument; + messageTable.fresh = false; + messageTable.setAttribute('style', 'width: 100%;'); // fill that div! + if (live) { + messageTable["final"] = true; + liveMessageTable = messageTable; + latest.messageTable = messageTable; + var tr = (0, _message.renderMessageEditor)(channelObject, messageTable, userContext, options); + if (newestFirst) { + messageTable.insertBefore(tr, messageTable.firstChild); // If newestFirst + } else { + messageTable.appendChild(tr); // not newestFirst + } - /** - * Serializes this formula - * @param base - The base string - * @param contentType - The content type of the syntax to use - * @param provenance - The provenance URI - * @param options - options to pass to the serializer, as defined in serialize method - */ - }, { - key: "serialize", - value: function serialize(base, contentType, provenance, options) { - // delegate the graph serialization to the implementation in ./serialize - return (0,_serialize__WEBPACK_IMPORTED_MODULE_17__["default"])(provenance, this, base, contentType, undefined, options); - } + messageTable.inputRow = tr; + } - /** - * Creates a new formula with the substituting bindings applied - * @param bindings - The bindings to substitute - */ - }, { - key: "substitute", - value: function substitute(bindings) { - var statementsCopy = this.statements.map(function (ea) { - return ea.substitute(bindings); - }); - // console.log('Formula subs statmnts:' + statementsCopy) - var y = new Formula(); - y.addAll(statementsCopy); - // console.log('indexed-form subs formula:' + y) - return y; - } - }, { - key: "sym", - value: function sym(uri, name) { - if (name) { - throw new Error('This feature (kb.sym with 2 args) is removed. Do not assume prefix mappings.'); - } - return this.rdfFactory.namedNode(uri); - } + /// ///// Infinite scroll + // + // @@ listen for swipe past end event not just button + if (options.infinite) { + var scrollBackbuttonTR = dom.createElement('tr'); + var scrollBackbuttonCell = scrollBackbuttonTR.appendChild(dom.createElement('td')); + // up traingles: noun_1369237.svg + // down triangles: noun_1369241.svg + var scrollBackIcon = newestFirst ? 'noun_1369241.svg' : 'noun_1369237.svg'; // down and up arrows respoctively + scrollBackbutton = widgets.button(dom, _iconBase.icons.iconBase + scrollBackIcon, 'Previous messages ...'); + scrollBackbuttonCell.style = 'width:3em; height:3em;'; + scrollBackbutton.addEventListener('click', scrollBackbuttonHandler, false); + messageTable.extendedBack = false; + scrollBackbuttonCell.appendChild(scrollBackbutton); + setScrollBackbuttonIcon(); + var dateCell = scrollBackbuttonTR.appendChild(dom.createElement('td')); + dateCell.style = 'text-align: center; vertical-align: middle; color: #888; font-style: italic;'; + dateCell.textContent = widgets.shortDate(date.toISOString(), true); // no time, only date - /** - * Gets the node matching the specified pattern. Throws when no match could be made. - * @param s - The subject - * @param p - The predicate - * @param o - The object - * @param g - The graph that contains the statement - */ - }, { - key: "the", - value: function the(s, p, o, g) { - var x = this.any(s, p, o, g); - if (x == null) { - _log__WEBPACK_IMPORTED_MODULE_18__["default"].error('No value found for the() {' + s + ' ' + p + ' ' + o + '}.'); - } - return x; - } + // @@@@@@@@@@@ todo move this button to other end of message cell, o + var scrollForwardButtonCell = scrollBackbuttonTR.appendChild(dom.createElement('td')); + var scrollForwardIcon = newestFirst ? 'noun_1369241.svg' : 'noun_1369237.svg'; // down and up arrows respoctively + scrollForwardButton = widgets.button(dom, _iconBase.icons.iconBase + scrollForwardIcon, 'Later messages ...'); + scrollForwardButtonCell.appendChild(scrollForwardButton); + scrollForwardButtonCell.style = 'width:3em; height:3em;'; + scrollForwardButton.addEventListener('click', scrollForwardButtonHandler, false); + messageTable.extendedForward = false; + setScrollForwardButtonIcon(); + messageTable.extendedForwards = false; + if (!newestFirst) { + // opposite end from the entry field + messageTable.insertBefore(scrollBackbuttonTR, messageTable.firstChild); // If not newestFirst + } else { + messageTable.appendChild(scrollBackbuttonTR); // newestFirst + } + } - /** - * RDFS Inference - * These are hand-written implementations of a backward-chaining reasoner - * over the RDFS axioms. - * @param seeds - A hash of NTs of classes to start with - * @param predicate - The property to trace though - * @param inverse - Trace inverse direction - */ - }, { - key: "transitiveClosure", - value: function transitiveClosure(seeds, predicate, inverse) { - var elt, i, len, s, sups, t; - var agenda = {}; - Object.assign(agenda, seeds); // make a copy - var done = {}; // classes we have looked up - while (true) { - t = function () { - for (var p in agenda) { - if (!agenda.hasOwnProperty(p)) continue; - return p; - } - }(); - if (t == null) { - return done; - } - sups = inverse ? this.each(void 0, predicate, this.fromNT(t)) : this.each(this.fromNT(t), predicate); - for (i = 0, len = sups.length; i < len; i++) { - elt = sups[i]; - s = elt.toNT(); - if (s in done) { - continue; - } - if (s in agenda) { - continue; - } - agenda[s] = agenda[t]; - } - done[t] = agenda[t]; - delete agenda[t]; - } - } + var sts = _solidLogic.store.statementsMatching(null, ns.wf('message'), null, chatDocument); + if (!live && sts.length === 0) { + // not todays + // no need buttomns at the moment + // messageTable.style.visibility = 'collapse' // Hide files with no messages + } + sts.forEach(function (st) { + addMessage(st.object, messageTable); + }); + messageTable.fresh = true; - /** - * Finds the types in the list which have no *stored* supertypes - * We exclude the universal class, owl:Things and rdf:Resource, as it is - * information-free. - * @param types - The types - */ - }, { - key: "topTypeURIs", - value: function topTypeURIs(types) { - var i; - var j; - var k; - var len; - var n; - var ref; - var tops; - var v; - tops = []; - for (k in types) { - if (!types.hasOwnProperty(k)) continue; - v = types[k]; - n = 0; - ref = this.each(this.rdfFactory.namedNode(k), this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf')); - for (i = 0, len = ref.length; i < len; i++) { - j = ref[i]; - if (j.uri !== 'http://www.w3.org/2000/01/rdf-schema#Resource') { - n++; - break; - } - } - if (!n) { - tops[k] = v; - } - } - if (tops['http://www.w3.org/2000/01/rdf-schema#Resource']) { - delete tops['http://www.w3.org/2000/01/rdf-schema#Resource']; - } - if (tops['http://www.w3.org/2002/07/owl#Thing']) { - delete tops['http://www.w3.org/2002/07/owl#Thing']; - } - return tops; - } + // loadMessageTable(messageTable, chatDocument) + messageTable.fresh = false; + return messageTable; + }; + _createMessageTable = function _createMessageTable3() { + _createMessageTable = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(date, live) { + var chatDocument, messageTable, statusTR; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + debug.log(' createMessageTable for ' + date); + chatDocument = dateFolder.leafDocumentFromDate(date); + _context6.prev = 2; + _context6.next = 5; + return _solidLogic.store.fetcher.load(chatDocument); + case 5: + _context6.next = 19; + break; + case 7: + _context6.prev = 7; + _context6.t0 = _context6["catch"](2); + messageTable = dom.createElement('table'); + statusTR = messageTable.appendChild(dom.createElement('tr')); // ### find status in exception + if (!(_context6.t0.response && _context6.t0.response.status && _context6.t0.response.status === 404)) { + _context6.next = 16; + break; + } + debug.log('Error 404 for chat file ' + chatDocument); + return _context6.abrupt("return", renderMessageTable(date, live)); + case 16: + debug.log('*** Error NON 404 for chat file ' + chatDocument); + statusTR.appendChild(widgets.errorMessageBlock(dom, _context6.t0, 'pink')); + case 18: + return _context6.abrupt("return", statusTR); + case 19: + return _context6.abrupt("return", renderMessageTable(date, live)); + case 20: + case "end": + return _context6.stop(); + } + }, _callee6, null, [[2, 7]]); + })); + return _createMessageTable.apply(this, arguments); + }; + createMessageTable = function _createMessageTable2(_x6, _x7) { + return _createMessageTable.apply(this, arguments); + }; + removePreviousMessages = function _removePreviousMessag(backwards, messageTable) { + if (backwards ? newestFirst : !newestFirst) { + // it was put on bottom + while (messageTable.nextSibling) { + div.removeChild(messageTable.nextSibling); + } + } else { + // it was put on top as we scroll back + while (messageTable.previousSibling) { + div.removeChild(messageTable.previousSibling); + } + } + var extr = backwards ? earliest : latest; + extr.messageTable = messageTable; + }; + _insertPreviousMessages = function _insertPreviousMessag2() { + _insertPreviousMessages = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(backwards) { + var extremity, date, live, todayDoc, doc, newMessageTable; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + extremity = backwards ? earliest : latest; + date = extremity.messageTable.date; // day in mssecs + _context5.next = 4; + return dateFolder.loadPrevious(date, backwards); + case 4: + date = _context5.sent; + // backwards + debug.log("insertPreviousMessages: from ".concat(backwards ? 'backwards' : 'forwards', " loadPrevious: ").concat(date)); + if (!(!date && !backwards && !liveMessageTable)) { + _context5.next = 9; + break; + } + _context5.next = 9; + return appendCurrentMessages(); + case 9: + if (date) { + _context5.next = 11; + break; + } + return _context5.abrupt("return", true); + case 11: + // done + live = false; + if (!backwards) { + todayDoc = dateFolder.leafDocumentFromDate(new Date()); + doc = dateFolder.leafDocumentFromDate(date); + live = doc.sameTerm(todayDoc); // Is this todays? + } + _context5.next = 15; + return createMessageTable(date, live); + case 15: + newMessageTable = _context5.sent; + extremity.messageTable = newMessageTable; // move pointer to earliest + if (backwards ? newestFirst : !newestFirst) { + // put on bottom or top + div.appendChild(newMessageTable); + } else { + // put on top as we scroll back + div.insertBefore(newMessageTable, div.firstChild); + } + return _context5.abrupt("return", live); + case 19: + case "end": + return _context5.stop(); + } + }, _callee5); + })); + return _insertPreviousMessages.apply(this, arguments); + }; + insertPreviousMessages = function _insertPreviousMessag(_x5) { + return _insertPreviousMessages.apply(this, arguments); + }; + addMessage = function _addMessage(message, messageTable) { + var latest = (0, _chatLogic.mostRecentVersion)(message); + // const content = store.any(latest, ns.sioc('content')) + if ((0, _chatLogic.isDeleted)(latest) && !options.showDeletedMessages) { + return; // ignore deleted messaged -- @@ could also leave a placeholder + } - /** - * Serializes this formula to a string - */ - }, { - key: "toString", - value: function toString() { - return '{' + this.statements.join('\n') + '}'; - } + insertMessageIntoTable(channelObject, messageTable, message, messageTable.fresh, options, userContext); // fresh from elsewhere + }; + syncMessages = function _syncMessages(about, messageTable) { + var displayed = {}; + var ele, ele2; + for (ele = messageTable.firstChild; ele; ele = ele.nextSibling) { + if (ele.AJAR_subject) { + displayed[ele.AJAR_subject.uri] = true; + } + } + var messages = _solidLogic.store.statementsMatching(about, ns.wf('message'), null, messageTable.chatDocument).map(function (st) { + return st.object; + }); + var stored = {}; + messages.forEach(function (m) { + stored[m.uri] = true; + if (!displayed[m.uri]) { + addMessage(m, messageTable); + } + }); - /** - * Gets a new variable - * @param name - The variable's name - */ - }, { - key: "variable", - value: function variable(name) { - return new _variable__WEBPACK_IMPORTED_MODULE_15__["default"](name); - } + // eslint-disable-next-line space-in-parens + for (ele = messageTable.firstChild; ele;) { + ele2 = ele.nextSibling; + if (ele.AJAR_subject && !stored[ele.AJAR_subject.uri]) { + messageTable.removeChild(ele); + } + ele = ele2; + } + for (ele = messageTable.firstChild; ele; ele = ele.nextSibling) { + if (ele.AJAR_subject) { + // Refresh thumbs up etc + widgets.refreshTree(ele); // Things inside may have changed too + } + } + }; - /** - * Gets the number of statements in this formula that matches the specified pattern - * @param s - The subject - * @param p - The predicate - * @param o - The object - * @param g - The graph that contains the statement - */ - }, { - key: "whether", - value: function whether(s, p, o, g) { - return this.statementsMatching(s, p, o, g, false).length; - } - }]); - return Formula; -}(_node_internal__WEBPACK_IMPORTED_MODULE_12__["default"]); + // Body of main function + options = options || {}; + options.authorDateOnLeft = false; // @@ make a user optiosn + newestFirst = options.newestFirst === '1' || options.newestFirst === true; // hack for now + channelObject = new _chatLogic.ChatChannel(chatChannel, options); + dateFolder = channelObject.dateFolder; + div = dom.createElement('div'); + channelObject.div = div; + statusArea = div.appendChild(dom.createElement('div')); + userContext = { + dom: dom, + statusArea: statusArea, + div: statusArea + }; // logged on state, pointers to user's stuff + // const messageTable = dom.createElement('table') // @@ check does this go in renderMessageTable + earliest = { + messageTable: null + }; // Stuff about each end of the loaded days + latest = { + messageTable: null + }; + lock = false; + _context12.next = 30; + return loadInitialContent(); + case 30: + return _context12.abrupt("return", div); + case 31: + case "end": + return _context12.stop(); + } + }, _callee12); + })); + return _infiniteMessageArea.apply(this, arguments); +} +//# sourceMappingURL=infinite.js.map /***/ }), -/***/ "../rdflib/esm/index.js": -/*!******************************!*\ - !*** ../rdflib/esm/index.js ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./lib/chat/message.js": +/*!*****************************!*\ + !*** ./lib/chat/message.js ***! + \*****************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BlankNode": () => (/* reexport safe */ _blank_node__WEBPACK_IMPORTED_MODULE_10__["default"]), -/* harmony export */ "Collection": () => (/* reexport safe */ _collection__WEBPACK_IMPORTED_MODULE_12__["default"]), -/* harmony export */ "ConnectedStore": () => (/* binding */ ConnectedStore), -/* harmony export */ "DataFactory": () => (/* reexport safe */ _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"]), -/* harmony export */ "Empty": () => (/* reexport safe */ _empty__WEBPACK_IMPORTED_MODULE_13__["default"]), -/* harmony export */ "Fetcher": () => (/* reexport safe */ _fetcher__WEBPACK_IMPORTED_MODULE_14__["default"]), -/* harmony export */ "Formula": () => (/* reexport safe */ _formula__WEBPACK_IMPORTED_MODULE_8__["default"]), -/* harmony export */ "IndexedFormula": () => (/* reexport safe */ _store__WEBPACK_IMPORTED_MODULE_15__["default"]), -/* harmony export */ "Literal": () => (/* reexport safe */ _literal__WEBPACK_IMPORTED_MODULE_17__["default"]), -/* harmony export */ "LiveStore": () => (/* binding */ LiveStore), -/* harmony export */ "N3Parser": () => (/* reexport safe */ _n3parser__WEBPACK_IMPORTED_MODULE_19__["default"]), -/* harmony export */ "NamedNode": () => (/* reexport safe */ _named_node__WEBPACK_IMPORTED_MODULE_20__["default"]), -/* harmony export */ "Namespace": () => (/* reexport safe */ _namespace__WEBPACK_IMPORTED_MODULE_21__["default"]), -/* harmony export */ "NextId": () => (/* binding */ NextId), -/* harmony export */ "Node": () => (/* reexport safe */ _node__WEBPACK_IMPORTED_MODULE_9__["default"]), -/* harmony export */ "Query": () => (/* reexport safe */ _query__WEBPACK_IMPORTED_MODULE_23__.Query), -/* harmony export */ "RDFParser": () => (/* reexport safe */ _rdfxmlparser__WEBPACK_IMPORTED_MODULE_26__["default"]), -/* harmony export */ "RDFaProcessor": () => (/* reexport safe */ _rdfaparser__WEBPACK_IMPORTED_MODULE_25__["default"]), -/* harmony export */ "SPARQLToQuery": () => (/* reexport safe */ _sparql_to_query__WEBPACK_IMPORTED_MODULE_29__["default"]), -/* harmony export */ "Serializer": () => (/* reexport safe */ _serializer__WEBPACK_IMPORTED_MODULE_28__["default"]), -/* harmony export */ "Statement": () => (/* reexport safe */ _statement__WEBPACK_IMPORTED_MODULE_31__["default"]), -/* harmony export */ "Store": () => (/* reexport safe */ _store__WEBPACK_IMPORTED_MODULE_15__["default"]), -/* harmony export */ "UpdateManager": () => (/* reexport safe */ _update_manager__WEBPACK_IMPORTED_MODULE_32__["default"]), -/* harmony export */ "UpdatesSocket": () => (/* reexport safe */ _updates_via__WEBPACK_IMPORTED_MODULE_33__.UpdatesSocket), -/* harmony export */ "UpdatesVia": () => (/* reexport safe */ _updates_via__WEBPACK_IMPORTED_MODULE_33__.UpdatesVia), -/* harmony export */ "Util": () => (/* reexport module object */ _utils_js__WEBPACK_IMPORTED_MODULE_35__), -/* harmony export */ "Variable": () => (/* reexport safe */ _variable__WEBPACK_IMPORTED_MODULE_36__["default"]), -/* harmony export */ "blankNode": () => (/* binding */ blankNode), -/* harmony export */ "defaultGraph": () => (/* binding */ defaultGraph), -/* harmony export */ "fetcher": () => (/* binding */ fetcher), -/* harmony export */ "fromNT": () => (/* binding */ fromNT), -/* harmony export */ "graph": () => (/* binding */ graph), -/* harmony export */ "isBlankNode": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isBlankNode), -/* harmony export */ "isCollection": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isCollection), -/* harmony export */ "isGraph": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isGraph), -/* harmony export */ "isLiteral": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isLiteral), -/* harmony export */ "isNamedNode": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isNamedNode), -/* harmony export */ "isPredicate": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isPredicate), -/* harmony export */ "isQuad": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isQuad), -/* harmony export */ "isRDFObject": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isRDFObject), -/* harmony export */ "isRDFlibObject": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isRDFlibObject), -/* harmony export */ "isRDFlibPredicate": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isRDFlibPredicate), -/* harmony export */ "isRDFlibSubject": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isRDFlibSubject), -/* harmony export */ "isStatement": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isStatement), -/* harmony export */ "isStore": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isStore), -/* harmony export */ "isSubject": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isSubject), -/* harmony export */ "isTerm": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isTerm), -/* harmony export */ "isVariable": () => (/* reexport safe */ _utils_terms__WEBPACK_IMPORTED_MODULE_11__.isVariable), -/* harmony export */ "jsonParser": () => (/* reexport safe */ _jsonparser__WEBPACK_IMPORTED_MODULE_16__["default"]), -/* harmony export */ "lit": () => (/* binding */ lit), -/* harmony export */ "literal": () => (/* binding */ literal), -/* harmony export */ "log": () => (/* reexport safe */ _log__WEBPACK_IMPORTED_MODULE_18__["default"]), -/* harmony export */ "namedNode": () => (/* binding */ namedNode), -/* harmony export */ "parse": () => (/* reexport safe */ _parse__WEBPACK_IMPORTED_MODULE_22__["default"]), -/* harmony export */ "quad": () => (/* binding */ quad), -/* harmony export */ "queryToSPARQL": () => (/* reexport safe */ _query_to_sparql__WEBPACK_IMPORTED_MODULE_24__["default"]), -/* harmony export */ "serialize": () => (/* reexport safe */ _serialize__WEBPACK_IMPORTED_MODULE_27__["default"]), -/* harmony export */ "sparqlUpdateParser": () => (/* reexport safe */ _patch_parser__WEBPACK_IMPORTED_MODULE_30__["default"]), -/* harmony export */ "st": () => (/* binding */ st), -/* harmony export */ "sym": () => (/* binding */ namedNode), -/* harmony export */ "term": () => (/* binding */ term), -/* harmony export */ "termValue": () => (/* reexport safe */ _utils_termValue__WEBPACK_IMPORTED_MODULE_37__.termValue), -/* harmony export */ "triple": () => (/* binding */ triple), -/* harmony export */ "uri": () => (/* reexport module object */ _uri__WEBPACK_IMPORTED_MODULE_34__), -/* harmony export */ "variable": () => (/* binding */ variable) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./blank-node */ "../rdflib/esm/blank-node.js"); -/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./collection */ "../rdflib/esm/collection.js"); -/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./empty */ "../rdflib/esm/empty.js"); -/* harmony import */ var _fetcher__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./fetcher */ "../rdflib/esm/fetcher.js"); -/* harmony import */ var _formula__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./formula */ "../rdflib/esm/formula.js"); -/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./store */ "../rdflib/esm/store.js"); -/* harmony import */ var _jsonparser__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./jsonparser */ "../rdflib/esm/jsonparser.js"); -/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./literal */ "../rdflib/esm/literal.js"); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); -/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./n3parser */ "../rdflib/esm/n3parser.js"); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); -/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); -/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./node */ "../rdflib/esm/node.js"); -/* harmony import */ var _parse__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./parse */ "../rdflib/esm/parse.js"); -/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./query */ "../rdflib/esm/query.js"); -/* harmony import */ var _query_to_sparql__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./query-to-sparql */ "../rdflib/esm/query-to-sparql.js"); -/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./rdfaparser */ "../rdflib/esm/rdfaparser.js"); -/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./rdfxmlparser */ "../rdflib/esm/rdfxmlparser.js"); -/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./serialize */ "../rdflib/esm/serialize.js"); -/* harmony import */ var _serializer__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./serializer */ "../rdflib/esm/serializer.js"); -/* harmony import */ var _sparql_to_query__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./sparql-to-query */ "../rdflib/esm/sparql-to-query.js"); -/* harmony import */ var _patch_parser__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./patch-parser */ "../rdflib/esm/patch-parser.js"); -/* harmony import */ var _statement__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./statement */ "../rdflib/esm/statement.js"); -/* harmony import */ var _update_manager__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./update-manager */ "../rdflib/esm/update-manager.js"); -/* harmony import */ var _updates_via__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./updates-via */ "../rdflib/esm/updates-via.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); -/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./variable */ "../rdflib/esm/variable.js"); -/* harmony import */ var _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./factories/rdflib-data-factory */ "../rdflib/esm/factories/rdflib-data-factory.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); -/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./utils/termValue */ "../rdflib/esm/utils/termValue.js"); - - - - - - - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - - - - - - - - - - +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.creatorAndDate = creatorAndDate; +exports.creatorAndDateHorizontal = creatorAndDateHorizontal; +exports.elementForImageURI = elementForImageURI; +exports.renderMessageEditor = renderMessageEditor; +exports.renderMessageRow = renderMessageRow; +exports.switchToEditor = switchToEditor; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _infinite = __webpack_require__(/*! ./infinite */ "./lib/chat/infinite.js"); +var _messageTools = __webpack_require__(/*! ./messageTools */ "./lib/chat/messageTools.js"); +var _bookmarks = __webpack_require__(/*! ./bookmarks */ "./lib/chat/bookmarks.js"); +var _chatLogic = __webpack_require__(/*! ./chatLogic */ "./lib/chat/chatLogic.js"); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); +var _index = __webpack_require__(/*! ../media/index */ "./lib/media/index.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var pad = _interopRequireWildcard(__webpack_require__(/*! ../pad */ "./lib/pad.js")); +var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +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); } +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; } +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; } } }; } +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); } +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; } +var dom = window.document; +var messageBodyStyle = style.messageBodyStyle; +var label = utils.label; +/** + * HTML component for an image + */ +function elementForImageURI(imageUri, options) { + var img = dom.createElement('img'); + var height = '10'; + if (options.inlineImageHeightEms) { + height = ('' + options.inlineImageHeightEms).trim(); + } + img.setAttribute('style', 'max-height: ' + height + 'em; border-radius: 1em; margin: 0.7em;'); + // widgets.makeDropTarget(img, handleURIsDroppedOnMugshot, droppedFileHandler) + if (imageUri) img.setAttribute('src', imageUri); + var anchor = dom.createElement('a'); + anchor.setAttribute('href', imageUri); + anchor.setAttribute('target', 'images'); + anchor.appendChild(img); + widgets.makeDraggable(img, $rdf.sym(imageUri)); + return anchor; +} +var anchor = function anchor(text, term) { + // If there is no link return an element anyway + var a = dom.createElement('a'); + if (term && term.uri) { + a.setAttribute('href', term.uri); + a.addEventListener('click', widgets.openHrefInOutlineMode, true); + a.setAttribute('style', 'color: #3B5998; text-decoration: none; '); // font-weight: bold + } + a.textContent = text; + return a; +}; +function nick(person) { + var s = _solidLogic.store.any(person, ns.foaf('nick')); + if (s) return '' + s.value; + return '' + label(person); +} +/** + * Displays creator and date for a chat message + * inside the `td1` element + */ +function creatorAndDate(td1, creator, date, message) { + var nickAnchor = td1.appendChild(anchor(nick(creator), creator)); + if (creator.uri) { + _solidLogic.store.fetcher.nowOrWhenFetched(creator.doc(), undefined, function (_ok, _body) { + nickAnchor.textContent = nick(creator); + }); + } + td1.appendChild(dom.createElement('br')); + td1.appendChild(anchor(date, message)); +} +/** + * Horizontally displays creator and date for a chat message + * inside the `td1` element + */ +function creatorAndDateHorizontal(td1, creator, date, message) { + var nickAnchor = td1.appendChild(anchor(label(creator), creator)); + if (creator.uri) { + _solidLogic.store.fetcher.nowOrWhenFetched(creator.doc(), undefined, function (_ok, _body) { + nickAnchor.textContent = nick(creator); + }); + } + var dateBit = td1.appendChild(anchor(date, message)); + dateBit.style.fontSize = '80%'; + dateBit.style.marginLeft = '1em'; + td1.appendChild(dom.createElement('br')); +} +/** + * Renders a chat message, read-only mode + */ +function renderMessageRow(channelObject, message, fresh, options, userContext) { + var colorizeByAuthor = options.colorizeByAuthor === '1' || options.colorizeByAuthor === true; + var creator = _solidLogic.store.any(message, ns.foaf('maker')); + var date = _solidLogic.store.any(message, ns.dct('created')); + var latestVersion = (0, _chatLogic.mostRecentVersion)(message); + var content = _solidLogic.store.any(latestVersion, ns.sioc('content')); + var originalMessage = (0, _chatLogic.originalVersion)(message); + var edited = !message.sameTerm(originalMessage); + var sortDate = _solidLogic.store.the(originalMessage, ns.dct('created'), null, originalMessage.doc()); // In message + var messageRow = dom.createElement('tr'); + messageRow.AJAR_date = sortDate.value; + messageRow.AJAR_subject = message; + var td1 = dom.createElement('td'); + messageRow.appendChild(td1); + if (!options.authorDateOnLeft) { + var img = dom.createElement('img'); + img.setAttribute('style', 'max-height: 2.5em; max-width: 2.5em; border-radius: 0.5em; margin: auto;'); + widgets.setImage(img, creator); + td1.appendChild(img); + } else { + creatorAndDate(td1, creator, widgets.shortDate(sortDate.value), message); + } + var bothDates = widgets.shortDate(sortDate.value); + if (edited) { + bothDates += ' ... ' + widgets.shortDate(date.value); + } + // Render the content ot the message itself + var td2 = messageRow.appendChild(dom.createElement('td')); + if (!options.authorDateOnLeft) { + creatorAndDateHorizontal(td2, creator, bothDates, + // widgets.shortDate(dateString) + message); + } + var text = content.value.trim(); + var isURI = /^https?:\/[^ <>]*$/i.test(text); + var para = null; + if (isURI) { + var isImage = /\.(gif|jpg|jpeg|tiff|png|svg)$/i.test(text); // @@ Should use content-type not URI + if (isImage && options.expandImagesInline) { + var _img = elementForImageURI(text, options); + td2.appendChild(_img); + } else { + // Link but not Image + var anc = td2.appendChild(dom.createElement('a')); + para = anc.appendChild(dom.createElement('p')); + anc.href = text; + para.textContent = text; + td2.appendChild(anc); + } + } else { + // text + para = dom.createElement('p'); + td2.appendChild(para); + para.textContent = text; + } + if (para) { + var bgcolor = colorizeByAuthor ? pad.lightColorHash(creator) : getBgColor(fresh); + para.setAttribute('style', messageBodyStyle + 'background-color: ' + bgcolor + ';'); + } + function getBgColor(fresh) { + return fresh ? '#e8ffe8' : 'white'; + } + // Sentiment strip + var strip = (0, _messageTools.sentimentStripLinked)(message, message.doc()); + if (strip.children.length) { + td2.appendChild(dom.createElement('br')); + td2.appendChild(strip); + } + // Message tool bar button + var td3 = dom.createElement('td'); + messageRow.appendChild(td3); + var toolsButton = widgets.button(dom, _iconBase.icons.iconBase + 'noun_243787.svg', '...'); + td3.appendChild(toolsButton); + toolsButton.addEventListener('click', function (_event) { + if (messageRow.toolTR) { + // already got a toolbar? Toogle + messageRow.parentNode.removeChild(messageRow.toolTR); + delete messageRow.toolTR; + return; + } + var toolsTR = dom.createElement('tr'); + var tools = (0, _messageTools.messageToolbar)(message, messageRow, userContext, channelObject); + tools.style = 'border: 0.05em solid #888; border-radius: 0 0 0.7em 0.7em; border-top: 0; height:3.5em; background-color: #fff;'; // @@ fix + if (messageRow.nextSibling) { + messageRow.parentElement.insertBefore(toolsTR, messageRow.nextSibling); + } else { + messageRow.parentElement.appendChild(toolsTR); + } + messageRow.toolTR = toolsTR; + toolsTR.appendChild(dom.createElement('td')); // left + var toolsTD = toolsTR.appendChild(dom.createElement('td')); + toolsTR.appendChild(dom.createElement('td')); // right + toolsTD.appendChild(tools); + }); + return messageRow; +} +function switchToEditor(messageRow, message, channelObject, userContext) { + var messageTable = messageRow.parentNode; + var editRow = renderMessageEditor(channelObject, messageTable, userContext, channelObject.options, (0, _chatLogic.mostRecentVersion)(message)); + messageTable.insertBefore(editRow, messageRow); + editRow.originalRow = messageRow; + messageRow.style.visibility = 'hidden'; // Hide the original message. unhide if user cancels edit +} +/* Control for a new message -- or editing an old message *************** + * + */ +function renderMessageEditor(channelObject, messageTable, userContext, options, originalMessage) { + function revertEditing(messageEditor) { + messageEditor.originalRow.style.visibility = 'visible'; // restore read-only version + messageEditor.parentNode.removeChild(messageEditor); + } + function handleFieldInput(_x) { + return _handleFieldInput.apply(this, arguments); + } + function _handleFieldInput() { + _handleFieldInput = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(_event) { + return _regenerator["default"].wrap(function _callee5$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return sendMessage(field.value, true); + case 2: + case "end": + return _context6.stop(); + } + }, _callee5); + })); + return _handleFieldInput.apply(this, arguments); + } + function sendMessage(_x2, _x3) { + return _sendMessage.apply(this, arguments); + } // sendMessage + // DRAG AND DROP + function _sendMessage() { + _sendMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(text, fromMainField) { + var sendComplete, message, statusArea; + return _regenerator["default"].wrap(function _callee6$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + sendComplete = function _sendComplete(message, _text2) { + // const dateStamp = store.any(message, ns.dct('created'), null, message.doc()) + // const content = $rdf.literal(text2) + (0, _infinite.insertMessageIntoTable)(channelObject, messageTable, message, false, options, userContext); // not green + if (originalMessage) { + // editing another message + var oldRow = messageEditor.originalRow; + // oldRow.style.display = '' // restore read-only version, re-attack + if (oldRow.parentNode) { + oldRow.parentNode.removeChild(oldRow); // No longer needed old version + } else { + debug.warn('No parentNode on old message ' + oldRow.textContent); + oldRow.style.backgroundColor = '#fee'; + oldRow.style.visibility = 'hidden'; // @@ FIX THIS AND REMOVE FROM DOM INSTEAD + } + messageEditor.parentNode.removeChild(messageEditor); // no longer need editor + } else { + if (fromMainField) { + field.value = ''; // clear from out for reuse + field.setAttribute('style', messageBodyStyle); + field.disabled = false; + field.scrollIntoView(options.newestFirst); // allign bottom (top) + field.focus(); // Start typing next line immediately + field.select(); + } + } + // await channelObject.div.refresh() // Add new day if nec @@ add back + }; + // const me = authn.currentUser() // Must be logged on or wuld have got login button + if (fromMainField) { + field.setAttribute('style', messageBodyStyle + 'color: #bbb;'); // pendingedit + field.disabled = true; + } + _context7.prev = 2; + _context7.next = 5; + return channelObject.updateMessage(text, originalMessage); + case 5: + message = _context7.sent; + _context7.next = 13; + break; + case 8: + _context7.prev = 8; + _context7.t0 = _context7["catch"](2); + statusArea = userContext.statusArea || messageEditor; + statusArea.appendChild(widgets.errorMessageBlock(dom, 'Error writing message: ' + _context7.t0)); + return _context7.abrupt("return"); + case 13: + sendComplete(message, text); + case 14: + case "end": + return _context7.stop(); + } + }, _callee6, null, [[2, 8]]); + })); + return _sendMessage.apply(this, arguments); + } + function droppedFileHandler(files) { + var base = messageTable.chatDocument.dir().uri; + widgets.uploadFiles(_solidLogic.store.fetcher, files, base + 'Files', base + 'Pictures', /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(theFile, destURI) { + return _regenerator["default"].wrap(function _callee$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return sendMessage(destURI); + case 2: + case "end": + return _context2.stop(); + } + }, _callee); + })); + return function (_x4, _x5) { + return _ref.apply(this, arguments); + }; + }()); + } + // When a set of URIs are dropped on the field + var droppedURIHandler = /*#__PURE__*/function () { + var _ref2 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(uris) { + var _iterator, _step, uri; + return _regenerator["default"].wrap(function _callee2$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + _iterator = _createForOfIteratorHelper(uris); + _context3.prev = 1; + _iterator.s(); + case 3: + if ((_step = _iterator.n()).done) { + _context3.next = 9; + break; + } + uri = _step.value; + _context3.next = 7; + return sendMessage(uri); + case 7: + _context3.next = 3; + break; + case 9: + _context3.next = 14; + break; + case 11: + _context3.prev = 11; + _context3.t0 = _context3["catch"](1); + _iterator.e(_context3.t0); + case 14: + _context3.prev = 14; + _iterator.f(); + return _context3.finish(14); + case 17: + case "end": + return _context3.stop(); + } + }, _callee2, null, [[1, 11, 14, 17]]); + })); + return function droppedURIHandler(_x6) { + return _ref2.apply(this, arguments); + }; + }(); + // When we are actually logged on + function turnOnInput() { + function getImageDoc() { + imageDoc = $rdf.sym(chatDocument.dir().uri + 'Image_' + Date.now() + '.png'); + return imageDoc; + } + function tookPicture(_x7) { + return _tookPicture.apply(this, arguments); + } // Body of turnOnInput + function _tookPicture() { + _tookPicture = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(imageDoc) { + return _regenerator["default"].wrap(function _callee4$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (!imageDoc) { + _context5.next = 3; + break; + } + _context5.next = 3; + return sendMessage(imageDoc.uri); + case 3: + case "end": + return _context5.stop(); + } + }, _callee4); + })); + return _tookPicture.apply(this, arguments); + } + var menuButton; + if (options.menuHandler) { + var _menuButton = widgets.button(dom, _iconBase.icons.iconBase + 'noun_243787.svg', 'More'); + _menuButton.setAttribute('style', style.buttonStyle + 'float: right;'); + // menuButton.addEventListener('click', _event => sendMessage(), false) (done in turnoninput) + rhs.appendChild(_menuButton); + } + if (options.menuHandler && menuButton) { + var _me = _solidLogic.authn.currentUser(); + var menuOptions = { + me: _me, + dom: dom, + div: null, + // @@ was: div + newBase: messageTable.chatDocument.dir().uri + }; + menuButton.addEventListener('click', function (event) { + options.menuHandler(event, channelObject.chatChannel, menuOptions); + }, false); + } + var me = _solidLogic.authn.currentUser(); // If already logged on + creatorAndDate(lhs, me, '', null); + field = dom.createElement('textarea'); + middle.innerHTML = ''; + middle.appendChild(field); + field.rows = 3; + if (originalMessage) { + field.value = _solidLogic.store.anyValue(originalMessage, ns.sioc('content'), null, originalMessage.doc()); + } + // field.cols = 40 + field.setAttribute('style', messageBodyStyle + 'background-color: #eef;'); + // Trap the Enter BEFORE it is used ti make a newline + field.addEventListener('keydown', /*#__PURE__*/function () { + var _ref3 = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(e) { + return _regenerator["default"].wrap(function _callee3$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + if (!(e.code === 'Enter')) { + _context4.next = 4; + break; + } + if (!(!e.shiftKey && !options.shiftEnterSendsMessage || e.shiftKey && options.shiftEnterSendsMessage)) { + _context4.next = 4; + break; + } + _context4.next = 4; + return handleFieldInput(e); + case 4: + case "end": + return _context4.stop(); + } + }, _callee3); + })); + return function (_x8) { + return _ref3.apply(this, arguments); + }; + }(), false); + widgets.makeDropTarget(field, droppedURIHandler, droppedFileHandler); + rhs.innerHTML = ''; + sendButton = widgets.button(dom, sendIcon, 'Send'); + sendButton.style["float"] = 'right'; + sendButton.addEventListener('click', function (_event) { + return handleFieldInput(); + }, false); + rhs.appendChild(sendButton); + if (originalMessage) { + // Are we editing another message? + var cancelButton = rhs.appendChild(widgets.cancelButton(dom)); + cancelButton.style["float"] = 'left'; + // cancelButton.firstChild.style.opacity = '0.3' // moved to buttons + cancelButton.addEventListener('click', function (_event) { + return revertEditing(messageEditor); + }, false); + rhs.appendChild(cancelButton); + } + var chatDocument = channelObject.dateFolder.leafDocumentFromDate(new Date()); + var imageDoc; + middle.appendChild(_index.media.cameraButton(dom, _solidLogic.store, getImageDoc, tookPicture)); + pad.recordParticipation(channelObject.channel, channelObject.channel.doc()); // participation = + } // turn on inpuut + // Body of renderMessageEditor + var sortDate, sendIcon; + if (originalMessage) { + sortDate = _solidLogic.store.anyValue(originalMessage, ns.dct('created'), null, originalMessage.doc()); + // text = store.anyValue(originalMessage, ns.sioc('content'), null, originalMessage.doc()) + sendIcon = _iconBase.icons.iconBase + 'noun_1180158.svg'; // Green check + // cancelIcon = icons.iconBase + 'noun_1180156.svg' // Black cross + } else { + sendIcon = _iconBase.icons.iconBase + 'noun_383448.svg'; + sortDate = '9999-01-01T00:00:00Z'; // ISO format for field sort + // text = '' + } -// Prepare bound versions of data factory methods for export -var boundDataFactory = {}; -for (var name in _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"]) { - if (typeof _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"][name] === 'function') boundDataFactory[name] = _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"][name].bind(_factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_7__["default"]); -} -var fetcher = boundDataFactory.fetcher, - graph = boundDataFactory.graph, - lit = boundDataFactory.lit, - st = boundDataFactory.st, - namedNode = boundDataFactory.namedNode, - variable = boundDataFactory.variable, - blankNode = boundDataFactory.blankNode, - defaultGraph = boundDataFactory.defaultGraph, - literal = boundDataFactory.literal, - quad = boundDataFactory.quad, - triple = boundDataFactory.triple; -var formula = new _formula__WEBPACK_IMPORTED_MODULE_8__["default"](); -var fromNT = function fromNT(str) { - return formula.fromNT(str); -}; -var term = _node__WEBPACK_IMPORTED_MODULE_9__["default"].fromValue; + var messageEditor = dom.createElement('tr'); + var lhs = dom.createElement('td'); + var middle = dom.createElement('td'); + var rhs = dom.createElement('td'); + messageEditor.appendChild(lhs); + messageEditor.appendChild(middle); + messageEditor.appendChild(rhs); + messageEditor.AJAR_date = sortDate; + // messageEditor.appendChild(dom.createElement('br')) -// TODO: this export is broken; -// it exports the _current_ value of nextId, which is always 0 -var NextId = _blank_node__WEBPACK_IMPORTED_MODULE_10__["default"].nextId; + var field, sendButton; + var context = { + div: middle, + dom: dom + }; + (0, _login.ensureLoggedIn)(context).then(function (context) { + // me = context.me + turnOnInput(); + Object.assign(context, userContext); + (0, _bookmarks.findBookmarkDocument)(context).then(function (_context) { + // console.log('Bookmark file: ' + context.bookmarkDocument) + }); + }); + return messageEditor; +} // renderMessageEditor +//# sourceMappingURL=message.js.map +/***/ }), +/***/ "./lib/chat/messageTools.js": +/*!**********************************!*\ + !*** ./lib/chat/messageTools.js ***! + \**********************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -var ConnectedStore = /*#__PURE__*/function (_Store) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(ConnectedStore, _Store); - var _super = _createSuper(ConnectedStore); - function ConnectedStore(features) { - var _this; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, ConnectedStore); - _this = _super.call(this, features); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "fetcher", void 0); - _this.fetcher = new _fetcher__WEBPACK_IMPORTED_MODULE_14__["default"]((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), {}); - return _this; - } - return (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__["default"])(ConnectedStore); -}(_store__WEBPACK_IMPORTED_MODULE_15__["default"]); -var LiveStore = /*#__PURE__*/function (_ConnectedStore) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(LiveStore, _ConnectedStore); - var _super2 = _createSuper(LiveStore); - function LiveStore(features) { - var _this2; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, LiveStore); - _this2 = _super2.call(this, features); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this2), "updater", void 0); - _this2.updater = new _update_manager__WEBPACK_IMPORTED_MODULE_32__["default"]((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this2)); - return _this2; - } - return (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__["default"])(LiveStore); -}(ConnectedStore); +"use strict"; -/***/ }), -/***/ "../rdflib/esm/jsonldparser.js": -/*!*************************************!*\ - !*** ../rdflib/esm/jsonldparser.js ***! - \*************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.messageToolbar = messageToolbar; +exports.sentimentStrip = sentimentStrip; +exports.sentimentStripLinked = sentimentStripLinked; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _slicedToArray2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "./node_modules/@babel/runtime/helpers/slicedToArray.js")); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +var _bookmarks = __webpack_require__(/*! ./bookmarks */ "./lib/chat/bookmarks.js"); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var _chatLogic = __webpack_require__(/*! ./chatLogic */ "./lib/chat/chatLogic.js"); +var _message = __webpack_require__(/*! ./message */ "./lib/chat/message.js"); +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); } +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; } +/** + * Tools for doing things with a message + * Let us be creative here. Allow all sorts of things to + * be done to a message - linking to new or old objects in an open way + * + * Ideas: Bookmark, Like, star, pin at top of chat, reply as new thread, + * If you made it originally: edit, delete, attach + * @packageDocumentation + */ -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ jsonldParser), -/* harmony export */ "jsonldObjectToTerm": () => (/* binding */ jsonldObjectToTerm) -/* harmony export */ }); -/* harmony import */ var jsonld__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jsonld */ "../rdflib/node_modules/jsonld/lib/jsonld.js"); -/* harmony import */ var jsonld__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jsonld__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils */ "../rdflib/esm/utils.js"); +// import { media } from '../media/index' +// import * as pad from '../pad' +// pull in first avoid cross-refs +// import * as style from '../style' +var dom = window.document; +// THE UNUSED ICONS are here as reminders for possible future functionality +// const BOOKMARK_ICON = 'noun_45961.svg' +// const HEART_ICON = 'noun_130259.svg' -> Add this to my (private) favorites +// const MENU_ICON = 'noun_897914.svg' +// const PAPERCLIP_ICON = 'noun_25830.svg' -> add attachments to this message +// const PIN_ICON = 'noun_562340.svg' -> pin this message permanently in the chat UI +var PENCIL_ICON = 'noun_253504.svg'; // edit a message +// const SPANNER_ICON = 'noun_344563.svg' -> settings +var THUMBS_UP_ICON = 'noun_1384132.svg'; +var THUMBS_DOWN_ICON = 'noun_1384135.svg'; /** - * Parses json-ld formatted JS objects to a rdf Term. - * @param kb - The DataFactory to use. - * @param obj - The json-ld object to process. - * @return {Literal|NamedNode|BlankNode|Collection} + * Emoji in Unicode */ -function jsonldObjectToTerm(kb, obj) { - if (typeof obj === 'string') { - return kb.rdfFactory.literal(obj); - } - if (Object.prototype.hasOwnProperty.call(obj, '@list')) { - if (kb.rdfFactory.supports["COLLECTIONS"] === true) { - return listToCollection(kb, obj['@list']); - } - return listToStatements(kb, obj); - } - if (Object.prototype.hasOwnProperty.call(obj, '@id')) { - return nodeType(kb, obj); - } - if (Object.prototype.hasOwnProperty.call(obj, '@language')) { - return kb.rdfFactory.literal(obj['@value'], obj['@language']); - } - if (Object.prototype.hasOwnProperty.call(obj, '@type')) { - return kb.rdfFactory.literal(obj['@value'], kb.rdfFactory.namedNode(obj['@type'])); - } - if (Object.prototype.hasOwnProperty.call(obj, '@value')) { - return kb.rdfFactory.literal(obj['@value']); - } - return kb.rdfFactory.literal(obj); -} +var emoji = {}; +emoji[ns.schema('AgreeAction')] = '👍'; +emoji[ns.schema('DisagreeAction')] = '👎'; +emoji[ns.schema('EndorseAction')] = '⭐️'; +emoji[ns.schema('LikeAction')] = '❤️'; /** - * Adds the statements in a json-ld list object to {kb}. + * Create strip of sentiments expressed */ -function listToStatements(kb, obj) { - var listId = obj['@id'] ? nodeType(kb, obj) : kb.rdfFactory.blankNode(); - var items = obj['@list'].map(function (listItem) { - return jsonldObjectToTerm(kb, listItem); +function sentimentStrip(target, doc) { + // alain seems not used + var latest = (0, _chatLogic.mostRecentVersion)(target); + var actions = _solidLogic.store.holds(latest, ns.schema('dateDeleted').value, null, latest.doc()) ? _solidLogic.store.each(null, ns.schema('target'), target, doc) : []; + var sentiments = actions.map(function (a) { + return _solidLogic.store.any(a, ns.rdf('type'), null, doc); }); - var statements = (0,_utils__WEBPACK_IMPORTED_MODULE_1__.arrayToStatements)(kb.rdfFactory, listId, items); - kb.addAll(statements); - return listId; + sentiments.sort(); + var strings = sentiments.map(function (x) { + return emoji[x] || ''; + }); + return dom.createTextNode(strings.join(' ')); } -function listToCollection(kb, obj) { - if (!Array.isArray(obj)) { - throw new TypeError("Object must be an array"); - } - return kb.rdfFactory.collection(obj.map(function (o) { - return jsonldObjectToTerm(kb, o); - })); -} - /** - * Takes a json-ld formatted string {str} and adds its statements to {kb}. + * Create strip of sentiments expressed, with hyperlinks * - * Ensure that {kb.rdfFactory} is a DataFactory. + * @param target {NamedNode} - The thing about which they are expressed + * @param doc {NamedNode} - The document in which they are expressed */ -function jsonldParser(str, kb, base, callback) { - var baseString = base && Object.prototype.hasOwnProperty.call(base, 'termType') ? base.value : base; - return jsonld__WEBPACK_IMPORTED_MODULE_0___default().flatten(JSON.parse(str), null, { - base: baseString - }).then(function (flattened) { - return flattened.reduce(function (store, flatResource) { - kb = processResource(kb, base, flatResource); - return kb; - }, kb); - }).then(callback).catch(callback); -} -function nodeType(kb, obj) { - if (obj['@id'].startsWith('_:')) { - // This object is a Blank Node. Pass the id without the `_:` prefix - return kb.rdfFactory.blankNode(obj['@id'].substring(2)); - } else { - // This object is a Named Node - return kb.rdfFactory.namedNode(obj['@id']); - } -} -function processResource(kb, base, flatResource) { - var id = flatResource['@id'] ? nodeType(kb, flatResource) : kb.rdfFactory.blankNode(); - for (var _i = 0, _Object$keys = Object.keys(flatResource); _i < _Object$keys.length; _i++) { - var property = _Object$keys[_i]; - if (property === '@id') { - continue; - } else if (property == '@graph') { - // the JSON-LD flattened structure may contain nested graphs - // the id value for this object is the new base (named graph id) for all nested flat resources - var graphId = id; - // this is an array of resources - var nestedFlatResources = flatResource[property]; - - // recursively process all flat resources in the array, but with the graphId as base. - for (var i = 0; i < nestedFlatResources.length; i++) { - kb = processResource(kb, graphId, nestedFlatResources[i]); - } - } - var value = flatResource[property]; - if (Array.isArray(value)) { - for (var _i2 = 0; _i2 < value.length; _i2++) { - kb.addStatement(createStatement(kb, id, property, value[_i2], base)); +function sentimentStripLinked(target, doc) { + var strip = dom.createElement('span'); + function refresh() { + strip.innerHTML = ''; + var actions = (0, _chatLogic.mostRecentVersion)(target).uri !== ns.schema('dateDeleted').uri ? _solidLogic.store.each(null, ns.schema('target'), target, doc) : []; + var sentiments = actions.map(function (a) { + return [_solidLogic.store.any(a, ns.rdf('type'), null, doc), _solidLogic.store.any(a, ns.schema('agent'), null, doc)]; + }); + sentiments.sort(); + sentiments.forEach(function (ss) { + var _ss = (0, _slicedToArray2["default"])(ss, 2), + theClass = _ss[0], + agent = _ss[1]; + var res; + if (agent) { + res = dom.createElement('a'); + res.setAttribute('href', agent.uri); + } else { + res = dom.createTextNode(''); } - } else { - kb.addStatement(createStatement(kb, id, property, value, base)); - } + res.textContent = emoji[theClass] || '*'; + strip.appendChild(res); + }); } - return kb; + refresh(); + strip.refresh = refresh; + return strip; } - /** - * Create statement quad depending on @type being a type node - * @param kb - * @param subject id - * @param property - * @param value - * @return quad statement + * Creates a message toolbar component */ -function createStatement(kb, id, property, value, base) { - var predicate, object; - if (property === "@type") { - predicate = kb.rdfFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); - object = kb.rdfFactory.namedNode(value); - } else { - predicate = kb.rdfFactory.namedNode(property); - object = jsonldObjectToTerm(kb, value); +function messageToolbar(message, messageRow, userContext, channelObject) { + function deleteMessage() { + return _deleteMessage.apply(this, arguments); } - return kb.rdfFactory.quad(id, predicate, object, kb.rdfFactory.namedNode(base)); -} - -/***/ }), + function _deleteMessage() { + _deleteMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var author, msg, area; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + author = _solidLogic.store.any(message, ns.foaf('maker')); + if (me) { + _context2.next = 5; + break; + } + alert('You can\'t delete the message, you are not logged in.'); + _context2.next = 22; + break; + case 5: + if (!me.sameTerm(author)) { + _context2.next = 21; + break; + } + _context2.prev = 6; + _context2.next = 9; + return channelObject.deleteMessage(message); + case 9: + _context2.next = 18; + break; + case 11: + _context2.prev = 11; + _context2.t0 = _context2["catch"](6); + msg = 'Error deleting messaage ' + _context2.t0; + debug.warn(msg); + alert(msg); + area = userContext.statusArea || messageRow.parentNode; + area.appendChild(widgets.errorMessageBlock(dom, msg)); + case 18: + messageRow.parentNode.removeChild(messageRow); + _context2.next = 22; + break; + case 21: + alert('You can\'t delete the message, you are not logged in as the author, ' + author); + case 22: + closeToolbar(); + case 23: + case "end": + return _context2.stop(); + } + }, _callee2, null, [[6, 11]]); + })); + return _deleteMessage.apply(this, arguments); + } + function editMessage(_x) { + return _editMessage.apply(this, arguments); + } // alain TODO allow chat owner to fully delete message + sentiments and replacing messages + function _editMessage() { + _editMessage = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(messageRow) { + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + if (me.value === _solidLogic.store.any(message, ns.foaf('maker')).value) { + closeToolbar(); // edit is a one-off action + (0, _message.switchToEditor)(messageRow, message, channelObject, userContext); + } + case 1: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _editMessage.apply(this, arguments); + } + var div = dom.createElement('div'); + // is message deleted ? + if ((0, _chatLogic.mostRecentVersion)(message).value === ns.schema('dateDeleted').value) return div; + function closeToolbar() { + div.parentElement.parentElement.removeChild(div.parentElement); // remive the TR + } + function deleteThingThen(_x2) { + return _deleteThingThen.apply(this, arguments); + } // Things only the original author can do + function _deleteThingThen() { + _deleteThingThen = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(x) { + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return _solidLogic.store.updater.update(_solidLogic.store.connectedStatements(x), []); + case 2: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _deleteThingThen.apply(this, arguments); + } + var me = _solidLogic.authn.currentUser(); // If already logged on + if (me && _solidLogic.store.holds(message, ns.foaf('maker'), me)) { + // button to delete the message + div.appendChild(widgets.deleteButtonWithCheck(dom, div, 'message', deleteMessage)); + // button to edit the message + div.appendChild(widgets.button(dom, _iconBase.icons.iconBase + PENCIL_ICON, 'edit', function () { + return editMessage(messageRow); + })); + } // if mine + // Things anyone can do if they have a bookmark list async + /* + var bookmarkButton = await bookmarks.renderBookmarksButton(userContext) + if (bookmarkButton) { + div.appendChild(bookmarkButton) + } + */ + // Things anyone can do if they have a bookmark list -/***/ "../rdflib/esm/jsonparser.js": -/*!***********************************!*\ - !*** ../rdflib/esm/jsonparser.js ***! - \***********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + (0, _bookmarks.renderBookmarksButton)(userContext).then(function (bookmarkButton) { + if (bookmarkButton) div.appendChild(bookmarkButton); + }); -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ((function () { - return { - parseJSON: function parseJSON(data, source, store) { - var subject, predicate, object; - var bnodes = {}; - var why = store.sym(source); - for (var x in data) { - if (x.indexOf('_:') === 0) { - if (bnodes[x]) { - subject = bnodes[x]; - } else { - subject = store.bnode(x); - bnodes[x] = subject; - } - } else { - subject = store.sym(x); - } - var preds = data[x]; - for (var y in preds) { - var objects = preds[y]; - predicate = store.sym(y); - for (var z in objects) { - var obj = objects[z]; - if (obj.type === 'uri') { - object = store.sym(obj.value); - store.add(subject, predicate, object, why); - } else if (obj.type === 'BlankNode') { - if (bnodes[obj.value]) { - object = bnodes[obj.value]; - } else { - object = store.bnode(obj.value); - bnodes[obj.value] = object; + /** Button to allow user to express a sentiment (like, endorse, etc) about a target + * + * @param context {Object} - Provide dom and me + * @param target {NamedNode} - The thing the user expresses an opnion about + * @param icon {uristring} - The icon to be used for the button + * @param actionClass {NamedNode} - The RDF class - typically a subclass of schema:Action + * @param doc - {NamedNode} - the Solid document iunto which the data should be written + * @param mutuallyExclusive {Array} - Any RDF classes of sentimentswhich are mutiually exclusive + */ + function sentimentButton(context, target, icon, actionClass, doc, mutuallyExclusive) { + function setColor() { + button.style.backgroundColor = action ? 'yellow' : 'white'; + } + var button = widgets.button(dom, icon, utils.label(actionClass), /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(_event) { + var insertMe, dirty, i, a; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!action) { + _context.next = 7; + break; } - store.add(subject, predicate, object, why); - } else if (obj.type === 'Literal') { - // var datatype - if (obj.datatype) { - object = store.literal(obj.value, undefined, store.sym(obj.datatype)); - } else if (obj.lang) { - object = store.literal(obj.value, obj.lang); - } else { - object = store.literal(obj.value); + _context.next = 3; + return deleteThingThen(action); + case 3: + action = null; + setColor(); + _context.next = 25; + break; + case 7: + // no action + action = widgets.newThing(doc); + insertMe = [rdf.st(action, ns.schema('agent'), context.me, doc), rdf.st(action, ns.rdf('type'), actionClass, doc), rdf.st(action, ns.schema('target'), target, doc)]; + _context.next = 11; + return _solidLogic.store.updater.update([], insertMe); + case 11: + setColor(); + if (!mutuallyExclusive) { + _context.next = 25; + break; } - store.add(subject, predicate, object, why); - } else { - throw new Error('error: unexpected termtype: ' + z.type); - } + // Delete incompative sentiments + dirty = false; + i = 0; + case 15: + if (!(i < mutuallyExclusive.length)) { + _context.next = 24; + break; + } + a = existingAction(mutuallyExclusive[i]); + if (!a) { + _context.next = 21; + break; + } + _context.next = 20; + return deleteThingThen(a); + case 20: + // but how refresh? refreshTree the parent? + dirty = true; + case 21: + i++; + _context.next = 15; + break; + case 24: + if (dirty) { + // widgets.refreshTree(button.parentNode) // requires them all to be immediate siblings + widgets.refreshTree(messageRow); // requires them all to be immediate siblings + } + case 25: + case "end": + return _context.stop(); } - } - } + }, _callee); + })); + return function (_x3) { + return _ref.apply(this, arguments); + }; + }()); + function existingAction(actionClass) { + var actions = _solidLogic.store.each(null, ns.schema('agent'), context.me, doc).filter(function (x) { + return _solidLogic.store.holds(x, ns.rdf('type'), actionClass, doc); + }).filter(function (x) { + return _solidLogic.store.holds(x, ns.schema('target'), target, doc); + }); + return actions.length ? actions[0] : null; } - }; -})()); + function refresh() { + action = existingAction(actionClass); + setColor(); + } + var action; + button.refresh = refresh; // If the file changes, refresh live + refresh(); + return button; + } + + // THUMBS_UP_ICON + // https://schema.org/AgreeAction + me = _solidLogic.authn.currentUser(); // If already logged on + // debug.log('Actions 3' + mostRecentVersion(message).value + ' ' + ns.schema('dateDeleted').value + ' ' + (mostRecentVersion(message).value !== ns.schema('dateDeleted').value)) + + if (me && (0, _chatLogic.mostRecentVersion)(message).value !== ns.schema('dateDeleted').value) { + var context1 = { + me: me, + dom: dom, + div: div + }; + div.appendChild(sentimentButton(context1, message, + // @@ TODO use widgets.sentimentButton + _iconBase.icons.iconBase + THUMBS_UP_ICON, ns.schema('AgreeAction'), message.doc(), [ns.schema('DisagreeAction')])); + // Thumbs down + div.appendChild(sentimentButton(context1, message, _iconBase.icons.iconBase + THUMBS_DOWN_ICON, ns.schema('DisagreeAction'), message.doc(), [ns.schema('AgreeAction')])); + } + // X button to remove the tool UI itself + var cancelButton = div.appendChild(widgets.cancelButton(dom)); + cancelButton.style["float"] = 'right'; + cancelButton.firstChild.style.opacity = '0.3'; + cancelButton.addEventListener('click', closeToolbar); + return div; +} +//# sourceMappingURL=messageTools.js.map /***/ }), -/***/ "../rdflib/esm/lists.js": +/***/ "./lib/create/create.js": /*!******************************!*\ - !*** ../rdflib/esm/lists.js ***! + !*** ./lib/create/create.js ***! \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "convertFirstRestNil": () => (/* binding */ convertFirstRestNil), -/* harmony export */ "substituteInDoc": () => (/* binding */ substituteInDoc), -/* harmony export */ "substituteNillsInDoc": () => (/* binding */ substituteNillsInDoc) -/* harmony export */ }); -/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./collection */ "../rdflib/esm/collection.js"); -/* harmony import */ var _statement__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./statement */ "../rdflib/esm/statement.js"); -/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); -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; } } }; } -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); } -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; } -/* Lists form conversion -*/ -// import DataFactory from './factories/extended-term-factory' -// import jsonldParser from './jsonldparser' -// @ts-ignore is this injected? -// @@ Goal: remove this dependency -// import N3Parser from './n3parser' -// import { parseRDFaDOM } from './rdfaparser' -// import RDFParser from './rdfxmlparser' -// import sparqlUpdateParser from './patch-parser' -// import * as Util from './utils-js' - -// import BlankNode from './blank-node' -// import NamedNode from './named-node' - - -// import Formula from './formula' +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.newThingUI = newThingUI; +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); +var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +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); } +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; } +/* create.js UI to craete new objects in the solid-app-set world + ** + */ -var RDF = (0,_namespace__WEBPACK_IMPORTED_MODULE_0__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#'); +var kb = _solidLogic.solidLogicSingleton.store; -/* Replace a given node with another node throughout a given document -* -* we do the predicate as well for complenesss though we don't expect Collections to use it -*/ -function substituteInDoc(store, x, y, doc) { - // console.log(`substituteInDoc put ${x} for ${y} in ${doc}}`) - var _iterator = _createForOfIteratorHelper(store.statementsMatching(y, null, null, doc)), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var quad = _step.value; - var newStatement = new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](x, quad.predicate, quad.object, doc); - store.remove(quad); - store.add(newStatement); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - var _iterator2 = _createForOfIteratorHelper(store.statementsMatching(null, y, null, doc)), - _step2; - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var _quad = _step2.value; - store.remove(_quad); - // console.log(` substituteInDoc predicate ${x} in ${quad}}`) - store.add(new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](_quad.subject, x, _quad.object, doc)); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); +/* newThingUI -- return UI for user to select a new object, folder, etc + ** + ** context must include: dom, div, + ** optional: folder: NamedNode -- the folder where the thing is bring put + ** (suppresses asking for a full URI or workspace) + ** + */ +function newThingUI(createContext, dataBrowserContext, thePanes) { + var dom = createContext.dom; + var div = createContext.div; + if (createContext.me && !createContext.me.uri) { + throw new Error('newThingUI: Invalid userid: ' + createContext.me); } - var _iterator3 = _createForOfIteratorHelper(store.statementsMatching(null, null, y, doc)), - _step3; - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var _quad2 = _step3.value; - store.remove(_quad2); - store.add(new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](_quad2.subject, _quad2.predicate, x, doc)); + var iconStyle = 'padding: 0.7em; width: 2em; height: 2em;'; // was: 'padding: 1em; width: 3em; height: 3em;' + var star = div.appendChild(dom.createElement('img')); + var visible = false; // the inividual tools tools + // noun_272948.svg = black star + // noun_34653_green.svg = green plus + star.setAttribute('src', _iconBase.icons.iconBase + 'noun_34653_green.svg'); + star.setAttribute('style', iconStyle); + star.setAttribute('title', 'Add another tool'); + var complain = function complain(message) { + var pre = div.appendChild(dom.createElement('pre')); + pre.setAttribute('style', 'background-color: pink'); + pre.appendChild(dom.createTextNode(message)); + }; + function styleTheIcons(style) { + for (var i = 0; i < iconArray.length; i++) { + var st = iconStyle + style; + if (iconArray[i].disabled) { + // @@ unused + st += 'opacity: 0.3;'; + } + iconArray[i].setAttribute('style', st); // eg 'background-color: #ccc;' } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); } -} -/* Change all lone rdf:nil nodes into empty Collections -*/ -function substituteNillsInDoc(store, doc) { - var x = RDF('nil'); - var _iterator4 = _createForOfIteratorHelper(store.statementsMatching(x, null, null, doc)), - _step4; - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var quad = _step4.value; - store.remove(quad); - var y = new _collection__WEBPACK_IMPORTED_MODULE_2__["default"](); - store.add(new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](y, quad.predicate, quad.object, doc)); - } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); + function selectTool(icon) { + styleTheIcons('display: none;'); // 'background-color: #ccc;' + icon.setAttribute('style', iconStyle + 'background-color: yellow;'); } - var _iterator5 = _createForOfIteratorHelper(store.statementsMatching(null, null, x, doc)), - _step5; - try { - for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { - var _quad3 = _step5.value; - if (!_quad3.predicate.sameTerm(RDF('rest'))) { - // If not a tail - store.remove(_quad3); - var _y = new _collection__WEBPACK_IMPORTED_MODULE_2__["default"](); - store.add(new _statement__WEBPACK_IMPORTED_MODULE_1__["default"](_quad3.subject, _quad3.predicate, _y, doc)); + function selectNewTool(_event) { + visible = !visible; + star.setAttribute('style', iconStyle + (visible ? 'background-color: yellow;' : '')); + styleTheIcons(visible ? '' : 'display: none;'); + } + star.addEventListener('click', selectNewTool); + function makeNewAppInstance(options) { + return new Promise(function (resolve, reject) { + var selectUI; // , selectUIParent + function callbackWS(ws, newBase) { + (0, _login.ensureLoadedProfile)(createContext).then(function (_context) { + var newPaneOptions = Object.assign({ + newBase: newBase, + folder: options.folder || undefined, + workspace: ws + }, options); + for (var opt in options) { + // get div, dom, me, folder, pane, refreshTable + newPaneOptions[opt] = options[opt]; + } + debug.log("newThingUI: Minting new ".concat(newPaneOptions.pane.name, " at ").concat(newPaneOptions.newBase)); + options.pane.mintNew(dataBrowserContext, newPaneOptions).then(function (newPaneOptions) { + if (!newPaneOptions || !newPaneOptions.newInstance) { + throw new Error('Cannot mint new - missing newInstance'); + } + if (newPaneOptions.folder) { + var tail = newPaneOptions.newInstance.uri.slice(newPaneOptions.folder.uri.length); + var isPackage = tail.includes('/'); + debug.log(' new thing is packge? ' + isPackage); + if (isPackage) { + kb.add(newPaneOptions.folder, ns.ldp('contains'), kb.sym(newPaneOptions.newBase), newPaneOptions.folder.doc()); + } else { + // single file + kb.add(newPaneOptions.folder, ns.ldp('contains'), newPaneOptions.newInstance, newPaneOptions.folder.doc()); // Ping the patch system? + } + // @ts-ignore @@ TODO check whether refresh can exist here. Either fix type or remove unreachable code + if (newPaneOptions.refreshTarget && newPaneOptions.refreshTarget.refresh) { + // @@ TODO Remove the need to cast as any + ; + newPaneOptions.refreshTarget.refresh(); // Refresh the containing display + } + // selectUI.parentNode.removeChild(selectUI) It removes itself + } else { + var p = options.div.appendChild(dom.createElement('p')); + p.setAttribute('style', 'font-size: 120%;'); + // Make link to new thing + p.innerHTML = "Your new " + options.noun + ' is ready to be set up. ' + "

Go to your new " + options.noun + '.'; + // selectUI.parentNode.removeChild(selectUI) // Clean up + // selectUIParent.removeChild(selectUI) // Clean up + } + + selectNewTool(); // toggle star to plain and menu vanish again + })["catch"](function (err) { + complain(err); + reject(err); + }); + }, function (err) { + // login fails + complain('Error logging on: ' + err); + }); + } // callbackWS + + var pa = options.pane; + // options.appPathSegment = pa.name // was 'edu.mit.solid.pane.' + options.noun = pa.mintClass ? utils.label(pa.mintClass) : pa.name; + options.appPathSegment = options.noun.slice(0, 1).toUpperCase() + options.noun.slice(1); + if (!options.folder) { + // No folder given? Ask user for full URI + selectUI = (0, _login.selectWorkspace)(dom, { + noun: options.noun, + appPathSegment: options.appPathSegment + }, callbackWS); + options.div.appendChild(selectUI); + // selectUIParent = options.div + } else { + var gotName = function gotName(name) { + if (!name) { + // selectUIParent.removeChild(selectUI) itremves itself if cancelled + selectNewTool(); // toggle star to plain and menu vanish again + } else { + var uri = options.folder.uri; + if (!uri.endsWith('/')) { + uri = uri + '/'; + } + uri = uri + encodeURIComponent(name) + '/'; + callbackWS(null, uri); + } + }; + widgets.askName(dom, kb, options.div, ns.foaf('name'), null, options.noun).then(gotName); + // selectUI = getNameForm(dom, kb, options.noun, gotName) + // options.div.appendChild(selectUI) + // selectUIParent = options.div } + }); + } // makeNewAppInstance + + var iconArray = []; + var mintingPanes = Object.values(thePanes).filter(function (pane) { + return pane.mintNew; + }); + var mintingClassMap = mintingPanes.reduce(function (classMap, pane) { + if (pane.mintClass) { + classMap[pane.mintClass.uri] = (classMap[pane.mintClass.uri] || 0) + 1; } - } catch (err) { - _iterator5.e(err); - } finally { - _iterator5.f(); - } + return classMap; + }, {}); + mintingPanes.forEach(function (pane) { + // @@ TODO Remove the need to cast to any + var icon = createContext.div.appendChild(dom.createElement('img')); + icon.setAttribute('src', pane.icon); + var noun = pane.mintClass ? mintingClassMap[pane.mintClass.uri] > 1 ? "".concat(utils.label(pane.mintClass), " (using ").concat(pane.name, " pane)") : utils.label(pane.mintClass) : pane.name + ' @@'; + icon.setAttribute('title', 'Make new ' + noun); + icon.setAttribute('style', iconStyle + 'display: none;'); + iconArray.push(icon); + if (!icon.disabled) { + icon.addEventListener('click', function (e) { + selectTool(icon); + makeNewAppInstance({ + event: e, + folder: createContext.folder || null, + iconEle: icon, + pane: pane, + noun: noun, + noIndexHTML: true, + // do NOT @@ for now write a HTML file + div: createContext.div, + me: createContext.me, + dom: createContext.dom, + refreshTarget: createContext.refreshTarget + }); + }); + } + }); } -/** - * Convert lists reified as rdf:first, rest - * Normal method is sync. - * Unfortunately jsdonld is currently written to need to be called async. - * Hence the mess below with executeCallback. - * @param store - The quadstore - * @param doc - The document in which the conversion is done - */ -function convertFirstRestNil(store, doc // Do whole store? -) { - function preceding(ele, listSoFar, trash) { - var rests = store.statementsMatching(ele, RDF('rest'), null, doc); - if (rests.length !== 1) throw new Error("Bad list structure: no rest at ".concat(ele)); - var firsts = store.statementsMatching(ele, RDF('first'), null, doc); - if (firsts.length !== 1) throw new Error("Bad list structure: rest but ".concat(firsts.length, " firsts at ").concat(ele)); - var value = firsts[0].object; - var total = [value].concat(listSoFar); - // console.log(' List now is: ', total) - var totalTrash = trash.concat(rests).concat(firsts); - var pres = store.statementsMatching(null, RDF('rest'), ele, doc); - if (pres.length === 0) { - // Head of the list - var newList = new _collection__WEBPACK_IMPORTED_MODULE_2__["default"](total); - store.remove(totalTrash); - // Replace old list with new list: - substituteInDoc(store, newList, ele, doc); - return; - } - if (pres.length !== 1) throw new Error("Bad list structure: ".concat(pres.length, " pres at ").concat(ele)); - var pre = pres[0].subject; - if (pre.termType !== 'BlankNode') throw new Error("Bad list element node ".concat(pre, " type: ").concat(pre.termType, " ")); - preceding(pre, total, totalTrash); - return; +// Form to get the name of a new thing before we create it +// +// Used in contacts for new groups, individuals. +// +/* +function getNameForm (dom, kb, classLabel, gotNameCallback) { + const form = dom.createElement('div') // form is broken as HTML behaviour can resurface on js error + form.innerHTML = '

Name of new ' + classLabel + ':

' + const namefield = dom.createElement('input') + namefield.setAttribute('type', 'text') + namefield.setAttribute('size', '30') + namefield.setAttribute('style', style.textInputStyle) + namefield.setAttribute('maxLength', '2048') // No arbitrary limits + namefield.select() // focus next user input + + const gotName = function () { + namefield.setAttribute('class', 'pendingedit') + namefield.disabled = true + continueButton.disabled = true + cancel.disabled = true + gotNameCallback(true, namefield.value) } - substituteNillsInDoc(store, doc); // lone ones only - var tails = store.statementsMatching(null, RDF('rest'), RDF('nil'), doc); - tails.forEach(function (tail) { - if (tail.subject.termType !== 'BlankNode') throw new Error("Bad list element node ".concat(tail.subject, " type: ").concat(tail.subject.termType, " ")); - preceding(tail.subject, [], []); - }); + namefield.addEventListener('keyup', function (e) { + if (e.keyCode === 13) { + gotName() + } + }, false) + form.appendChild(namefield) + + form.appendChild(dom.createElement('br')) + + const cancel = form.appendChild(widgets.cancelButton(dom)) + cancel.addEventListener('click', function (e) { + form.parentNode.removeChild(form) + gotNameCallback(false) + }, false) + + const continueButton = form.appendChild(widgets.continueButton(dom)) + continueButton.addEventListener('click', function (e) { + gotName() + }, false) + + return form } +*/ +//# sourceMappingURL=create.js.map /***/ }), -/***/ "../rdflib/esm/literal.js": -/*!********************************!*\ - !*** ../rdflib/esm/literal.js ***! - \********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./lib/create/index.js": +/*!*****************************!*\ + !*** ./lib/create/index.js ***! + \*****************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Literal) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../rdflib/node_modules/@babel/runtime/helpers/esm/typeof.js"); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); -/* harmony import */ var _xsd_internal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./xsd-internal */ "../rdflib/esm/xsd-internal.js"); - - +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.create = void 0; +var _create = __webpack_require__(/*! ./create */ "./lib/create/create.js"); +var create = { + newThingUI: _create.newThingUI +}; +exports.create = create; +//# sourceMappingURL=index.js.map +/***/ }), +/***/ "./lib/create/types.js": +/*!*****************************!*\ + !*** ./lib/create/types.js ***! + \*****************************/ +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_6__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_5__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +//# sourceMappingURL=types.js.map +/***/ }), +/***/ "./lib/debug.js": +/*!**********************!*\ + !*** ./lib/debug.js ***! + \**********************/ +/***/ ((__unused_webpack_module, exports) => { +"use strict"; -/** - * An RDF literal, containing some value which isn't expressed as an IRI. - * @link https://rdf.js.org/data-model-spec/#literal-interface - */ -var Literal = /*#__PURE__*/function (_Node) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__["default"])(Literal, _Node); - var _super = _createSuper(Literal); - /** - * The literal's datatype as a named node - */ +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.error = error; +exports.log = log; +exports.trace = trace; +exports.warn = warn; +function log() { + var _console; + // eslint-disable-next-line no-console + (_console = console).log.apply(_console, arguments); +} +function warn() { + var _console2; + // eslint-disable-next-line no-console + (_console2 = console).warn.apply(_console2, arguments); +} +function error() { + var _console3; + // eslint-disable-next-line no-console + (_console3 = console).error.apply(_console3, arguments); +} +function trace() { + var _console4; + // eslint-disable-next-line no-console + (_console4 = console).trace.apply(_console4, arguments); +} +//# sourceMappingURL=debug.js.map - /** - * The language for the literal - */ +/***/ }), - /** - * Initializes a literal - * @param value - The literal's lexical value - * @param language - The language for the literal. Defaults to ''. - * @param datatype - The literal's datatype as a named node. Defaults to xsd:string. - */ - function Literal(value, language, datatype) { - var _this; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, Literal); - _this = _super.call(this, value); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_8__.LiteralTermType); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_9__["default"].Literal); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "datatype", _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].string); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "isVar", 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_7__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_3__["default"])(_this), "language", ''); - if (language) { - _this.language = language; - _this.datatype = _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].langString; - } else if (datatype) { - _this.datatype = _named_node__WEBPACK_IMPORTED_MODULE_11__["default"].fromValue(datatype); - } else { - _this.datatype = _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].string; - } - return _this; - } +/***/ "./lib/footer/index.js": +/*!*****************************!*\ + !*** ./lib/footer/index.js ***! + \*****************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - /** - * Gets a copy of this literal - */ - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__["default"])(Literal, [{ - key: "copy", - value: function copy() { - return new Literal(this.value, this.lang, this.datatype); - } +"use strict"; - /** - * Gets whether two literals are the same - * @param other The other statement - */ - }, { - key: "equals", - value: function equals(other) { - if (!other) { - return false; - } - return this.termType === other.termType && this.value === other.value && this.language === other.language && (!this.datatype && !other.datatype || this.datatype && this.datatype.equals(other.datatype)); - } - /** - * The language for the literal - * @deprecated use {language} instead - */ - }, { - key: "lang", - get: function get() { - return this.language; - }, - set: function set(language) { - this.language = language || ''; - } - }, { - key: "toNT", - value: function toNT() { - return Literal.toNT(this); - } +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createControllerInfoBlock = createControllerInfoBlock; +exports.initFooter = initFooter; +exports.rebuildFooter = rebuildFooter; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); +var _headerFooterHelpers = __webpack_require__(/*! ../utils/headerFooterHelpers */ "./lib/utils/headerFooterHelpers.js"); +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); } +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; } +/* + This file was copied from mashlib/src/global/footer.ts file. It is modified to + work in solid-ui by adjusting where imported functions are found. + */ - /** Serializes a literal to an N-Triples string */ - }, { - key: "toString", - value: function toString() { - return '' + this.value; - } +var DEFAULT_SOLID_PROJECT_URL = 'https://solidproject.org'; +var DEFAULT_SOLID_PROJECT_NAME = 'solidproject.org'; - /** - * Builds a literal node from a boolean value - * @param value - The value - */ - }], [{ - key: "toNT", - value: function toNT(literal) { - if (typeof literal.value === 'number') { - return '' + literal.value; - } else if (typeof literal.value !== 'string') { - throw new Error('Value of RDF literal is not string or number: ' + literal.value); +/* + FooterOptions allow for customizing the link and name of the link part of the footer. + */ +/** + * Initialize footer component, the footer object returned depends on whether the user is authenticated. + * @param store the data store + * @returns the footer + */ +function initFooter(_x, _x2) { + return _initFooter.apply(this, arguments); +} +/** + * @ignore exporting this only for the unit test + */ +function _initFooter() { + _initFooter = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(store, options) { + var footer, pod, podOwner; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + footer = document.getElementById('PageFooter'); + if (footer) { + _context2.next = 3; + break; + } + return _context2.abrupt("return"); + case 3: + pod = (0, _headerFooterHelpers.getPod)(); + _context2.next = 6; + return (0, _headerFooterHelpers.getPodOwner)(pod, store); + case 6: + podOwner = _context2.sent; + rebuildFooter(footer, store, pod, podOwner, options)(); + _solidLogic.authSession.onLogin(rebuildFooter(footer, store, pod, podOwner, options)); + _solidLogic.authSession.onLogout(rebuildFooter(footer, store, pod, podOwner, options)); + case 10: + case "end": + return _context2.stop(); } - var str = literal.value; - // #x22 ("), #x5C (\), #x0A (\n) and #xD (\r) are disallowed and need to be replaced - // see https://www.w3.org/TR/n-triples/#grammar-production-STRING_LITERAL_QUOTE - str = str.replace(/\\/g, '\\\\'); - str = str.replace(/\"/g, '\\"'); - str = str.replace(/\n/g, '\\n'); - str = str.replace(/\r/g, '\\r'); - str = '"' + str + '"'; - if (literal.language) { - str += '@' + literal.language; - } else if (!literal.datatype.equals(_xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].string)) { - // Only add datatype if it's not a string - str += '^^' + literal.datatype.toCanonical(); + }, _callee2); + })); + return _initFooter.apply(this, arguments); +} +function rebuildFooter(footer, store, pod, podOwner, options) { + return /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var user; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + user = _solidLogic.authn.currentUser(); + footer.innerHTML = ''; + _context.t0 = footer; + _context.next = 5; + return createControllerInfoBlock(store, user, pod, podOwner, options); + case 5: + _context.t1 = _context.sent; + _context.t0.appendChild.call(_context.t0, _context.t1); + case 7: + case "end": + return _context.stop(); } - return str; - } - }, { - key: "fromBoolean", - value: function fromBoolean(value) { - var strValue = value ? '1' : '0'; - return new Literal(strValue, null, _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].boolean); - } - - /** - * Builds a literal node from a date value - * @param value The value - */ - }, { - key: "fromDate", - value: function fromDate(value) { - if (!(value instanceof Date)) { - throw new TypeError('Invalid argument to Literal.fromDate()'); - } - var d2 = function d2(x) { - return ('' + (100 + x)).slice(1, 3); - }; - var date = '' + value.getUTCFullYear() + '-' + d2(value.getUTCMonth() + 1) + '-' + d2(value.getUTCDate()) + 'T' + d2(value.getUTCHours()) + ':' + d2(value.getUTCMinutes()) + ':' + d2(value.getUTCSeconds()) + 'Z'; - return new Literal(date, null, _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].dateTime); - } - - /** - * Builds a literal node from a number value - * @param value - The value - */ - }, { - key: "fromNumber", - value: function fromNumber(value) { - if (typeof value !== 'number') { - throw new TypeError('Invalid argument to Literal.fromNumber()'); - } - var datatype; - var strValue = value.toString(); - if (strValue.indexOf('e') < 0 && Math.abs(value) <= Number.MAX_SAFE_INTEGER) { - datatype = Number.isInteger(value) ? _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].integer : _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].decimal; - } else { - datatype = _xsd_internal__WEBPACK_IMPORTED_MODULE_10__["default"].double; - } - return new Literal(strValue, null, datatype); - } - - /** - * Builds a literal node from an input value - * @param value - The input value - */ - }, { - key: "fromValue", - value: function fromValue(value) { - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_12__.isLiteral)(value)) { - return value; - } - switch ((0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(value)) { - case 'object': - if (value instanceof Date) { - return Literal.fromDate(value); - } - case 'boolean': - return Literal.fromBoolean(value); - case 'number': - return Literal.fromNumber(value); - case 'string': - return new Literal(value); - } - throw new Error("Can't make literal from " + value + ' of type ' + (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(value)); - } - }]); - return Literal; -}(_node_internal__WEBPACK_IMPORTED_MODULE_13__["default"]); - + }, _callee); + })); +} +/** + * @ignore exporting this only for the unit test + */ +function createControllerInfoBlock(store, user, pod, podOwner, options) { + var profileLinkContainer = document.createElement('div'); + if (!pod || !podOwner || user && user.equals(podOwner)) { + return profileLinkContainer; + } + profileLinkContainer.setAttribute('style', style.footer); + var podLinkPre = document.createElement('span'); + podLinkPre.innerText = "You're visiting "; + var podLink = document.createElement('a'); + podLink.href = pod.uri; + podLink.innerText = 'the Pod'; + var profileLinkPre = document.createElement('span'); + profileLinkPre.innerText = ' controlled by '; + var profileLink = document.createElement('a'); + profileLink.href = podOwner.uri; + profileLink.innerText = (0, _headerFooterHelpers.getName)(store, podOwner); + var solidProjectLinkPre = document.createElement('span'); + solidProjectLinkPre.innerText = '. For more info, check out '; + var solidProjectLink = document.createElement('a'); + solidProjectLink.href = options && options.solidProjectUrl ? options.solidProjectUrl : DEFAULT_SOLID_PROJECT_URL; + solidProjectLink.innerText = options && options.solidProjectName ? options.solidProjectName : DEFAULT_SOLID_PROJECT_NAME; + var solidProjectLinkPost = document.createElement('span'); + solidProjectLinkPost.innerText = '.'; + profileLinkContainer.appendChild(podLinkPre); + profileLinkContainer.appendChild(podLink); + profileLinkContainer.appendChild(profileLinkPre); + profileLinkContainer.appendChild(profileLink); + profileLinkContainer.appendChild(solidProjectLinkPre); + profileLinkContainer.appendChild(solidProjectLink); + profileLinkContainer.appendChild(solidProjectLinkPost); + return profileLinkContainer; +} +//# sourceMappingURL=index.js.map /***/ }), -/***/ "../rdflib/esm/log.js": -/*!****************************!*\ - !*** ../rdflib/esm/log.js ***! - \****************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./lib/header/empty-profile.js": +/*!*************************************!*\ + !*** ./lib/header/empty-profile.js ***! + \*************************************/ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/** - * A Dummy log - * @module log - */ -var log = { - debug: function debug(x) {}, - warn: function warn(x) {}, - info: function info(x) {}, - error: function error(x) {}, - success: function success(x) {}, - msg: function msg(x) {} -}; -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (log); -/***/ }), -/***/ "../rdflib/esm/n3parser.js": -/*!*********************************!*\ - !*** ../rdflib/esm/n3parser.js ***! - \*********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.emptyProfile = void 0; +var emptyProfile = "\n\n \n \n \n \n \n \n \n"; +exports.emptyProfile = emptyProfile; +//# sourceMappingURL=empty-profile.js.map -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "SinkParser": () => (/* binding */ SinkParser), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../rdflib/node_modules/@babel/runtime/helpers/esm/typeof.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils */ "../rdflib/esm/utils.js"); -/* harmony import */ var _lists__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./lists */ "../rdflib/esm/lists.js"); +/***/ }), +/***/ "./lib/header/index.js": +/*!*****************************!*\ + !*** ./lib/header/index.js ***! + \*****************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +"use strict"; -/** -* -* UTF-8 data encode / decode -* http://www.webtoolkit.info/ -* -**/ +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.createBanner = createBanner; +exports.createHelpMenu = createHelpMenu; +exports.createLoginSignUpButtons = createLoginSignUpButtons; +exports.createUserMenu = createUserMenu; +exports.createUserMenuButton = createUserMenuButton; +exports.createUserMenuItem = createUserMenuItem; +exports.createUserMenuLink = createUserMenuLink; +exports.getProfileImg = getProfileImg; +exports.initHeader = initHeader; +exports.rebuildHeader = rebuildHeader; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _index = __webpack_require__(/*! ../index */ "./lib/index.js"); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var _login = __webpack_require__(/*! ../login/login */ "./lib/login/login.js"); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); +var _emptyProfile = __webpack_require__(/*! ./empty-profile */ "./lib/header/empty-profile.js"); +var _headerFooterHelpers = __webpack_require__(/*! ../utils/headerFooterHelpers */ "./lib/utils/headerFooterHelpers.js"); +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); } +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; } +/* global EventListenerOrEventListenerObject */ +/* + This file was copied from mashlib/src/global/header.ts file. It is modified to + work in solid-ui by adjusting where imported functions are found. + */ +// import { loginStatusBox, authSession, currentUser } from '../authn/authn' -function hexify(str) { - // also used in parser - return encodeURI(str); +/** + * menu icons +*/ +var DEFAULT_HELP_MENU_ICON = _index.icons.iconBase + 'noun_help.svg'; +var DEFAUL_SOLID_ICON_URL = 'https://solidproject.org/assets/img/solid-emblem.svg'; +/** + * Initialize header component, the header object returned depends on whether the user is authenticated. + * @param store the data store + * @param userMenuList a list of menu items when the user is logged in + * @param options allow the header to be customized with a personalized logo, help icon and a help menu list of links or buttons. + * @returns a header for an authenticated user with menu items given or a login screen + */ +function initHeader(_x, _x2, _x3) { + return _initHeader.apply(this, arguments); } -var Utf8 = { - // public method for url encoding - encode: function encode(string) { - string = string.replace(/\r\n/g, "\n"); - var utftext = ""; - for (var n = 0; n < string.length; n++) { - var c = string.charCodeAt(n); - if (c < 128) { - utftext += String.fromCharCode(c); - } else if (c > 127 && c < 2048) { - utftext += String.fromCharCode(c >> 6 | 192); - utftext += String.fromCharCode(c & 63 | 128); - } else { - utftext += String.fromCharCode(c >> 12 | 224); - utftext += String.fromCharCode(c >> 6 & 63 | 128); - utftext += String.fromCharCode(c & 63 | 128); +/** + * @ignore exporting this only for the unit test + */ +function _initHeader() { + _initHeader = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(store, userMenuList, options) { + var header, pod; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + header = document.getElementById('PageHeader'); + if (header) { + _context2.next = 3; + break; + } + return _context2.abrupt("return"); + case 3: + pod = (0, _headerFooterHelpers.getPod)(); + rebuildHeader(header, store, pod, userMenuList, options)(); + _solidLogic.authSession.onLogout(rebuildHeader(header, store, pod, userMenuList, options)); + _solidLogic.authSession.onLogin(rebuildHeader(header, store, pod, userMenuList, options)); + case 7: + case "end": + return _context2.stop(); } - } - return utftext; - }, - // public method for url decoding - decode: function decode(utftext) { - var string = ""; - var i = 0; - while (i < utftext.length) { - var c = utftext.charCodeAt(i); - if (c < 128) { - string += String.fromCharCode(c); - i++; - } else if (c > 191 && c < 224) { - string += String.fromCharCode((c & 31) << 6 | utftext.charCodeAt(i + 1) & 63); - i += 2; - } else { - string += String.fromCharCode((c & 15) << 12 | (utftext.charCodeAt(i + 1) & 63) << 6 | utftext.charCodeAt(i + 2) & 63); - i += 3; + }, _callee2); + })); + return _initHeader.apply(this, arguments); +} +function rebuildHeader(header, store, pod, userMenuList, options) { + return /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee() { + var user; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + user = _solidLogic.authn.currentUser(); + header.innerHTML = ''; + _context.t0 = header; + _context.next = 5; + return createBanner(store, pod, user, userMenuList, options); + case 5: + _context.t1 = _context.sent; + _context.t0.appendChild.call(_context.t0, _context.t1); + case 7: + case "end": + return _context.stop(); + } + }, _callee); + })); +} +/** + * @ignore exporting this only for the unit test + */ +function createBanner(_x4, _x5, _x6, _x7, _x8) { + return _createBanner.apply(this, arguments); +} +/** + * @ignore exporting this only for the unit test + */ +function _createBanner() { + _createBanner = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(store, pod, user, userMenuList, options) { + var podLink, image, userMenu, banner, leftSideOfHeader, helpMenu; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + podLink = document.createElement('a'); + podLink.href = pod.uri; + podLink.setAttribute('style', style.headerBannerLink); + image = document.createElement('img'); + if (options) { + image.src = options.logo ? options.logo : DEFAUL_SOLID_ICON_URL; + } + image.setAttribute('style', style.headerBannerIcon); + podLink.appendChild(image); + if (!user) { + _context3.next = 13; + break; + } + _context3.next = 10; + return createUserMenu(store, user, userMenuList); + case 10: + _context3.t0 = _context3.sent; + _context3.next = 14; + break; + case 13: + _context3.t0 = createLoginSignUpButtons(); + case 14: + userMenu = _context3.t0; + banner = document.createElement('div'); + banner.setAttribute('style', style.headerBanner); + banner.appendChild(podLink); + leftSideOfHeader = document.createElement('div'); + leftSideOfHeader.setAttribute('style', style.headerBannerRightMenu); + leftSideOfHeader.appendChild(userMenu); + if (options && options.helpMenuList) { + helpMenu = createHelpMenu(options, options.helpMenuList); + leftSideOfHeader.appendChild(helpMenu); + } + banner.appendChild(leftSideOfHeader); + return _context3.abrupt("return", banner); + case 24: + case "end": + return _context3.stop(); } + }, _callee3); + })); + return _createBanner.apply(this, arguments); +} +function createHelpMenu(options, helpMenuItems) { + if (!helpMenuItems) return; + var helpMenuList = document.createElement('ul'); + helpMenuList.setAttribute('style', style.headerUserMenuList); + helpMenuItems.forEach(function (menuItem) { + var menuItemType = menuItem.url ? 'url' : 'onclick'; + if (menuItemType === 'url') { + helpMenuList.appendChild(createUserMenuItem(createUserMenuLink(menuItem.label, menuItem.url, menuItem.target))); + } else { + helpMenuList.appendChild(createUserMenuItem(createUserMenuButton(menuItem.label, menuItem.onclick))); } - return string; - } -}; // Things we need to define to make converted pythn code work in js -// environment of $rdf - -var RDFSink_forSomeSym = "http://www.w3.org/2000/10/swap/log#forSome"; -var RDFSink_forAllSym = "http://www.w3.org/2000/10/swap/log#forAll"; -var Logic_NS = "http://www.w3.org/2000/10/swap/log#"; - -// pyjs seems to reference runtime library which I didn't find - -var pyjslib_Tuple = function pyjslib_Tuple(theList) { - return theList; -}; -var pyjslib_List = function pyjslib_List(theList) { - return theList; -}; -var pyjslib_Dict = function pyjslib_Dict(listOfPairs) { - if (listOfPairs.length > 0) throw "missing.js: oops nnonempty dict not imp"; - return []; -}; -var pyjslib_len = function pyjslib_len(s) { - return s.length; -}; -var pyjslib_slice = function pyjslib_slice(str, i, j) { - if (typeof str.slice == 'undefined') throw '@@ mising.js: No .slice function for ' + str + ' of type ' + (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_2__["default"])(str); - if (typeof j == 'undefined' || j == null) return str.slice(i); - return str.slice(i, j); // @ exactly the same spec? -}; - -var StopIteration = Error('dummy error stop iteration'); -var pyjslib_Iterator = function pyjslib_Iterator(theList) { - this.last = 0; - this.li = theList; - this.next = function () { - if (this.last == this.li.length) throw StopIteration; - return this.li[this.last++]; + }); + var helpMenu = document.createElement('nav'); + helpMenu.setAttribute('style', style.headerUserMenuNavigationMenuNotDisplayed); + helpMenu.setAttribute('aria-hidden', 'true'); + helpMenu.setAttribute('id', 'helperNav'); + helpMenu.appendChild(helpMenuList); + var helpMenuContainer = document.createElement('div'); + helpMenuContainer.setAttribute('style', style.headerBannerUserMenu); + helpMenuContainer.appendChild(helpMenu); + var helpMenuTrigger = document.createElement('button'); + helpMenuTrigger.setAttribute('style', style.headerUserMenuTrigger); + helpMenuTrigger.type = 'button'; + var helpMenuIcon = document.createElement('img'); + helpMenuIcon.src = options && options.helpIcon ? options.helpIcon : _index.icons.iconBase + DEFAULT_HELP_MENU_ICON; + helpMenuIcon.setAttribute('style', style.headerUserMenuTriggerImg); + helpMenuContainer.appendChild(helpMenuTrigger); + helpMenuTrigger.appendChild(helpMenuIcon); + var throttledMenuToggle = (0, _headerFooterHelpers.throttle)(function (event) { + return toggleMenu(event, helpMenuTrigger, helpMenu); + }, 50); + helpMenuTrigger.addEventListener('click', throttledMenuToggle); + var timer = setTimeout(function () { + return null; + }, 0); + helpMenuContainer.addEventListener('mouseover', function (event) { + clearTimeout(timer); + throttledMenuToggle(event); + var nav = document.getElementById('helperNav'); + nav === null || nav === void 0 ? void 0 : nav.setAttribute('style', style.headerUserMenuNavigationMenu); + }); + helpMenuContainer.addEventListener('mouseout', function (event) { + timer = setTimeout(function () { + return throttledMenuToggle(event); + }, 200); + var nav = document.getElementById('helperNav'); + nav === null || nav === void 0 ? void 0 : nav.setAttribute('style', style.headerUserMenuNavigationMenuNotDisplayed); + }); + return helpMenuContainer; +} +/** + * @ignore exporting this only for the unit test + */ +function createLoginSignUpButtons() { + var profileLoginButtonPre = document.createElement('div'); + profileLoginButtonPre.setAttribute('style', style.headerBannerLogin); + profileLoginButtonPre.appendChild((0, _login.loginStatusBox)(document, null, {})); + return profileLoginButtonPre; +} +/** + * @ignore exporting this only for the unit test + */ +function createUserMenuButton(label, onClick) { + var button = document.createElement('button'); + button.setAttribute('style', style.headerUserMenuButton); + button.onmouseover = function () { + button.setAttribute('style', style.headerUserMenuButtonHover); }; - return this; -}; -var ord = function ord(str) { - return str.charCodeAt(0); -}; -var string_find = function string_find(str, s) { - return str.indexOf(s); -}; -var assertFudge = function assertFudge(condition, desc) { - if (condition) return; - if (desc) throw "python Assertion failed: " + desc; - throw "(python) Assertion failed."; -}; -var stringFromCharCode = function stringFromCharCode(uesc) { - return String.fromCharCode(uesc); -}; -String.prototype.encode = function (encoding) { - if (encoding != 'utf-8') throw "UTF8_converter: can only do utf-8"; - return Utf8.encode(this); -}; -String.prototype.decode = function (encoding) { - if (encoding != 'utf-8') throw "UTF8_converter: can only do utf-8"; - //return Utf8.decode(this); - return this; -}; -var uripath_join = function uripath_join(base, given) { - return _uri__WEBPACK_IMPORTED_MODULE_3__.join(given, base); // sad but true -}; - -var becauseSubexpression = null; // No reason needed -var diag_tracking = 0; -var diag_chatty_flag = 0; -var diag_progress = function diag_progress(str) {/*$rdf.log.debug(str);*/}; - -// why_BecauseOfData = function(doc, reason) { return doc }; - -var RDF_type_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type"; -var RDF_nil_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"; -var DAML_sameAs_URI = "http://www.w3.org/2002/07/owl#sameAs"; - -/* -function SyntaxError(details) { - return new __SyntaxError(details); + button.onmouseout = function () { + button.setAttribute('style', style.headerUserMenuButton); + }; + button.addEventListener('click', onClick); + button.innerText = label; + return button; } -*/ - -function __SyntaxError(details) { - this.details = details; +/** + * @ignore exporting this only for the unit test + */ +function createUserMenuLink(label, href, target) { + var link = document.createElement('a'); + link.setAttribute('style', style.headerUserMenuLink); + link.onmouseover = function () { + link.setAttribute('style', style.headerUserMenuLinkHover); + }; + link.onmouseout = function () { + link.setAttribute('style', style.headerUserMenuLink); + }; + link.href = href; + link.innerText = label; + if (target) link.target = target; + return link; } -/* - -$Id: n3parser.js 14561 2008-02-23 06:37:26Z kennyluck $ - -HAND EDITED FOR CONVERSION TO JAVASCRIPT - -This module implements a Nptation3 parser, and the final -part of a notation3 serializer. - -See also: - -Notation 3 -http://www.w3.org/DesignIssues/Notation3 - -Closed World Machine - and RDF Processor -http://www.w3.org/2000/10/swap/cwm - -To DO: See also "@@" in comments +/** + * @ignore exporting this only for the unit test + */ +function createUserMenu(_x9, _x10, _x11) { + return _createUserMenu.apply(this, arguments); +} +/** + * @ignore exporting this only for the unit test + */ +function _createUserMenu() { + _createUserMenu = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(store, user, userMenuList) { + var fetcher, loggedInMenuList, loggedInMenu, loggedInMenuTrigger, profileImg, loggedInMenuContainer, throttledMenuToggle, timer; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + fetcher = store.fetcher; + if (!fetcher) { + _context4.next = 4; + break; + } + _context4.next = 4; + return fetcher.load(user); + case 4: + loggedInMenuList = document.createElement('ul'); + loggedInMenuList.setAttribute('style', style.headerUserMenuList); + if (userMenuList) { + userMenuList.forEach(function (menuItem) { + var menuItemType = menuItem.url ? 'url' : 'onclick'; + if (menuItemType === 'url') { + loggedInMenuList.appendChild(createUserMenuItem(createUserMenuLink(menuItem.label, menuItem.url, menuItem.target))); + } else { + loggedInMenuList.appendChild(createUserMenuItem(createUserMenuButton(menuItem.label, menuItem.onclick))); + } + }); + } + loggedInMenu = document.createElement('nav'); + loggedInMenu.setAttribute('style', style.headerUserMenuNavigationMenuNotDisplayed); + loggedInMenu.setAttribute('aria-hidden', 'true'); + loggedInMenu.setAttribute('id', 'loggedInNav'); + loggedInMenu.appendChild(loggedInMenuList); + loggedInMenuTrigger = document.createElement('button'); + loggedInMenuTrigger.setAttribute('style', style.headerUserMenuTrigger); + loggedInMenuTrigger.type = 'button'; + profileImg = getProfileImg(store, user); + if (typeof profileImg === 'string') { + loggedInMenuTrigger.innerHTML = profileImg; + } else { + loggedInMenuTrigger.appendChild(profileImg); + } + loggedInMenuContainer = document.createElement('div'); + loggedInMenuContainer.setAttribute('style', style.headerBannerUserMenuNotDisplayed); + loggedInMenuContainer.appendChild(loggedInMenuTrigger); + loggedInMenuContainer.appendChild(loggedInMenu); + throttledMenuToggle = (0, _headerFooterHelpers.throttle)(function (event) { + return toggleMenu(event, loggedInMenuTrigger, loggedInMenu); + }, 50); + loggedInMenuTrigger.addEventListener('click', throttledMenuToggle); + timer = setTimeout(function () { + return null; + }, 0); + loggedInMenuContainer.addEventListener('mouseover', function (event) { + clearTimeout(timer); + throttledMenuToggle(event); + var nav = document.getElementById('loggedInNav'); + nav === null || nav === void 0 ? void 0 : nav.setAttribute('style', style.headerUserMenuNavigationMenu); + }); + loggedInMenuContainer.addEventListener('mouseout', function (event) { + timer = setTimeout(function () { + return throttledMenuToggle(event); + }, 200); + var nav = document.getElementById('loggedInNav'); + nav === null || nav === void 0 ? void 0 : nav.setAttribute('style', style.headerUserMenuNavigationMenuNotDisplayed); + }); + return _context4.abrupt("return", loggedInMenuContainer); + case 27: + case "end": + return _context4.stop(); + } + }, _callee4); + })); + return _createUserMenu.apply(this, arguments); +} +function createUserMenuItem(child) { + var menuProfileItem = document.createElement('li'); + menuProfileItem.setAttribute('style', style.headerUserMenuListItem); + menuProfileItem.appendChild(child); + return menuProfileItem; +} +/** + * @ignore exporting this only for the unit test + */ +function getProfileImg(store, user) { + var profileUrl = null; + try { + profileUrl = widgets.findImage(user); + if (!profileUrl) { + return _emptyProfile.emptyProfile; + } + } catch (_unused) { + return _emptyProfile.emptyProfile; + } + var profileImage = document.createElement('div'); + profileImage.setAttribute('style', style.headerUserMenuPhoto); + profileImage.style.backgroundImage = "url(".concat(profileUrl, ")"); + return profileImage; +} -- Clean up interfaces -______________________________________________ +/** + * @internal + */ +function toggleMenu(event, trigger, menu) { + var isExpanded = trigger.getAttribute('aria-expanded') === 'true'; + var expand = event.type === 'mouseover'; + var close = event.type === 'mouseout'; + if (isExpanded && expand || !isExpanded && close) { + return; + } + trigger.setAttribute('aria-expanded', (!isExpanded).toString()); + menu.setAttribute('aria-hidden', isExpanded.toString()); +} +//# sourceMappingURL=index.js.map -Module originally by Dan Connolly, includeing notation3 -parser and RDF generator. TimBL added RDF stream model -and N3 generation, replaced stream model with use -of common store/formula API. Yosi Scharf developped -the module, including tests and test harness. +/***/ }), -*/ +/***/ "./lib/iconBase.js": +/*!*************************!*\ + !*** ./lib/iconBase.js ***! + \*************************/ +/***/ ((module, exports, __webpack_require__) => { -var ADDED_HASH = "#"; -var LOG_implies_URI = "http://www.w3.org/2000/10/swap/log#implies"; -var INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; -var FLOAT_DATATYPE = "http://www.w3.org/2001/XMLSchema#double"; -var DECIMAL_DATATYPE = "http://www.w3.org/2001/XMLSchema#decimal"; -var DATE_DATATYPE = "http://www.w3.org/2001/XMLSchema#date"; -var DATETIME_DATATYPE = "http://www.w3.org/2001/XMLSchema#dateTime"; -var BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; -var option_noregen = 0; -var _notQNameChars = "\t\r\n !\"#$%&'()*.,+/;<=>?@[\\]^`{|}~"; -var _notNameChars = _notQNameChars + ":"; -var _rdfns = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; -var N3CommentCharacter = "#"; -var eol = new RegExp("^[ \\t]*(#[^\\n]*)?\\r?\\n", 'g'); -var eof = new RegExp("^[ \\t]*(#[^\\n]*)?$", 'g'); -var ws = new RegExp("^[ \\t]*", 'g'); -var signed_integer = new RegExp("^[-+]?[0-9]+", 'g'); -var number_syntax = new RegExp("^([-+]?[0-9]+)(\\.[0-9]+)?(e[-+]?[0-9]+)?", 'g'); -var datetime_syntax = new RegExp('^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9](T[0-9][0-9]:[0-9][0-9](:[0-9][0-9](\\.[0-9]*)?)?)?Z?'); -var digitstring = new RegExp("^[0-9]+", 'g'); -var interesting = new RegExp("[\\\\\\r\\n\\\"]", 'g'); -var langcode = new RegExp("^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*", 'g'); -function createSinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) { - return new SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why); -} -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (createSinkParser); -var SinkParser = /*#__PURE__*/function () { - function SinkParser(store, openFormula, thisDoc, baseURI, genPrefix, metaURI, flags, why) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, SinkParser); - if (typeof openFormula == 'undefined') openFormula = null; - if (typeof thisDoc == 'undefined') thisDoc = ""; - if (typeof baseURI == 'undefined') baseURI = null; - if (typeof genPrefix == 'undefined') genPrefix = ""; - if (typeof metaURI == 'undefined') metaURI = null; - if (typeof flags == 'undefined') flags = ""; - if (typeof why == 'undefined') why = null; - /* - note: namespace names should *not* end in #; - the # will get added during qname processing */ +"use strict"; +/* module decorator */ module = __webpack_require__.nmd(module); - this._bindings = new pyjslib_Dict([]); - this._flags = flags; - if (thisDoc != "") { - assertFudge(thisDoc.indexOf(":") >= 0, "Document URI not absolute: " + thisDoc); - this._bindings[""] = thisDoc + "#"; - } - this._store = store; - if (genPrefix) { - store.setGenPrefix(genPrefix); - } - this._thisDoc = thisDoc; - this.source = store.sym(thisDoc); - this.lines = 0; - this.statementCount = 0; - this.hasNil = false; - this.startOfLine = 0; - this.previousLine = 0; - this._genPrefix = genPrefix; - this.keywords = new pyjslib_List(["a", "this", "bind", "has", "is", "of", "true", "false"]); - this.keywordsSet = 0; - this._anonymousNodes = new pyjslib_Dict([]); - this._variables = new pyjslib_Dict([]); - this._parentVariables = new pyjslib_Dict([]); - this._reason = why; - this._reason2 = null; - if (diag_tracking) { - this._reason2 = why_BecauseOfData(store.sym(thisDoc), this._reason); - } - if (baseURI) { - this._baseURI = baseURI; - } else { - if (thisDoc) { - this._baseURI = thisDoc; - } else { - this._baseURI = null; - } - } - assertFudge(!this._baseURI || this._baseURI.indexOf(":") >= 0); - if (!this._genPrefix) { - if (this._thisDoc) { - this._genPrefix = this._thisDoc + "#_g"; - } else { - this._genPrefix = RDFSink_uniqueURI(); - } - } - if (openFormula == null) { - if (this._thisDoc) { - this._formula = store.formula(thisDoc + "#_formula"); - } else { - this._formula = store.formula(); - } - } else { - this._formula = openFormula; - } - this._context = this._formula; - this._parentContext = null; - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(SinkParser, [{ - key: "here", - value: function here(i) { - return this._genPrefix + "_L" + this.lines + "C" + (i - this.startOfLine + 1); - } - }, { - key: "formula", - value: function formula() { - return this._formula; - } - }, { - key: "loadStream", - value: function loadStream(stream) { - return this.loadBuf(stream.read()); - } - }, { - key: "loadBuf", - value: function loadBuf(buf) { - /* - Parses a buffer and returns its top level formula*/ - this.startDoc(); - this.feed(buf); - return this.endDoc(); - } - }, { - key: "feed", - value: function feed(octets) { - /* - Feed an octet stream tothe parser - if BadSyntax is raised, the string - passed in the exception object is the - remainder after any statements have been parsed. - So if there is more data to feed to the - parser, it should be straightforward to recover.*/ +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.originalIconBase = exports.icons = exports.iconBase = void 0; +var _debug = __webpack_require__(/*! ./debug */ "./lib/debug.js"); +// Works in FF extension - what about browserify?? +// 2021-04-08 Convert to TS - var str = octets.decode("utf-8"); - var i = 0; - while (i >= 0) { - var j = this.skipSpace(str, i); - if (j < 0) { - return; - } - var i = this.directiveOrStatement(str, j); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "expected directive or statement"); - } - } - } - }, { - key: "directiveOrStatement", - value: function directiveOrStatement(str, h) { - var i = this.skipSpace(str, h); - if (i < 0) { - return i; - } - var j = this.directive(str, i); - if (j >= 0) { - return this.checkDot(str, j); - } - var j = this.statement(str, i); - if (j >= 0) { - return this.checkDot(str, j); - } - return j; - } - }, { - key: "tok", - value: function tok(_tok, str, i) { - /* - Check for keyword. Space must have been stripped on entry and - we must not be at end of file.*/ - var whitespace = "\t\n\v\f\r "; - if (str.slice(i, i + 1) == "@") { - var i = i + 1; - } else { - if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this.keywords, _tok) < 0) { - return -1; - } - } - var k = i + pyjslib_len(_tok); - if (str.slice(i, k) == _tok && _notQNameChars.indexOf(str.charAt(k)) >= 0) { - return k; - } else { - return -1; - } - } - }, { - key: "directive", - value: function directive(str, i) { - var j = this.skipSpace(str, i); - if (j < 0) { - return j; - } - var res = new pyjslib_List([]); - var j = this.tok("bind", str, i); - if (j > 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "keyword bind is obsolete: use @prefix"); - } - var j = this.tok("keywords", str, i); - if (j > 0) { - var i = this.commaSeparatedList(str, j, res, false); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "'@keywords' needs comma separated list of words"); - } - this.setKeywords(pyjslib_slice(res, null, null)); - if (diag_chatty_flag > 80) { - diag_progress("Keywords ", this.keywords); - } - return i; - } - var j = this.tok("forAll", str, i); - if (j > 0) { - var i = this.commaSeparatedList(str, j, res, true); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "Bad variable list after @forAll"); - } - var __x = new pyjslib_Iterator(res); - try { - while (true) { - var x = __x.next(); - if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this._variables, x) < 0 || (0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this._parentVariables, x) >= 0) { - this._variables[x] = this._context.newUniversal(x); - } - } - } catch (e) { - if (e != StopIteration) { - throw e; - } - } - return i; - } - var j = this.tok("forSome", str, i); - if (j > 0) { - var i = this.commaSeparatedList(str, j, res, this.uri_ref2); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "Bad variable list after @forSome"); - } - var __x = new pyjslib_Iterator(res); - try { - while (true) { - var x = __x.next(); - this._context.declareExistential(x); - } - } catch (e) { - if (e != StopIteration) { - throw e; - } - } - return i; - } - var j = this.tok("prefix", str, i); - if (j >= 0) { - var t = new pyjslib_List([]); - var i = this.qname(str, j, t); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "expected qname after @prefix"); - } - var j = this.uri_ref2(str, i, t); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "expected after @prefix _qname_"); - } - var ns = t[1].uri; - if (this._baseURI) { - var ns = uripath_join(this._baseURI, ns); - } else { - assertFudge(ns.indexOf(":") >= 0, "With no base URI, cannot handle relative URI for NS"); - } - assertFudge(ns.indexOf(":") >= 0); - this._bindings[t[0][0]] = ns; - this.bind(t[0][0], hexify(ns)); - return j; - } - var j = this.tok("base", str, i); - if (j >= 0) { - var t = new pyjslib_List([]); - var i = this.uri_ref2(str, j, t); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "expected after @base "); - } - var ns = t[0].uri; - if (this._baseURI) { - var ns = uripath_join(this._baseURI, ns); - } else { - throw BadSyntax(this._thisDoc, this.lines, str, j, "With no previous base URI, cannot use relative URI in @base <" + ns + ">"); - } - assertFudge(ns.indexOf(":") >= 0); - this._baseURI = ns; - return i; - } - return -1; - } - }, { - key: "bind", - value: function bind(qn, uri) { - if (qn == "") {} else { - this._store.setPrefixForURI(qn, uri); - } - } - }, { - key: "setKeywords", - value: function setKeywords(k) { - /* - Takes a list of strings*/ +/* The Firefox case is left for historical record, as we don't currenly + * have a FF extension for mashlib, but we could. This is sthepoint to + * hack the place it can find its icons internally + * + * The $SolidTestEnvironment is important and is used for + * example when testing on localhost to specify a place the icons be found + * in your test set up. + * + * You can also use it if you want to just run a mashlib whhich takes its + * icons seved by other than github. + */ +/* eslint-disable multiline-ternary */ - if (k == null) { - this.keywordsSet = 0; - } else { - this.keywords = k; - this.keywordsSet = 1; - } - } - }, { - key: "startDoc", - value: function startDoc() {} - }, { - key: "endDoc", - value: /* Signal end of document and stop parsing. returns formula */ - function endDoc() { - if (this.hasNil && this._store.rdfFactory.supports["COLLECTIONS"]) { - (0,_lists__WEBPACK_IMPORTED_MODULE_5__.convertFirstRestNil)(this._store, this.source); - } - return this._formula; - } - }, { - key: "makeStatement", - value: function makeStatement(quad) { - quad[0].add(quad[2], quad[1], quad[3], this.source); - if (quad[2].uri && quad[2].uri === RDF_nil_URI || quad[3].uri && quad[3].uri === RDF_nil_URI) { - this.hasNil = true; - } - this.statementCount += 1; - } - }, { - key: "statement", - value: function statement(str, i) { - var r = new pyjslib_List([]); - var i = this.object(str, i, r); - if (i < 0) { - return i; - } - var j = this.property_list(str, i, r[0]); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "expected propertylist"); - } - return j; - } - }, { - key: "subject", - value: function subject(str, i, res) { - return this.item(str, i, res); - } - }, { - key: "verb", - value: function verb(str, i, res) { - /* - has _prop_ - is _prop_ of - a - = - _prop_ - >- prop -> - <- prop -< - _operator_*/ +// Do not export. Always us this module to find the icons, as they vary +var iconsOnGithub = 'https://solidos.github.io/solid-ui/src'; // changed org 2022-05 - var j = this.skipSpace(str, i); - if (j < 0) { - return j; - } - var r = new pyjslib_List([]); - var j = this.tok("has", str, i); - if (j >= 0) { - var i = this.prop(str, j, r); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "expected property after 'has'"); - } - res.push(new pyjslib_Tuple(["->", r[0]])); - return i; - } - var j = this.tok("is", str, i); - if (j >= 0) { - var i = this.prop(str, j, r); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "expected after 'is'"); - } - var j = this.skipSpace(str, i); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "End of file found, expected property after 'is'"); - return j; - } - var i = j; - var j = this.tok("of", str, i); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "expected 'of' after 'is' "); - } - res.push(new pyjslib_Tuple(["<-", r[0]])); - return j; - } - var j = this.tok("a", str, i); - if (j >= 0) { - res.push(new pyjslib_Tuple(["->", this._store.sym(RDF_type_URI)])); - return j; - } - if (str.slice(i, i + 2) == "<=") { - res.push(new pyjslib_Tuple(["<-", this._store.sym(Logic_NS + "implies")])); - return i + 2; - } - if (str.slice(i, i + 1) == "=") { - if (str.slice(i + 1, i + 2) == ">") { - res.push(new pyjslib_Tuple(["->", this._store.sym(Logic_NS + "implies")])); - return i + 2; - } - res.push(new pyjslib_Tuple(["->", this._store.sym(DAML_sameAs_URI)])); - return i + 1; - } - if (str.slice(i, i + 2) == ":=") { - res.push(new pyjslib_Tuple(["->", Logic_NS + "becomes"])); - return i + 2; - } - var j = this.prop(str, i, r); - if (j >= 0) { - res.push(new pyjslib_Tuple(["->", r[0]])); - return j; - } - if (str.slice(i, i + 2) == ">-" || str.slice(i, i + 2) == "<-") { - throw BadSyntax(this._thisDoc, this.lines, str, j, ">- ... -> syntax is obsolete."); - } - return -1; - } - }, { - key: "prop", - value: function prop(str, i, res) { - return this.item(str, i, res); - } - }, { - key: "item", - value: function item(str, i, res) { - return this.path(str, i, res); - } - }, { - key: "blankNode", - value: function blankNode(uri) { - return this._context.bnode(uri, this._reason2); - } - }, { - key: "path", - value: function path(str, i, res) { - /* - Parse the path production. - */ +var icons = module.scriptURI // Firefox extension +? { + iconBase: module.scriptURI.slice(0, module.scriptURI.lastIndexOf('/')) + '/icons/', + originalIconBase: module.scriptURI.slice(0, module.scriptURI.lastIndexOf('/')) + '/originalIcons/' +} : typeof $SolidTestEnvironment !== 'undefined' && $SolidTestEnvironment.iconBase // Test environemnt +? { + iconBase: $SolidTestEnvironment.iconBase, + originalIconBase: $SolidTestEnvironment.originalIconBase +} : { + // Normal case: + iconBase: iconsOnGithub + '/icons/', + originalIconBase: iconsOnGithub + '/originalIcons/' +}; +exports.icons = icons; +(0, _debug.log)(' icons.iconBase is set to : ' + icons.iconBase); - var j = this.nodeOrLiteral(str, i, res); - if (j < 0) { - return j; - } - while ("!^.".indexOf(str.slice(j, j + 1)) >= 0) { - var ch = str.slice(j, j + 1); - if (ch == ".") { - var ahead = str.slice(j + 1, j + 2); - if (!ahead || _notNameChars.indexOf(ahead) >= 0 && ":?<[{(".indexOf(ahead) < 0) { - break; - } - } - var subj = res.pop(); - var obj = this.blankNode(this.here(j)); - var j = this.node(str, j + 1, res); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "EOF found in middle of path syntax"); - } - var pred = res.pop(); - if (ch == "^") { - this.makeStatement(new pyjslib_Tuple([this._context, pred, obj, subj])); - } else { - this.makeStatement(new pyjslib_Tuple([this._context, pred, subj, obj])); - } - res.push(obj); - } - return j; - } - }, { - key: "anonymousNode", - value: function anonymousNode(ln) { - /* - Remember or generate a term for one of these _: anonymous nodes*/ +// allow tests etc named-import this directly from this module +var iconBase = icons.iconBase; +exports.iconBase = iconBase; +var originalIconBase = icons.originalIconBase; +exports.originalIconBase = originalIconBase; +//# sourceMappingURL=iconBase.js.map - var term = this._anonymousNodes[ln]; - if (term) { - return term; - } - var term = this._store.bnode(ln); - // var term = this._store.bnode(this._context, this._reason2); eh? - this._anonymousNodes[ln] = term; - return term; - } - }, { - key: "node", - value: function node(str, i, res, subjectAlready) { - if (typeof subjectAlready == 'undefined') subjectAlready = null; - /* - Parse the production. - Space is now skipped once at the beginning - instead of in multipe calls to self.skipSpace(). - */ +/***/ }), - var subj = subjectAlready; - var j = this.skipSpace(str, i); - if (j < 0) { - return j; - } - var i = j; - var ch = str.slice(i, i + 1); - if (ch == "[") { - var bnodeID = this.here(i); - var j = this.skipSpace(str, i + 1); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF after '['"); - } - if (str.slice(j, j + 1) == "=") { - var i = j + 1; - var objs = new pyjslib_List([]); - var j = this.objectList(str, i, objs); - if (j >= 0) { - var subj = objs[0]; - if (pyjslib_len(objs) > 1) { - var __obj = new pyjslib_Iterator(objs); - try { - while (true) { - var obj = __obj.next(); - this.makeStatement(new pyjslib_Tuple([this._context, this._store.sym(DAML_sameAs_URI), subj, obj])); - } - } catch (e) { - if (e != StopIteration) { - throw e; - } - } - } - var j = this.skipSpace(str, j); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF when objectList expected after [ = "); - } - if (str.slice(j, j + 1) == ";") { - var j = j + 1; - } - } else { - throw BadSyntax(this._thisDoc, this.lines, str, i, "objectList expected after [= "); - } - } - if (subj == null) { - var subj = this.blankNode(bnodeID); - } - var i = this.property_list(str, j, subj); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "property_list expected"); - } - var j = this.skipSpace(str, i); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF when ']' expected after [ "); - } - if (str.slice(j, j + 1) != "]") { - throw BadSyntax(this._thisDoc, this.lines, str, j, "']' expected"); - } - res.push(subj); - return j + 1; - } - if (ch == "{") { - var ch2 = str.slice(i + 1, i + 2); - if (ch2 == "$") { - i += 1; - var j = i + 1; - var mylist = new pyjslib_List([]); - var first_run = true; - while (1) { - var i = this.skipSpace(str, j); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "needed '$}', found end."); - } - if (str.slice(i, i + 2) == "$}") { - var j = i + 2; - break; - } - if (!first_run) { - if (str.slice(i, i + 1) == ",") { - i += 1; - } else { - throw BadSyntax(this._thisDoc, this.lines, str, i, "expected: ','"); - } - } else { - var first_run = false; - } - var item = new pyjslib_List([]); - var j = this.item(str, i, item); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "expected item in set or '$}'"); - } - mylist.push(item[0]); - } - res.push(this._store.newSet(mylist, this._context)); - return j; - } else { - var j = i + 1; - var oldParentContext = this._parentContext; - this._parentContext = this._context; - var parentAnonymousNodes = this._anonymousNodes; - var grandParentVariables = this._parentVariables; - this._parentVariables = this._variables; - this._anonymousNodes = new pyjslib_Dict([]); - this._variables = this._variables.slice(); - var reason2 = this._reason2; - this._reason2 = becauseSubexpression; - if (subj == null) { - var subj = this._store.formula(); - } - this._context = subj; - while (1) { - var i = this.skipSpace(str, j); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "needed '}', found end."); - } - if (str.slice(i, i + 1) == "}") { - var j = i + 1; - break; - } - var j = this.directiveOrStatement(str, i); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "expected statement or '}'"); - } - } - this._anonymousNodes = parentAnonymousNodes; - this._variables = this._parentVariables; - this._parentVariables = grandParentVariables; - this._context = this._parentContext; - this._reason2 = reason2; - this._parentContext = oldParentContext; - res.push(subj.close()); - return j; - } - } - if (ch == "(") { - var thing_type = this._store.list; - var ch2 = str.slice(i + 1, i + 2); - if (ch2 == "$") { - var thing_type = this._store.newSet; - i += 1; - } - var j = i + 1; - var mylist = new pyjslib_List([]); - while (1) { - var i = this.skipSpace(str, j); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "needed ')', found end."); - } - if (str.slice(i, i + 1) == ")") { - var j = i + 1; - break; - } - var item = new pyjslib_List([]); - var j = this.item(str, i, item); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "expected item in list or ')'"); - } - mylist.push(item[0]); - } - res.push(thing_type(mylist, this._context)); - return j; - } - var j = this.tok("this", str, i); - if (j >= 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "Keyword 'this' was ancient N3. Now use @forSome and @forAll keywords."); - res.push(this._context); - return j; - } - var j = this.tok("true", str, i); - if (j >= 0) { - res.push(true); - return j; - } - var j = this.tok("false", str, i); - if (j >= 0) { - res.push(false); - return j; - } - if (subj == null) { - var j = this.uri_ref2(str, i, res); - if (j >= 0) { - return j; - } - } - return -1; - } - }, { - key: "property_list", - value: function property_list(str, i, subj) { - /* - Parse property list - Leaves the terminating punctuation in the buffer - */ +/***/ "./lib/index.js": +/*!**********************!*\ + !*** ./lib/index.js ***! + \**********************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - while (1) { - var j = this.skipSpace(str, i); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF found when expected verb in property list"); - return j; - } - if (str.slice(j, j + 2) == ":-") { - var i = j + 2; - var res = new pyjslib_List([]); - var j = this.node(str, i, res, subj); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "bad {} or () or [] node after :- "); - } - var i = j; - continue; - } - var i = j; - var v = new pyjslib_List([]); - var j = this.verb(str, i, v); - if (j <= 0) { - return i; - } - var objs = new pyjslib_List([]); - var i = this.objectList(str, j, objs); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "objectList expected"); - } - var __obj = new pyjslib_Iterator(objs); - try { - while (true) { - var obj = __obj.next(); - var pairFudge = v[0]; - var dir = pairFudge[0]; - var sym = pairFudge[1]; - if (dir == "->") { - this.makeStatement(new pyjslib_Tuple([this._context, sym, subj, obj])); - } else { - this.makeStatement(new pyjslib_Tuple([this._context, sym, obj, subj])); - } - } - } catch (e) { - if (e != StopIteration) { - throw e; - } - } - var j = this.skipSpace(str, i); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "EOF found in list of objects"); - return j; - } - if (str.slice(i, i + 1) != ";") { - return i; - } - var i = i + 1; - } - } - }, { - key: "commaSeparatedList", - value: function commaSeparatedList(str, j, res, ofUris) { - /* - return value: -1 bad syntax; >1 new position in str - res has things found appended - Used to use a final value of the function to be called, e.g. this.bareWord - but passing the function didn't work fo js converion pyjs - */ +"use strict"; +/* +The MIT License (MIT) - var i = this.skipSpace(str, j); - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "EOF found expecting comma sep list"); - return i; - } - if (str.charAt(i) == ".") { - return j; - } - if (ofUris) { - var i = this.uri_ref2(str, i, res); - } else { - var i = this.bareWord(str, i, res); - } - if (i < 0) { - return -1; - } - while (1) { - var j = this.skipSpace(str, i); - if (j < 0) { - return j; - } - var ch = str.slice(j, j + 1); - if (ch != ",") { - if (ch != ".") { - return -1; - } - return j; - } - if (ofUris) { - var i = this.uri_ref2(str, j + 1, res); - } else { - var i = this.bareWord(str, j + 1, res); - } - if (i < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "bad list content"); - return i; - } - } - } - }, { - key: "objectList", - value: function objectList(str, i, res) { - var i = this.object(str, i, res); - if (i < 0) { - return -1; - } - while (1) { - var j = this.skipSpace(str, i); - if (j < 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "EOF found after object"); - return j; - } - if (str.slice(j, j + 1) != ",") { - return j; - } - var i = this.object(str, j + 1, res); - if (i < 0) { - return i; - } - } - } - }, { - key: "checkDot", - value: function checkDot(str, i) { - var j = this.skipSpace(str, i); - if (j < 0) { - return j; - } - if (str.slice(j, j + 1) == ".") { - return j + 1; - } - if (str.slice(j, j + 1) == "}") { - return j; - } - if (str.slice(j, j + 1) == "]") { - return j; - } - throw BadSyntax(this._thisDoc, this.lines, str, j, "expected '.' or '}' or ']' at end of statement"); - return i; - } - }, { - key: "uri_ref2", - value: function uri_ref2(str, i, res) { - /* - Generate uri from n3 representation. - Note that the RDF convention of directly concatenating - NS and local name is now used though I prefer inserting a '#' - to make the namesapces look more like what XML folks expect. - */ +Copyright (c) 2015-2016 Solid - var qn = new pyjslib_List([]); - var j = this.qname(str, i, qn); - if (j >= 0) { - var pairFudge = qn[0]; - var pfx = pairFudge[0]; - var ln = pairFudge[1]; - if (pfx == null) { - assertFudge(0, "not used?"); - var ns = this._baseURI + ADDED_HASH; - } else { - var ns = this._bindings[pfx]; - if (!ns) { - if (pfx == "_") { - res.push(this.anonymousNode(ln)); - return j; - } - throw BadSyntax(this._thisDoc, this.lines, str, i, "Prefix " + pfx + " not bound."); - } - } - var symb = this._store.sym(ns + ln); - if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this._variables, symb) >= 0) { - res.push(this._variables[symb]); - } else { - res.push(symb); - } - return j; - } - var i = this.skipSpace(str, i); - if (i < 0) { - return -1; - } - if (str.charAt(i) == "?") { - var v = new pyjslib_List([]); - var j = this.variable(str, i, v); - if (j > 0) { - res.push(v[0]); - return j; - } - return -1; - } else if (str.charAt(i) == "<") { - var i = i + 1; - var st = i; - while (i < pyjslib_len(str)) { - if (str.charAt(i) == ">") { - var uref = str.slice(st, i); - if (this._baseURI) { - var uref = uripath_join(this._baseURI, uref); - } else { - assertFudge(uref.indexOf(":") >= 0, "With no base URI, cannot deal with relative URIs"); - } - if (str.slice(i - 1, i) == "#" && !(pyjslib_slice(uref, -1, null) == "#")) { - var uref = uref + "#"; - } - var symb = this._store.sym(uref); - if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this._variables, symb) >= 0) { - res.push(this._variables[symb]); - } else { - res.push(symb); - } - return i + 1; - } - var i = i + 1; - } - throw BadSyntax(this._thisDoc, this.lines, str, j, "unterminated URI reference"); - } else if (this.keywordsSet) { - var v = new pyjslib_List([]); - var j = this.bareWord(str, i, v); - if (j < 0) { - return -1; - } - if ((0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this.keywords, v[0]) >= 0) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "Keyword \"" + v[0] + "\" not allowed here."); - } - res.push(this._store.sym(this._bindings[""] + v[0])); - return j; - } else { - return -1; - } - } - }, { - key: "skipSpace", - value: function skipSpace(str, i) { - /* - Skip white space, newlines and comments. - return -1 if EOF, else position of first non-ws character*/ +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: - var whitespace = " \n\r\t\f\x0B\xA0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u200B\u2028\u2029\u3000"; - for (var j = i ? i : 0; j < str.length; j++) { - var ch = str.charAt(j); - // console.log(" skipspace j= "+j + " i= " + i + " n= " + str.length); - // console.log(" skipspace ch <" + ch + ">"); - if (whitespace.indexOf(ch) < 0) { - //not ws - // console.log(" skipspace 2 ch <" + ch + ">"); - if (str.charAt(j) === '#') { - for (;; j++) { - // console.log(" skipspace2 j= "+j + " i= " + i + " n= " + str.length); - if (j === str.length) { - return -1; // EOF - } +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. - if (str.charAt(j) === '\n') { - this.lines = this.lines + 1; - break; - } - } - ; - } else { - // Not hash - something interesting - // console.log(" skipspace 3 ch <" + ch + ">"); - return j; - } - } else { - // Whitespace - // console.log(" skipspace 5 ch <" + ch + ">"); - if (str.charAt(j) === '\n') { - this.lines = this.lines + 1; - } - } - } // next j - return -1; // EOF - } - }, { - key: "variable", - value: function variable(str, i, res) { - /* - ?abc -> variable(:abc) - */ +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. - var j = this.skipSpace(str, i); - if (j < 0) { - return -1; - } - if (str.slice(j, j + 1) != "?") { - return -1; - } - var j = j + 1; - var i = j; - if ("0123456789-".indexOf(str.charAt(j)) >= 0) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "Varible name can't start with '" + str.charAt(j) + "s'"); - return -1; - } - while (i < pyjslib_len(str) && _notNameChars.indexOf(str.charAt(i)) < 0) { - var i = i + 1; - } - if (this._parentContext == null) { - throw BadSyntax(this._thisDoc, this.lines, str, j, "Can't use ?xxx syntax for variable in outermost level: " + str.slice(j - 1, i)); - } - res.push(this._store.variable(str.slice(j, i))); - return i; - } - }, { - key: "bareWord", - value: function bareWord(str, i, res) { - /* - abc -> :abc - */ +If you would like to know more about the solid Solid project, please see +https://github.com/solidos/solid +*/ - var j = this.skipSpace(str, i); - if (j < 0) { - return -1; - } - var ch = str.charAt(j); - if ("0123456789-".indexOf(ch) >= 0) { - return -1; - } - if (_notNameChars.indexOf(ch) >= 0) { - return -1; - } - var i = j; - while (i < pyjslib_len(str) && _notNameChars.indexOf(str.charAt(i)) < 0) { - var i = i + 1; - } - res.push(str.slice(j, i)); - return i; - } - }, { - key: "qname", - value: function qname(str, i, res) { - /* - xyz:def -> ('xyz', 'def') - If not in keywords and keywordsSet: def -> ('', 'def') - :def -> ('', 'def') - */ - var i = this.skipSpace(str, i); - if (i < 0) { - return -1; - } - var c = str.charAt(i); - if ("0123456789-+".indexOf(c) >= 0) { - return -1; - } - if (_notNameChars.indexOf(c) < 0) { - var ln = c; - var i = i + 1; - while (i < pyjslib_len(str)) { - var c = str.charAt(i); - if (_notNameChars.indexOf(c) < 0) { - var ln = ln + c; - var i = i + 1; - } else { - break; - } - } - } else { - var ln = ""; - } - if (i < pyjslib_len(str) && str.charAt(i) == ":") { - var pfx = ln; - var i = i + 1; - var ln = ""; - while (i < pyjslib_len(str)) { - var c = str.charAt(i); - if (_notNameChars.indexOf(c) < 0) { - var ln = ln + c; - var i = i + 1; - } else { - break; - } - } - res.push(new pyjslib_Tuple([pfx, ln])); - return i; - } else { - if (ln && this.keywordsSet && (0,_utils__WEBPACK_IMPORTED_MODULE_4__.ArrayIndexOf)(this.keywords, ln) < 0) { - res.push(new pyjslib_Tuple(["", ln])); - return i; - } - return -1; - } - } - }, { - key: "object", - value: function object(str, i, res) { - var j = this.subject(str, i, res); - if (j >= 0) { - return j; - } else { - var j = this.skipSpace(str, i); - if (j < 0) { - return -1; - } else { - var i = j; - } - var delim = null; - var ch = str.charAt(i); - if (ch == "\"" || ch == "'") { - if (str.slice(i, i + 3 == ch + ch)) { - delim = ch + ch + ch; - } else { - delim = ch; - } - var i = i + pyjslib_len(delim); - var pairFudge = this.strconst(str, i, delim); - var j = pairFudge[0]; - var s = pairFudge[1]; - res.push(this._store.literal(s)); - diag_progress("New string const ", s, j); - return j; - } else { - return -1; - } - } - } - }, { - key: "nodeOrLiteral", - value: function nodeOrLiteral(str, i, res) { - var j = this.node(str, i, res); - if (j >= 0) { - return j; - } else { - var j = this.skipSpace(str, i); - if (j < 0) { - return -1; - } else { - var i = j; - } - var ch = str.charAt(i); - if ("-+0987654321".indexOf(ch) >= 0) { - datetime_syntax.lastIndex = 0; - var m = datetime_syntax.exec(str.slice(i)); - if (m != null) { - // j = ( i + datetime_syntax.lastIndex ) ; - var val = m[0]; - j = i + val.length; - if (val.indexOf("T") >= 0) { - res.push(this._store.literal(val, this._store.sym(DATETIME_DATATYPE))); - } else { - res.push(this._store.literal(val, this._store.sym(DATE_DATATYPE))); - } - } else { - number_syntax.lastIndex = 0; - var m = number_syntax.exec(str.slice(i)); - if (m == null) { - throw BadSyntax(this._thisDoc, this.lines, str, i, "Bad number or date syntax"); - } - j = i + number_syntax.lastIndex; - var val = str.slice(i, j); - if (val.indexOf("e") >= 0) { - res.push(this._store.literal(parseFloat(val), this._store.sym(FLOAT_DATATYPE))); - } else if (str.slice(i, j).indexOf(".") >= 0) { - res.push(this._store.literal(parseFloat(val), this._store.sym(DECIMAL_DATATYPE))); - } else { - res.push(this._store.literal(parseInt(val), this._store.sym(INTEGER_DATATYPE))); - } - } - ; - return j; // Where we have got up to - } +/** + * Provides a Solid client helper object (which exposes various static modules). + * @module solidUi.js + * @main solidUi.js + */ - if (str.charAt(i) == "\"") { - if (str.slice(i, i + 3) == "\"\"\"") { - var delim = "\"\"\""; - } else { - var delim = "\""; - } - var i = i + pyjslib_len(delim); - var dt = null; - var pairFudge = this.strconst(str, i, delim); - var j = pairFudge[0]; - var s = pairFudge[1]; - var lang = null; - if (str.slice(j, j + 1) == "@") { - langcode.lastIndex = 0; - var m = langcode.exec(str.slice(j + 1)); - if (m == null) { - throw BadSyntax(this._thisDoc, startline, str, i, "Bad language code syntax on string literal, after @"); - } - var i = langcode.lastIndex + j + 1; - var lang = str.slice(j + 1, i); - var j = i; - } - if (str.slice(j, j + 2) == "^^") { - var res2 = new pyjslib_List([]); - var j = this.uri_ref2(str, j + 2, res2); - var dt = res2[0]; - } - res.push(this._store.literal(s, lang || dt)); - return j; - } else { - return -1; - } - } - } - }, { - key: "strconst", - value: function strconst(str, i, delim) { - /* - parse an N3 string constant delimited by delim. - return index, val - */ +/** + * @class SolidUi + * @static + */ - var j = i; - var ustr = ""; - var startline = this.lines; - while (j < pyjslib_len(str)) { - var i = j + pyjslib_len(delim); - if (str.slice(j, i) == delim) { - return new pyjslib_Tuple([i, ustr]); - } - if (str.charAt(j) == "\"") { - var ustr = ustr + "\""; - var j = j + 1; - continue; - } - interesting.lastIndex = 0; - var m = interesting.exec(str.slice(j)); - if (!m) { - throw BadSyntax(this._thisDoc, startline, str, j, "Closing quote missing in string at ^ in " + str.slice(j - 20, j) + "^" + str.slice(j, j + 20)); - } - var i = j + interesting.lastIndex - 1; - var ustr = ustr + str.slice(j, i); - var ch = str.charAt(i); - if (ch == "\"") { - var j = i; - continue; - } else if (ch == "\r") { - var j = i + 1; - continue; - } else if (ch == "\n") { - if (delim == "\"") { - throw BadSyntax(this._thisDoc, startline, str, i, "newline found in string literal"); - } - this.lines = this.lines + 1; - var ustr = ustr + ch; - var j = i + 1; - this.previousLine = this.startOfLine; - this.startOfLine = j; - } else if (ch == "\\") { - var j = i + 1; - var ch = str.slice(j, j + 1); - if (!ch) { - throw BadSyntax(this._thisDoc, startline, str, i, "unterminated string literal (2)"); - } - var k = string_find("abfrtvn\\\"", ch); - if (k >= 0) { - var uch = "\a\b\f\r\t\v\n\\\"".charAt(k); - var ustr = ustr + uch; - var j = j + 1; - } else if (ch == "u") { - var pairFudge = this.uEscape(str, j + 1, startline); - var j = pairFudge[0]; - var ch = pairFudge[1]; - var ustr = ustr + ch; - } else if (ch == "U") { - var pairFudge = this.UEscape(str, j + 1, startline); - var j = pairFudge[0]; - var ch = pairFudge[1]; - var ustr = ustr + ch; - } else { - throw BadSyntax(this._thisDoc, this.lines, str, i, "bad escape"); - } - } - } - throw BadSyntax(this._thisDoc, this.lines, str, i, "unterminated string literal"); - } - }, { - key: "uEscape", - value: function uEscape(str, i, startline) { - var j = i; - var count = 0; - var value = 0; - while (count < 4) { - var chFudge = str.slice(j, j + 1); - var ch = chFudge.toLowerCase(); - var j = j + 1; - if (ch == "") { - throw BadSyntax(this._thisDoc, startline, str, i, "unterminated string literal(3)"); - } - var k = string_find("0123456789abcdef", ch); - if (k < 0) { - throw BadSyntax(this._thisDoc, startline, str, i, "bad string literal hex escape"); - } - var value = value * 16 + k; - var count = count + 1; - } - var uch = String.fromCharCode(value); - return new pyjslib_Tuple([j, uch]); - } - }, { - key: "UEscape", - value: function UEscape(str, i, startline) { - var j = i; - var count = 0; - var value = "\\U"; - while (count < 8) { - var chFudge = str.slice(j, j + 1); - var ch = chFudge.toLowerCase(); - var j = j + 1; - if (ch == "") { - throw BadSyntax(this._thisDoc, startline, str, i, "unterminated string literal(3)"); - } - var k = string_find("0123456789abcdef", ch); - if (k < 0) { - throw BadSyntax(this._thisDoc, startline, str, i, "bad string literal hex escape"); - } - var value = value + ch; - var count = count + 1; - } - var uch = stringFromCharCode("0x" + pyjslib_slice(value, 2, 10) - 0); - return new pyjslib_Tuple([j, uch]); - } - }]); - return SinkParser; -}(); -function OLD_BadSyntax(uri, lines, str, i, why) { - return new __OLD_BadSyntax(uri, lines, str, i, why); -} -function __OLD_BadSyntax(uri, lines, str, i, why) { - this._str = str.encode("utf-8"); - this._str = str; - this._i = i; - this._why = why; - this.lines = lines; - this._uri = uri; -} -__OLD_BadSyntax.prototype.toString = function () { - var str = this._str; - var i = this._i; - var st = 0; - if (i > 60) { - var pre = "..."; - var st = i - 60; - } else { - var pre = ""; +// REMOVE @ts-ignore as you migrate files to TypeScript +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "acl", ({ + enumerable: true, + get: function get() { + return _index.acl; } - if (pyjslib_len(str) - i > 60) { - var post = "..."; - } else { - var post = ""; +})); +Object.defineProperty(exports, "aclControl", ({ + enumerable: true, + get: function get() { + return _index.aclControl; } - return "Line %i of <%s>: Bad syntax (%s) at ^ in:\n\"%s%s^%s%s\"" % new pyjslib_Tuple([this.lines + 1, this._uri, this._why, pre, str.slice(st, i), str.slice(i, i + 60), post]); -}; -function BadSyntax(uri, lines, str, i, why) { - var lineNo = lines + 1; - var msg = "Line " + lineNo + " of <" + uri + ">: Bad syntax: " + why + "\nat: \"" + str.slice(i, i + 30) + "\""; - var e = new SyntaxError(msg, uri, lineNo); - e.lineNo = lineNo; - e.characterInFile = i; - e.syntaxProblem = why; - return e; -} -function stripCR(str) { - var res = ""; - var __ch = new pyjslib_Iterator(str); - try { - while (true) { - var ch = __ch.next(); - if (ch != "\r") { - var res = res + ch; - } - } - } catch (e) { - if (e != StopIteration) { - throw e; - } +})); +Object.defineProperty(exports, "authn", ({ + enumerable: true, + get: function get() { + return _solidLogic.authn; } - return res; +})); +Object.defineProperty(exports, "create", ({ + enumerable: true, + get: function get() { + return _index2.create; + } +})); +exports.dom = exports.createTypes = void 0; +Object.defineProperty(exports, "icons", ({ + enumerable: true, + get: function get() { + return _iconBase.icons; + } +})); +Object.defineProperty(exports, "infiniteMessageArea", ({ + enumerable: true, + get: function get() { + return _infinite.infiniteMessageArea; + } +})); +Object.defineProperty(exports, "initFooter", ({ + enumerable: true, + get: function get() { + return _footer.initFooter; + } +})); +Object.defineProperty(exports, "initHeader", ({ + enumerable: true, + get: function get() { + return _header.initHeader; + } +})); +exports.login = exports.log = exports.language = void 0; +Object.defineProperty(exports, "matrix", ({ + enumerable: true, + get: function get() { + return _index3.matrix; + } +})); +Object.defineProperty(exports, "media", ({ + enumerable: true, + get: function get() { + return _index4.media; + } +})); +Object.defineProperty(exports, "messageArea", ({ + enumerable: true, + get: function get() { + return _messageArea.messageArea; + } +})); +exports.rdf = exports.preferences = exports.participation = exports.pad = exports.ns = void 0; +Object.defineProperty(exports, "store", ({ + enumerable: true, + get: function get() { + return _solidLogic.store; + } +})); +exports.style = void 0; +Object.defineProperty(exports, "table", ({ + enumerable: true, + get: function get() { + return _table.renderTableViewPane; + } +})); +exports.utils = exports.tabs = void 0; +Object.defineProperty(exports, "versionInfo", ({ + enumerable: true, + get: function get() { + return _versionInfo.versionInfo; + } +})); +exports.widgets = void 0; +var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); +exports.rdf = rdf; +var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); +exports.ns = ns; +var _index = __webpack_require__(/*! ./acl/index */ "./lib/acl/index.js"); +var _index2 = __webpack_require__(/*! ./create/index */ "./lib/create/index.js"); +var _iconBase = __webpack_require__(/*! ./iconBase */ "./lib/iconBase.js"); +var language = _interopRequireWildcard(__webpack_require__(/*! ./widgets/forms/autocomplete/language */ "./lib/widgets/forms/autocomplete/language.js")); +exports.language = language; +var log = _interopRequireWildcard(__webpack_require__(/*! ./log */ "./lib/log.js")); +exports.log = log; +var _index3 = __webpack_require__(/*! ./matrix/index */ "./lib/matrix/index.js"); +var _index4 = __webpack_require__(/*! ./media/index */ "./lib/media/index.js"); +var _messageArea = __webpack_require__(/*! ./messageArea */ "./lib/messageArea.js"); +var _infinite = __webpack_require__(/*! ./chat/infinite */ "./lib/chat/infinite.js"); +var pad = _interopRequireWildcard(__webpack_require__(/*! ./pad */ "./lib/pad.js")); +exports.pad = pad; +var participation = _interopRequireWildcard(__webpack_require__(/*! ./participation */ "./lib/participation.js")); +exports.participation = participation; +var preferences = _interopRequireWildcard(__webpack_require__(/*! ./preferences */ "./lib/preferences.js")); +exports.preferences = preferences; +var style = _interopRequireWildcard(__webpack_require__(/*! ./style */ "./lib/style.js")); +exports.style = style; +var _table = __webpack_require__(/*! ./table */ "./lib/table.js"); +var tabs = _interopRequireWildcard(__webpack_require__(/*! ./tabs */ "./lib/tabs.js")); +exports.tabs = tabs; +var utils = _interopRequireWildcard(__webpack_require__(/*! ./utils */ "./lib/utils/index.js")); +exports.utils = utils; +var login = _interopRequireWildcard(__webpack_require__(/*! ./login/login */ "./lib/login/login.js")); +exports.login = login; +var widgets = _interopRequireWildcard(__webpack_require__(/*! ./widgets/index */ "./lib/widgets/index.js")); +exports.widgets = widgets; +var _versionInfo = __webpack_require__(/*! ./versionInfo */ "./lib/versionInfo.js"); +var _header = __webpack_require__(/*! ./header */ "./lib/header/index.js"); +var _footer = __webpack_require__(/*! ./footer */ "./lib/footer/index.js"); +var createTypes = _interopRequireWildcard(__webpack_require__(/*! ./create/types */ "./lib/create/types.js")); +exports.createTypes = createTypes; +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +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); } +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; } +// pull in first avoid cross-refs +// @ts-ignore +// @ts-ignore +// @ts-ignore +// @ts-ignore +// @ts-ignore +// @ts-ignore +// @ts-ignore +// @ts-ignore +// @ts-ignore +// @ts-ignore +var dom = window ? window.document : null; // Idea that UI.dom can be adapted in non-browser environments +exports.dom = dom; +if (typeof window !== 'undefined') { + ; + window.UI = { + authn: _solidLogic.authn, + store: _solidLogic.store, + ns: ns, + rdf: rdf, + acl: _index.acl, + aclControl: _index.aclControl, + create: _index2.create, + createTypes: createTypes, + dom: dom, + icons: _iconBase.icons, + language: language, + log: log, + login: login, + matrix: _index3.matrix, + media: _index4.media, + messageArea: _messageArea.messageArea, + infiniteMessageArea: _infinite.infiniteMessageArea, + pad: pad, + participation: participation, + preferences: preferences, + style: style, + table: _table.renderTableViewPane, + tabs: tabs, + utils: utils, + widgets: widgets, + versionInfo: _versionInfo.versionInfo, + initHeader: _header.initHeader, + initFooter: _footer.initFooter + }; // Simpler access by non-node scripts } -function dummyWrite(x) {} + +// this variables are directly used in the storybook +//# sourceMappingURL=index.js.map /***/ }), -/***/ "../rdflib/esm/named-node.js": -/*!***********************************!*\ - !*** ../rdflib/esm/named-node.js ***! - \***********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./lib/log.js": +/*!********************!*\ + !*** ./lib/log.js ***! + \********************/ +/***/ ((__unused_webpack_module, exports) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ NamedNode) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/termValue */ "../rdflib/esm/utils/termValue.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); - +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.LogLevel = void 0; +exports.alert = alert; +exports.clear = clear; +exports.debug = debug; +exports.dumpHTML = dumpHTML; +exports.error = error; +exports.escapeForXML = escapeForXML; +exports.info = info; +exports.logAscending = logAscending; +exports.logDescending = logDescending; +exports.msg = msg; +exports.setInternals = setInternals; +exports.setLevel = setLevel; +exports.success = success; +exports.warn = warn; +// /////////////////////// Logging +// +// bitmask levels +// const TNONE = 0 +/** @internal */ +var TERROR = 1; +/** @internal */ +var TWARN = 2; +/** @internal */ +var TMESG = 4; +/** @internal */ +var TSUCCESS = 8; +/** @internal */ +var TINFO = 16; +/** @internal */ +var TDEBUG = 32; +/** @internal */ +var TALL = 63; +/** @internal */ +var LogLevel; +/** @internal */ +exports.LogLevel = LogLevel; +(function (LogLevel) { + LogLevel[LogLevel["Error"] = 1] = "Error"; + LogLevel[LogLevel["Warning"] = 2] = "Warning"; + LogLevel[LogLevel["Message"] = 4] = "Message"; + LogLevel[LogLevel["Success"] = 8] = "Success"; + LogLevel[LogLevel["Info"] = 16] = "Info"; + LogLevel[LogLevel["Debug"] = 32] = "Debug"; + LogLevel[LogLevel["All"] = 63] = "All"; +})(LogLevel || (exports.LogLevel = LogLevel = {})); +var _level = TERROR + TWARN + TMESG; +/** @internal */ +var _ascending = false; +/** @internal */ +var _dom = document; // must be able to override for tests +/** @internal */ +var _window = window; // must be able to override for tests +/** @internal */ +function log(str) { + var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : TMESG; + var typestr = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'mesg'; + if (!(_level & type)) return; // bitmask + if (typeof _dom !== 'undefined') { + var logArea = _dom.getElementById('status'); + if (!logArea) return; + var addendum = _dom.createElement('span'); + addendum.setAttribute('class', typestr); + var now = new Date(); + addendum.innerHTML = "".concat(now.getHours(), ":").concat(now.getMinutes(), ":").concat(now.getSeconds(), " [").concat(typestr, "] ").concat(escapeForXML(str), "
"); + if (_ascending) { + logArea.insertBefore(addendum, logArea.firstChild); + } else { + logArea.appendChild(addendum); + } + } else if (typeof console !== 'undefined') { + // eslint-disable-next-line no-console + console.log(str); + } +} -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +/** + * Adds a message to the element with id "status". The messages are prepended with + * time and type of message, in this case [mesg]. + */ +function msg(message) { + log(message); +} +/** + * Adds a warning message to the element with id "status". The messages are + * prepended with time and type of message, in this case [warn]. + */ +function warn(message) { + log(message, TWARN, 'warn'); +} +/** + * Adds a debugging message to the element with id "status". The messages are + * prepended with time and type of message, in this case [dbug]. + */ +function debug(message) { + log(message, TDEBUG, 'dbug'); +} +/** + * Adds a info message to the element with id "status". The messages are + * prepended with time and type of message, in this case [info]. + */ +function info(message) { + log(message, TINFO, 'info'); +} +/** + * Adds a error to the element with id "status". The messages are + * prepended with time and type of message, in this case [eror]. + */ +function error(message) { + log(message, TERROR, 'eror'); +} +/** + * Adds a success message to the element with id "status". The messages are + * prepended with time and type of message, in this case [good]. + */ +function success(message) { + log(message, TSUCCESS, 'good'); +} /** - * A named (IRI) RDF node + * Uses the global alert to send an alert. If global alert is not available, it + * will output the message using the method [[warning]]s. */ -var NamedNode = /*#__PURE__*/function (_Node) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(NamedNode, _Node); - var _super = _createSuper(NamedNode); - /** - * Create a named (IRI) RDF Node - * @constructor - * @param iri - The IRI for this node - */ - function NamedNode(iri) { - var _this; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, NamedNode); - _this = _super.call(this, (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_7__.termValue)(iri)); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_8__.NamedNodeTermType); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_9__["default"].NamedNode); - if (!_this.value) { - throw new Error('Missing IRI for NamedNode'); - } - if (!_this.value.includes(':')) { - throw new Error('NamedNode IRI "' + iri + '" must be absolute.'); - } - if (_this.value.includes(' ')) { - var message = 'Error: NamedNode IRI "' + iri + '" must not contain unencoded spaces.'; - throw new Error(message); - } - return _this; +function alert(message) { + if (_window && typeof _window.alert !== 'undefined') { + _window.alert(message); + } else { + warn(message); } +} - /** - * Returns an $rdf node for the containing directory, ending in slash. - */ - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(NamedNode, [{ - key: "dir", - value: function dir() { - var str = this.value.split('#')[0]; - var p = str.slice(0, -1).lastIndexOf('/'); - var q = str.indexOf('//'); - if (q >= 0 && p < q + 2 || p < 0) return null; - return new NamedNode(str.slice(0, p + 1)); - } +/** + * Will clear the content of the element with id "status". + */ +function clear() { + var _dom2; + var logArea = (_dom2 = _dom) === null || _dom2 === void 0 ? void 0 : _dom2.getElementById('status'); + if (!logArea) return; + logArea.innerHTML = ''; +} - /** - * Returns an NN for the whole web site, ending in slash. - * Contrast with the "origin" which does NOT have a trailing slash - */ - }, { - key: "site", - value: function site() { - var str = this.value.split('#')[0]; - var p = str.indexOf('//'); - if (p < 0) throw new Error('This URI does not have a web site part (origin)'); - var q = str.indexOf('/', p + 2); - if (q < 0) { - return new NamedNode(str.slice(0) + '/'); // Add slash to a bare origin - } else { - return new NamedNode(str.slice(0, q + 1)); - } - } +/** + * Lets you configure which types of messages will be shown. The module uses + * [bitmask](https://en.wikipedia.org/wiki/Mask_(computing)) to filter which + * types of messages should be shown. E.g. if you only want warning messages + * to be shown, pass 2 to the function, if you want warning and success to be + * shown, pass 10 (2+8). By passing the sum of all, 63, you'll show all + * types of messages. + * + * - Error: 1 + * - Warning: 2 + * - Message: 4 + * - Success: 8 + * - Info: 16 + * - Debug: 32 + */ +function setLevel(level) { + _level = TALL; + debug('Log level is now ' + level); + _level = level; +} - /** - * Creates the fetchable named node for the document. - * Removes everything from the # anchor tag. - */ - }, { - key: "doc", - value: function doc() { - if (this.value.indexOf('#') < 0) { - return this; - } else { - return new NamedNode(this.value.split('#')[0]); - } - } +/** + * Will dump the current HTML using the [[debug]] method. + */ +function dumpHTML() { + var _dom3, _dom3$body; + if (!_dom) return; + var level = _level; + _level = TALL; + debug(((_dom3 = _dom) === null || _dom3 === void 0 ? void 0 : (_dom3$body = _dom3.body) === null || _dom3$body === void 0 ? void 0 : _dom3$body.innerHTML) || ''); + _level = level; +} - /** - * Returns the URI including - */ - }, { - key: "toString", - value: function toString() { - return '<' + this.value + '>'; - } +/** + * Will start prepending messages the list of log messages. + */ +function logAscending() { + _ascending = true; +} - /** The local identifier with the document */ - }, { - key: "id", - value: function id() { - return this.value.split('#')[1]; - } +/** + * Will start appending messages the list of log messages. (This is default + * behavior.) + */ +function logDescending() { + _ascending = false; +} - /** Alias for value, favored by Tim */ - }, { - key: "uri", - get: function get() { - return this.value; - }, - set: function set(uri) { - this.value = uri; - } +/** @internal */ +function escapeForXML(str) { + // can be replaced with function utils module when migrating + return str.replace(/&/g, '&').replace(//g, '>'); +} - /** - * Creates a named node from the specified input value - * @param value - An input value - */ - }], [{ - key: "fromValue", - value: function fromValue(value) { - if (typeof value === 'undefined' || value === null) { - return value; - } - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_10__.isTerm)(value)) { - return value; - } - return new NamedNode(value); - } - }]); - return NamedNode; -}(_node_internal__WEBPACK_IMPORTED_MODULE_11__["default"]); - - -/***/ }), - -/***/ "../rdflib/esm/namespace.js": -/*!**********************************!*\ - !*** ../rdflib/esm/namespace.js ***! - \**********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Namespace) -/* harmony export */ }); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); - -/** - * Gets a namespace for the specified namespace's URI - * @param nsuri - The URI for the namespace - * @param [factory] - The factory for creating named nodes with - */ -function Namespace(nsuri, factory) { - var dataFactory = factory || { - namedNode: function namedNode(value) { - return new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"](value); - } - }; - return function (ln) { - return dataFactory.namedNode(nsuri + (ln || '')); - }; -} +/** @internal */ +function setInternals(window, document) { + _window = window; + _dom = document; +} +//# sourceMappingURL=log.js.map /***/ }), -/***/ "../rdflib/esm/node-internal.js": -/*!**************************************!*\ - !*** ../rdflib/esm/node-internal.js ***! - \**************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { +/***/ "./lib/login/login.js": +/*!****************************!*\ + !*** ./lib/login/login.js ***! + \****************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Node) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.ensureLoadedPreferences = ensureLoadedPreferences; +exports.ensureLoadedProfile = ensureLoadedProfile; +exports.ensureLoggedIn = ensureLoggedIn; +exports.filterAvailablePanes = filterAvailablePanes; +exports.findAppInstances = findAppInstances; +exports.getUserRoles = getUserRoles; +exports.loginStatusBox = loginStatusBox; +exports.newAppInstance = newAppInstance; +exports.registrationControl = registrationControl; +exports.registrationList = registrationList; +exports.renderScopeHeadingRow = renderScopeHeadingRow; +exports.renderSignInPopup = renderSignInPopup; +exports.scopeLabel = scopeLabel; +exports.selectWorkspace = selectWorkspace; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var _rdflib = __webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js"); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var style = _interopRequireWildcard(__webpack_require__(/*! ../style */ "./lib/style.js")); +var _log = __webpack_require__(/*! ../log */ "./lib/log.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns.js */ "./lib/ns.js")); +var _signup = __webpack_require__(/*! ../signup/signup.js */ "./lib/signup/signup.js"); +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +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); } +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; } +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; } } }; } +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); } +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; } +var store = _solidLogic.solidLogicSingleton.store; +var _solidLogicSingleton$ = _solidLogic.solidLogicSingleton.profile, + loadPreferences = _solidLogicSingleton$.loadPreferences, + loadProfile = _solidLogicSingleton$.loadProfile; +var _solidLogicSingleton$2 = _solidLogic.solidLogicSingleton.typeIndex, + getScopedAppInstances = _solidLogicSingleton$2.getScopedAppInstances, + getRegistrations = _solidLogicSingleton$2.getRegistrations, + loadAllTypeIndexes = _solidLogicSingleton$2.loadAllTypeIndexes, + getScopedAppsFromIndex = _solidLogicSingleton$2.getScopedAppsFromIndex, + deleteTypeIndexRegistration = _solidLogicSingleton$2.deleteTypeIndexRegistration; /** - * The superclass of all RDF Statement objects, that is - * NamedNode, Literal, BlankNode, etc. - * Should not be instantiated directly. - * Also called Term. - * @link https://rdf.js.org/data-model-spec/#term-interface - * @class Node + * Resolves with the logged in user's WebID + * + * @param context */ -var Node = /*#__PURE__*/function () { - // Specified in './node.ts' to prevent circular dependency - - // Specified in './node.ts' to prevent circular dependency - - /** The type of node */ - - /** The class order for this node */ - - /** The node's value */ - - function Node(value) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Node); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "termType", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "classOrder", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "value", void 0); - this.value = value; +// used to be logIn +function ensureLoggedIn(context) { + var me = _solidLogic.authn.currentUser(); + if (me) { + _solidLogic.authn.saveUser(me, context); + return Promise.resolve(context); } - - /** - * Creates the substituted node for this one, according to the specified bindings - * @param bindings - Bindings of identifiers to nodes - */ - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Node, [{ - key: "substitute", - value: function substitute(bindings) { - return this; - } - - /** - * Compares this node with another - * @see {equals} to check if two nodes are equal - * @param other - The other node - */ - }, { - key: "compareTerm", - value: function compareTerm(other) { - if (this.classOrder < other.classOrder) { - return -1; - } - if (this.classOrder > other.classOrder) { - return +1; - } - if (this.value < other.value) { - return -1; - } - if (this.value > other.value) { - return +1; + return new Promise(function (resolve) { + _solidLogic.authn.checkUser().then(function (webId) { + // Already logged in? + if (webId) { + debug.log("logIn: Already logged in as ".concat(webId)); + return resolve(context); } - return 0; - } - - /** - * Compares whether the two nodes are equal - * @param other The other node - */ - }, { - key: "equals", - value: function equals(other) { - if (!other) { - return false; + if (!context.div || !context.dom) { + return resolve(context); } - return this.termType === other.termType && this.value === other.value; - } - - /** - * Creates a hash for this node - * @deprecated use {rdfFactory.id} instead if possible - */ - }, { - key: "hashString", - value: function hashString() { - return this.toCanonical(); - } - - /** - * Compares whether this node is the same as the other one - * @param other - Another node - */ - }, { - key: "sameTerm", - value: function sameTerm(other) { - return this.equals(other); - } - - /** - * Creates a canonical string representation of this node - */ - }, { - key: "toCanonical", - value: function toCanonical() { - return this.toNT(); - } - - /** - * Creates a n-triples string representation of this node - */ - }, { - key: "toNT", - value: function toNT() { - return this.toString(); - } - - /** - * Creates a n-quads string representation of this node - */ - }, { - key: "toNQ", - value: function toNQ() { - return this.toNT(); - } - - /** - * Creates a string representation of this node - */ - }, { - key: "toString", - value: function toString() { - throw new Error('Node.toString() is abstract - see the subclasses instead'); - } - }]); - return Node; -}(); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(Node, "fromValue", void 0); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(Node, "toJS", void 0); - - -/***/ }), - -/***/ "../rdflib/esm/node.js": -/*!*****************************!*\ - !*** ../rdflib/esm/node.js ***! - \*****************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./collection */ "../rdflib/esm/collection.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); -// This file attaches all functionality to Node -// that would otherwise require circular dependencies. - - - + var box = loginStatusBox(context.dom, function (webIdUri) { + _solidLogic.authn.saveUser(webIdUri, context); + resolve(context); // always pass growing context + }); -/** - * Creates an RDF Node from a native javascript value. - * RDF Nodes are returned unchanged, undefined returned as itself. - * @method fromValue - * @static - * @param value {Node|Date|String|Number|Boolean|Undefined} - * @return {Node|Collection} - */ -_node_internal__WEBPACK_IMPORTED_MODULE_0__["default"].fromValue = _collection__WEBPACK_IMPORTED_MODULE_1__.fromValue; -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_internal__WEBPACK_IMPORTED_MODULE_0__["default"]); -var ns = { - xsd: (0,_namespace__WEBPACK_IMPORTED_MODULE_2__["default"])('http://www.w3.org/2001/XMLSchema#') -}; + context.div.appendChild(box); + }); + }); +} /** - * Gets the javascript object equivalent to a node - * @param term The RDF node + * Loads preference file + * Do this after having done log in and load profile + * + * @private + * + * @param context */ -_node_internal__WEBPACK_IMPORTED_MODULE_0__["default"].toJS = function (term) { - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_3__.isCollection)(term)) { - return term.elements.map(_node_internal__WEBPACK_IMPORTED_MODULE_0__["default"].toJS); // Array node (not standard RDFJS) - } - - if (!(0,_utils_terms__WEBPACK_IMPORTED_MODULE_3__.isLiteral)(term)) return term; - if (term.datatype.equals(ns.xsd('boolean'))) { - return term.value === '1' || term.value === 'true'; - } - if (term.datatype.equals(ns.xsd('dateTime')) || term.datatype.equals(ns.xsd('date'))) { - return new Date(term.value); - } - if (term.datatype.equals(ns.xsd('integer')) || term.datatype.equals(ns.xsd('float')) || term.datatype.equals(ns.xsd('decimal'))) { - return Number(term.value); - } - return term.value; -}; - -/***/ }), - -/***/ "../rdflib/esm/parse.js": -/*!******************************!*\ - !*** ../rdflib/esm/parse.js ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ parse) -/* harmony export */ }); -/* harmony import */ var _factories_extended_term_factory__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./factories/extended-term-factory */ "../rdflib/esm/factories/extended-term-factory.js"); -/* harmony import */ var _jsonldparser__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./jsonldparser */ "../rdflib/esm/jsonldparser.js"); -/* harmony import */ var n3__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! n3 */ "../rdflib/node_modules/n3/src/N3Parser.js"); -/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./n3parser */ "../rdflib/esm/n3parser.js"); -/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rdfaparser */ "../rdflib/esm/rdfaparser.js"); -/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./rdfxmlparser */ "../rdflib/esm/rdfxmlparser.js"); -/* harmony import */ var _patch_parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./patch-parser */ "../rdflib/esm/patch-parser.js"); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); - - -// @ts-ignore is this injected? - // @@ Goal: remove this dependency - - - - - - +// used to be logInLoadPreferences +function ensureLoadedPreferences(_x) { + return _ensureLoadedPreferences.apply(this, arguments); +} /** - * Parse a string and put the result into the graph kb. - * Normal method is sync. - * Unfortunately jsdonld is currently written to need to be called async. - * Hence the mess below with executeCallback. - * @param str - The input string to parse - * @param kb - The store to use - * @param base - The base URI to use - * @param contentType - The MIME content type string for the input - defaults to text/turtle - * @param [callback] - The callback to call when the data has been loaded + * Logs the user in and loads their WebID profile document into the store + * + * @param context + * + * @returns Resolves with the context after login / fetch */ -function parse(str, kb, base) { - var contentType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'text/turtle'; - var callback = arguments.length > 4 ? arguments[4] : undefined; - contentType = contentType || _types__WEBPACK_IMPORTED_MODULE_0__.TurtleContentType; - contentType = contentType.split(';')[0]; - try { - if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.N3ContentType || contentType === _types__WEBPACK_IMPORTED_MODULE_0__.TurtleContentType) { - var p = (0,_n3parser__WEBPACK_IMPORTED_MODULE_1__["default"])(kb, kb, base, base, null, null, '', null); - p.loadBuf(str); - executeCallback(); - } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.RDFXMLContentType) { - var parser = new _rdfxmlparser__WEBPACK_IMPORTED_MODULE_2__["default"](kb); - parser.parse(_utils_js__WEBPACK_IMPORTED_MODULE_3__.parseXML(str), base, kb.sym(base)); - executeCallback(); - } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.XHTMLContentType) { - (0,_rdfaparser__WEBPACK_IMPORTED_MODULE_4__.parseRDFaDOM)(_utils_js__WEBPACK_IMPORTED_MODULE_3__.parseXML(str, { - contentType: _types__WEBPACK_IMPORTED_MODULE_0__.XHTMLContentType - }), kb, base); - executeCallback(); - } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.HTMLContentType) { - (0,_rdfaparser__WEBPACK_IMPORTED_MODULE_4__.parseRDFaDOM)(_utils_js__WEBPACK_IMPORTED_MODULE_3__.parseXML(str, { - contentType: _types__WEBPACK_IMPORTED_MODULE_0__.HTMLContentType - }), kb, base); - executeCallback(); - } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.SPARQLUpdateContentType || contentType === _types__WEBPACK_IMPORTED_MODULE_0__.SPARQLUpdateSingleMatchContentType) { - // @@ we handle a subset - (0,_patch_parser__WEBPACK_IMPORTED_MODULE_5__["default"])(str, kb, base); - executeCallback(); - } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.JSONLDContentType) { - (0,_jsonldparser__WEBPACK_IMPORTED_MODULE_6__["default"])(str, kb, base, executeCallback); - } else if (contentType === _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsContentType || contentType === _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsAltContentType) { - var n3Parser = new n3__WEBPACK_IMPORTED_MODULE_7__["default"]({ - factory: _factories_extended_term_factory__WEBPACK_IMPORTED_MODULE_8__["default"] - }); - nquadCallback(null, str); - } else if (contentType === undefined) { - throw new Error("contentType is undefined"); - } else { - throw new Error("Don't know how to parse " + contentType + ' yet'); - } - } catch (e) { - // @ts-ignore - executeErrorCallback(e); - } - parse.handled = { - 'text/n3': true, - 'text/turtle': true, - 'application/rdf+xml': true, - 'application/xhtml+xml': true, - 'text/html': true, - 'application/sparql-update': true, - 'application/sparql-update-single-match': true, - 'application/ld+json': true, - 'application/nquads': true, - 'application/n-quads': true - }; - function executeCallback() { - if (callback) { - callback(null, kb); - } else { - return; - } - } - function executeErrorCallback(e) { - if ( - // TODO: Always true, what is the right behavior - contentType !== _types__WEBPACK_IMPORTED_MODULE_0__.JSONLDContentType || - // @ts-ignore always true? - contentType !== _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsContentType || - // @ts-ignore always true? - contentType !== _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsAltContentType) { - if (callback) { - callback(e, kb); - } else { - var e2 = new Error('' + e + ' while trying to parse <' + base + '> as ' + contentType); - //@ts-ignore .cause is not a default error property - e2.cause = e; - throw e2; - } - } - } - /* - function setJsonLdBase (doc, base) { - if (doc instanceof Array) { - return +// used to be logInLoadProfile +function _ensureLoadedPreferences() { + _ensureLoadedPreferences = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(context) { + var statusArea, progressDisplay, complain, preferencesFile, m2; + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) switch (_context4.prev = _context4.next) { + case 0: + complain = function _complain(message) { + message = "ensureLoadedPreferences: ".concat(message); + if (statusArea) { + // statusArea.innerHTML = '' + statusArea.appendChild(widgets.errorMessageBlock(context.dom, message)); + } + debug.log(message); + // reject(new Error(message)) + }; + if (!context.preferencesFile) { + _context4.next = 3; + break; + } + return _context4.abrupt("return", Promise.resolve(context)); + case 3: + // already done + statusArea = context.statusArea || context.div || null; + _context4.prev = 4; + _context4.next = 7; + return ensureLoadedProfile(context); + case 7: + context = _context4.sent; + _context4.next = 10; + return loadPreferences(context.me); + case 10: + preferencesFile = _context4.sent; + if (progressDisplay) { + progressDisplay.parentNode.removeChild(progressDisplay); + } + context.preferencesFile = preferencesFile; + _context4.next = 51; + break; + case 15: + _context4.prev = 15; + _context4.t0 = _context4["catch"](4); + if (!(_context4.t0 instanceof _solidLogic.UnauthorizedError)) { + _context4.next = 22; + break; + } + m2 = 'Ooops - you are not authenticated (properly logged in) to for me to read your preference file. Try loggin out and logging in?'; + (0, _log.alert)(m2); + _context4.next = 51; + break; + case 22: + if (!(_context4.t0 instanceof _solidLogic.CrossOriginForbiddenError)) { + _context4.next = 28; + break; + } + m2 = "Unauthorized: Assuming preference file blocked for origin ".concat(window.location.origin); + context.preferencesFileError = m2; + return _context4.abrupt("return", context); + case 28: + if (!(_context4.t0 instanceof _solidLogic.SameOriginForbiddenError)) { + _context4.next = 34; + break; + } + m2 = 'You are not authorized to read your preference file. This may be because you are using an untrusted web app.'; + debug.warn(m2); + return _context4.abrupt("return", context); + case 34: + if (!(_context4.t0 instanceof _solidLogic.NotEditableError)) { + _context4.next = 40; + break; + } + m2 = 'You are not authorized to edit your preference file. This may be because you are using an untrusted web app.'; + debug.warn(m2); + return _context4.abrupt("return", context); + case 40: + if (!(_context4.t0 instanceof _solidLogic.WebOperationError)) { + _context4.next = 45; + break; + } + m2 = 'You are not authorized to edit your preference file. This may be because you are using an untrusted web app.'; + debug.warn(m2); + _context4.next = 51; + break; + case 45: + if (!(_context4.t0 instanceof _solidLogic.FetchError)) { + _context4.next = 50; + break; + } + m2 = "Strange: Error ".concat(_context4.t0.status, " trying to read your preference file.").concat(_context4.t0.message); + (0, _log.alert)(m2); + _context4.next = 51; + break; + case 50: + throw new Error("(via loadPrefs) ".concat(_context4.t0)); + case 51: + return _context4.abrupt("return", context); + case 52: + case "end": + return _context4.stop(); } - if (!('@context' in doc)) { - doc['@context'] = {} - } - doc['@context']['@base'] = base - } - */ - function nquadCallback(err, nquads) { - if (err) { - callback(err, kb); - } - try { - n3Parser.parse(nquads, tripleCallback); - } catch (err) { - callback(err, kb); - } - } - function tripleCallback(err, triple) { - if (triple) { - kb.add(triple.subject, triple.predicate, triple.object, triple.graph); - } else { - callback(err, kb); - } - } + }, _callee4, null, [[4, 15]]); + })); + return _ensureLoadedPreferences.apply(this, arguments); } - -/***/ }), - -/***/ "../rdflib/esm/patch-parser.js": -/*!*************************************!*\ - !*** ../rdflib/esm/patch-parser.js ***! - \*************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ sparqlUpdateParser) -/* harmony export */ }); -/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./n3parser */ "../rdflib/esm/n3parser.js"); -/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); -// Parse a simple SPARL-Update subset syntax for patches. -// -// This parses -// WHERE {xxx} DELETE {yyy} INSERT DATA {zzz} -// (not necessarily in that order) -// as though it were the n3 -// <#query> patch:where {xxx}; patch:delete {yyy}; patch:insert {zzz}. - - -function sparqlUpdateParser(str, kb, base) { - var i, j, k; - var keywords = ['INSERT', 'DELETE', 'WHERE']; - var SQNS = (0,_namespace__WEBPACK_IMPORTED_MODULE_0__["default"])('http://www.w3.org/ns/pim/patch#'); - var p = (0,_n3parser__WEBPACK_IMPORTED_MODULE_1__["default"])(kb, kb, base, base, null, null, '', null); - var clauses = {}; - var badSyntax = function badSyntax(uri, lines, str, i, why) { - return 'Line ' + (lines + 1) + ' of <' + uri + '>: Bad syntax:\n ' + why + '\n at: "' + str.slice(i, i + 30) + '"'; - }; - - // var check = function (next, last, message) { - // if (next < 0) { - // throw badSyntax(p._thisDoc, p.lines, str, j, last, message) - // } - // return next - // } - i = 0; - var query = kb.sym(base + '#query'); // Invent a URI for the query - clauses['query'] = query; // A way of accessing it in its N3 model. - - while (true) { - // console.log("A Now at i = " + i) - j = p.skipSpace(str, i); - if (j < 0) { - return clauses; - } - // console.log("B After space at j= " + j) - if (str[j] === ';') { - i = p.skipSpace(str, j + 1); - if (i < 0) { - return clauses; // Allow end in a - } - - j = i; - } - var found = false; - for (k = 0; k < keywords.length; k++) { - var key = keywords[k]; - if (str.slice(j, j + key.length) === key) { - i = p.skipSpace(str, j + key.length); - if (i < 0) { - throw badSyntax(p._thisDoc, p.lines, str, j + key.length, 'found EOF, needed {...} after ' + key); - } - if ((key === 'INSERT' || key === 'DELETE') && str.slice(i, i + 4) === 'DATA') { - // Some wanted 'DATA'. Whatever - j = p.skipSpace(str, i + 4); - if (j < 0) { - throw badSyntax(p._thisDoc, p.lines, str, i + 4, 'needed {...} after INSERT DATA ' + key); +function ensureLoadedProfile(_x2) { + return _ensureLoadedProfile.apply(this, arguments); +} +/** + * Returns promise of context with arrays of symbols + * + * leaving the `isPublic` param undefined will bring in community index things, too + */ +function _ensureLoadedProfile() { + _ensureLoadedProfile = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(context) { + var logInContext; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) switch (_context5.prev = _context5.next) { + case 0: + if (!context.publicProfile) { + _context5.next = 2; + break; } - i = j; - } - var res2 = []; - j = p.node(str, i, res2); // Parse all the complexity of the clause - - if (j < 0) { - throw badSyntax(p._thisDoc, p.lines, str, i, 'bad syntax or EOF in {...} after ' + key); - } - clauses[key.toLowerCase()] = res2[0]; - kb.add(query, SQNS(key.toLowerCase()), res2[0]); // , kb.sym(base) - // key is the keyword and res2 has the contents - found = true; - i = j; + return _context5.abrupt("return", context); + case 2: + _context5.prev = 2; + _context5.next = 5; + return ensureLoggedIn(context); + case 5: + logInContext = _context5.sent; + if (logInContext.me) { + _context5.next = 8; + break; + } + throw new Error('Could not log in'); + case 8: + _context5.next = 10; + return loadProfile(logInContext.me); + case 10: + context.publicProfile = _context5.sent; + _context5.next = 17; + break; + case 13: + _context5.prev = 13; + _context5.t0 = _context5["catch"](2); + if (context.div && context.dom) { + context.div.appendChild(widgets.errorMessageBlock(context.dom, _context5.t0.message)); + } + throw new Error("Can't log in: ".concat(_context5.t0)); + case 17: + return _context5.abrupt("return", context); + case 18: + case "end": + return _context5.stop(); } - } - if (!found && str.slice(j, j + 7) === '@prefix') { - i = p.directive(str, j); - if (i < 0) { - throw badSyntax(p._thisDoc, p.lines, str, i, 'bad syntax or EOF after @prefix '); + }, _callee5, null, [[2, 13]]); + })); + return _ensureLoadedProfile.apply(this, arguments); +} +function findAppInstances(_x3, _x4, _x5) { + return _findAppInstances.apply(this, arguments); +} +function _findAppInstances() { + _findAppInstances = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(context, theClass, isPublic) { + var items; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) switch (_context6.prev = _context6.next) { + case 0: + if (!context.me) { + _context6.next = 6; + break; + } + _context6.next = 3; + return getScopedAppInstances(theClass, context.me); + case 3: + _context6.t0 = _context6.sent; + _context6.next = 7; + break; + case 6: + _context6.t0 = []; + case 7: + items = _context6.t0; + if (isPublic === true) { + // old API - not recommended! + items = items.filter(function (item) { + return item.scope.label === 'public'; + }); + } else if (isPublic === false) { + items = items.filter(function (item) { + return item.scope.label === 'private'; + }); + } + context.instances = items.map(function (item) { + return item.instance; + }); + return _context6.abrupt("return", context); + case 11: + case "end": + return _context6.stop(); } - // console.log("P before dot i= " + i) - i = p.checkDot(str, i); - // console.log("Q after dot i= " + i) - found = true; - } - if (!found) { - // console.log("Bad syntax " + j) - throw badSyntax(p._thisDoc, p.lines, str, j, "Unknown syntax at start of statememt: '" + str.slice(j).slice(0, 20) + "'"); - } - } // while - // return clauses + }, _callee6); + })); + return _findAppInstances.apply(this, arguments); } - -/***/ }), - -/***/ "../rdflib/esm/query-to-sparql.js": -/*!****************************************!*\ - !*** ../rdflib/esm/query-to-sparql.js ***! - \****************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ queryToSPARQL) -/* harmony export */ }); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); - -function queryToSPARQL(query) { - var indent = 0; - function getSelect(query) { - var str = addIndent() + 'SELECT '; - for (var i = 0; i < query.vars.length; i++) { - str += query.vars[i] + ' '; - } - str += '\n'; - return str; - } - function getPattern(pat) { - var str = ''; - var st = pat.statements; - for (var x in st) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Found statement: ' + st); - str += addIndent() + st[x] + '\n'; - } - return str; - } - function getConstraints(pat) { - var str = ''; - for (var v in pat.constraints) { - var foo = pat.constraints[v]; - str += addIndent() + 'FILTER ( ' + foo.describe(v) + ' ) ' + '\n'; - } - return str; - } - function getOptionals(pat) { - var str = ''; - for (var x = 0; x < pat.optional.length; x++) { - // alert(pat.optional.termType) - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Found optional query'); - str += addIndent() + 'OPTIONAL { ' + '\n'; - indent++; - str += getPattern(pat.optional[x]); - str += getConstraints(pat.optional[x]); - str += getOptionals(pat.optional[x]); - indent--; - str += addIndent() + '}' + '\n'; - } - return str; - } - function getWhere(pat) { - var str = addIndent() + 'WHERE \n' + '{ \n'; - indent++; - str += getPattern(pat); - str += getConstraints(pat); - str += getOptionals(pat); - indent--; - str += '}'; - return str; - } - function addIndent() { - var str = ''; - for (var i = 0; i < indent; i++) { - str += ' '; - } - return str; - } - function getSPARQL(query) { - return getSelect(query) + getWhere(query.pat); - } - return getSPARQL(query); +function scopeLabel(context, scope) { + var mine = context.me && context.me.sameTerm(scope.agent); + var name = mine ? '' : utils.label(scope.agent) + ' '; + return "".concat(name).concat(scope.label); } - -/***/ }), - -/***/ "../rdflib/esm/query.js": -/*!******************************!*\ - !*** ../rdflib/esm/query.js ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Query": () => (/* binding */ Query), -/* harmony export */ "indexedFormulaQuery": () => (/* binding */ indexedFormulaQuery) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./store */ "../rdflib/esm/store.js"); -/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/default-graph-uri */ "../rdflib/esm/utils/default-graph-uri.js"); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); - - -// Matching a formula against another formula -// Assync as well as Synchronously -// -// W3C open source licence 2005. -// -// This builds on term.js, match.js (and identity.js?) -// to allow a query of a formula. -// -// Here we introduce for the first time a subclass of term: variable. -// -// SVN ID: $Id: query.js 25116 2008-11-15 16:13:48Z timbl $ - -// Variable -// -// Compare with BlankNode. They are similar, but a variable -// stands for something whose value is to be returned. -// Also, users name variables and want the same name back when stuff is printed -/* jsl:option explicit */ // Turn on JavaScriptLint variable declaration checking - - - - - - /** - * Query class, for tracking queries the user has in the UI. + * UI to control registration of instance */ -var Query = /*#__PURE__*/(0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_0__["default"])(function Query(name, id) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__["default"])(this, Query); - this.pat = new _store__WEBPACK_IMPORTED_MODULE_2__["default"](); // The pattern to search for - this.vars = []; // Used by UI code but not in query.js - // this.orderBy = [] // Not used yet - this.name = name; - this.id = id; -}); - +function registrationControl(_x6, _x7, _x8) { + return _registrationControl.apply(this, arguments); +} +function _registrationControl() { + _registrationControl = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(context, instance, theClass) { + var registrationStatements, renderScopeCheckbox, dom, box, me, scopes, msg, tbody, form, _iterator, _step, scope, row; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) switch (_context7.prev = _context7.next) { + case 0: + renderScopeCheckbox = function _renderScopeCheckbox(scope) { + var statements = registrationStatements(scope.index); + var name = scopeLabel(context, scope); + var label = "".concat(name, " link to this ").concat(context.noun); + return widgets.buildCheckboxForm(context.dom, _solidLogic.solidLogicSingleton.store, label, null, statements, form, scope.index); + }; + registrationStatements = function _registrationStatemen(index) { + var registrations = getRegistrations(instance, theClass); + var reg = registrations.length ? registrations[0] : widgets.newThing(index); + return [(0, _rdflib.st)(reg, ns.solid('instance'), instance, index), (0, _rdflib.st)(reg, ns.solid('forClass'), theClass, index)]; + }; + /// / body of registrationControl + dom = context.dom; + if (!(!dom || !context.div)) { + _context7.next = 5; + break; + } + throw new Error('registrationControl: need dom and div'); + case 5: + box = dom.createElement('div'); + context.div.appendChild(box); + context.me = _solidLogic.authn.currentUser(); // @@ + me = context.me; + if (me) { + _context7.next = 12; + break; + } + box.innerHTML = '

(Log in to save a link to this)

'; + return _context7.abrupt("return", context); + case 12: + _context7.prev = 12; + _context7.next = 15; + return loadAllTypeIndexes(me); + case 15: + scopes = _context7.sent; + _context7.next = 23; + break; + case 18: + _context7.prev = 18; + _context7.t0 = _context7["catch"](12); + if (context.div && context.preferencesFileError) { + msg = '(Lists of stuff not available)'; + context.div.appendChild(dom.createElement('p')).textContent = msg; + } else if (context.div) { + msg = "registrationControl: Type indexes not available: ".concat(_context7.t0); + context.div.appendChild(widgets.errorMessageBlock(context.dom, _context7.t0)); + } + debug.log(msg); + return _context7.abrupt("return", context); + case 23: + box.innerHTML = '
'; // tbody will be inserted anyway + box.setAttribute('style', 'font-size: 120%; text-align: right; padding: 1em; border: solid gray 0.05em;'); + tbody = box.children[0].children[0]; + form = new _rdflib.BlankNode(); // @@ say for now + _iterator = _createForOfIteratorHelper(scopes); + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + scope = _step.value; + row = tbody.appendChild(dom.createElement('tr')); + row.appendChild(renderScopeCheckbox(scope)); // @@ index + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); + } + return _context7.abrupt("return", context); + case 30: + case "end": + return _context7.stop(); + } + }, _callee7, null, [[12, 18]]); + })); + return _registrationControl.apply(this, arguments); +} +function renderScopeHeadingRow(context, store, scope) { + var backgroundColor = { + "private": '#fee', + "public": '#efe' + }; + var dom = context.dom; + var name = scopeLabel(context, scope); + var row = dom.createElement('tr'); + var cell = row.appendChild(dom.createElement('td')); + cell.setAttribute('colspan', '3'); + cell.style.backgoundColor = backgroundColor[scope.label] || 'white'; + var header = cell.appendChild(dom.createElement('h3')); + header.textContent = name + ' links'; + header.style.textAlign = 'left'; + return row; +} /** - * This function will match a pattern to the current Store - * - * The callback function is called whenever a match is found - * When fetcher is supplied this will be called to load from the web - * any new nodes as they are discovered. This will cause the query to traverse the - * graph of linked data, sometimes called "Link Following Query" - * - * @param myQuery - a knowledgebase containing a pattern to use as query - * @param callback - whenever the pattern in myQuery is met this is called with - * the new bindings as parameter - * @param fetcher? - If and only if, you want link following, give a fetcher - * which has been created for the quadstore being queried. - * @param onDone - callback when query finished - */ -function indexedFormulaQuery(myQuery, callback, fetcher, onDone) { - /** Debug strings + * UI to List at all registered things */ - function bindingDebug(b) { - var str = ''; - var v; - for (v in b) { - if (b.hasOwnProperty(v)) { - str += ' ' + v + ' -> ' + b[v]; - } - } - return str; - } - function bindingsDebug(nbs) { - var str = 'Bindings: '; - var i; - var n = nbs.length; - for (i = 0; i < n; i++) { - str += bindingDebug(nbs[i][0]) + ';\n\t'; - } - return str; - } // bindingsDebug +function registrationList(_x9, _x10) { + return _registrationList.apply(this, arguments); +} // registrationList +function _registrationList() { + _registrationList = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(context, options) { + var dom, div, box, scopes, table, tbody, _iterator2, _step2, scope, headingRow, items, _iterator3, _step3, _loop; + return _regenerator["default"].wrap(function _callee9$(_context10) { + while (1) switch (_context10.prev = _context10.next) { + case 0: + dom = context.dom; + div = context.div; + box = dom.createElement('div'); + div.appendChild(box); + context.me = _solidLogic.authn.currentUser(); // @@ + if (context.me) { + _context10.next = 8; + break; + } + box.innerHTML = '

(Log in list your stuff)

'; + return _context10.abrupt("return", context); + case 8: + _context10.next = 10; + return loadAllTypeIndexes(context.me); + case 10: + scopes = _context10.sent; + // includes community indexes - /** Unification - * - * Unification finds all bindings such that when the binding is applied - * to one term it is equal to the other. - * @returns {Arrray}- a list of bindings, where a binding is an associative array - * mapping variuable to value. - */ - function unifyTerm(self, other, bindings, formula) { - var actual = bindings[self]; - if (actual === undefined) { - // Not mapped - if (self.isVar) { - var b = []; - b[self] = other; - return [[b, null]]; // Match - } - - actual = self; - } - if (!actual.complexType) { - if (formula.redirections[actual]) { - actual = formula.redirections[actual]; - } - if (formula.redirections[other]) { - other = formula.redirections[other]; - } - if (actual.equals(other) || actual.uri && actual.uri === _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_3__.defaultGraphURI) { - // Used to mean 'any graph' in a query - return [[[], null]]; - } - return []; - } - if (self instanceof Array) { - if (!(other instanceof Array)) { - return []; - } - return unifyContents(self, other, bindings); - } - throw new Error('query.js: oops - code not written yet'); - // return undefined; // for lint - no jslint objects to unreachables - // return actual.unifyContents(other, bindings) - } // unifyTerm - - function unifyContents(self, other, bindings, formula) { - var nbs2; - if (self.length !== other.length) { - return []; // no way - } - - if (!self.length) { - return [[[], null]]; // Success - } - - var nbs = unifyTerm(self[0], other[0], bindings, formula); - if (nbs.length === 0) { - return nbs; - } - var res = []; - var i; - var n = nbs.length; - var nb; - var j; - var m; - var v; - var nb2; - var bindings2; - for (i = 0; i < n; i++) { - // for each possibility from the first term - nb = nbs[i][0]; // new bindings - bindings2 = []; - for (v in nb) { - if (nb.hasOwnProperty(v)) { - bindings2[v] = nb[v]; // copy - } + // console.log('@@ registrationList ', scopes) + box.innerHTML = '
'; // tbody will be inserted anyway + box.setAttribute('style', 'font-size: 120%; text-align: right; padding: 1em; border: solid #eee 0.5em;'); + table = box.firstChild; + tbody = table.firstChild; + _iterator2 = _createForOfIteratorHelper(scopes); + _context10.prev = 16; + _iterator2.s(); + case 18: + if ((_step2 = _iterator2.n()).done) { + _context10.next = 44; + break; + } + scope = _step2.value; + // need some predicate for listing/adding agents + headingRow = renderScopeHeadingRow(context, store, scope); + tbody.appendChild(headingRow); + _context10.next = 24; + return getScopedAppsFromIndex(scope, options.type || null); + case 24: + items = _context10.sent; + // any class + if (items.length === 0) headingRow.style.display = 'none'; + // console.log(`registrationList: @@ instance items for class ${options.type || 'undefined' }:`, items) + _iterator3 = _createForOfIteratorHelper(items); + _context10.prev = 27; + _loop = /*#__PURE__*/_regenerator["default"].mark(function _loop() { + var item, row; + return _regenerator["default"].wrap(function _loop$(_context9) { + while (1) switch (_context9.prev = _context9.next) { + case 0: + item = _step3.value; + row = widgets.personTR(dom, ns.solid('instance'), item.instance, { + deleteFunction: function () { + var _deleteFunction = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8() { + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return deleteTypeIndexRegistration(item); + case 2: + tbody.removeChild(row); + case 3: + case "end": + return _context8.stop(); + } + }, _callee8); + })); + function deleteFunction() { + return _deleteFunction.apply(this, arguments); + } + return deleteFunction; + }() + }); + row.children[0].style.paddingLeft = '3em'; + tbody.appendChild(row); + case 4: + case "end": + return _context9.stop(); + } + }, _loop); + }); + _iterator3.s(); + case 30: + if ((_step3 = _iterator3.n()).done) { + _context10.next = 34; + break; + } + return _context10.delegateYield(_loop(), "t0", 32); + case 32: + _context10.next = 30; + break; + case 34: + _context10.next = 39; + break; + case 36: + _context10.prev = 36; + _context10.t1 = _context10["catch"](27); + _iterator3.e(_context10.t1); + case 39: + _context10.prev = 39; + _iterator3.f(); + return _context10.finish(39); + case 42: + _context10.next = 18; + break; + case 44: + _context10.next = 49; + break; + case 46: + _context10.prev = 46; + _context10.t2 = _context10["catch"](16); + _iterator2.e(_context10.t2); + case 49: + _context10.prev = 49; + _iterator2.f(); + return _context10.finish(49); + case 52: + return _context10.abrupt("return", context); + case 53: + case "end": + return _context10.stop(); } + }, _callee9, null, [[16, 46, 49, 52], [27, 36, 39, 42]]); + })); + return _registrationList.apply(this, arguments); +} +function getDefaultSignInButtonStyle() { + return 'padding: 1em; border-radius:0.5em; font-size: 100%;'; +} - for (v in bindings) { - if (bindings.hasOwnProperty(v)) { - bindings2[v] = bindings[v]; // copy - } - } +/** + * Bootstrapping identity + * (Called by `loginStatusBox()`) + * + * @param dom + * @param setUserCallback + * + * @returns + */ +function signInOrSignUpBox(dom, setUserCallback) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + options = options || {}; + var signInButtonStyle = options.buttonStyle || getDefaultSignInButtonStyle(); + var box = dom.createElement('div'); + var magicClassName = 'SolidSignInOrSignUpBox'; + debug.log('widgets.signInOrSignUpBox'); + box.setUserCallback = setUserCallback; + box.setAttribute('class', magicClassName); + box.setAttribute('style', 'display:flex;'); - nbs2 = unifyContents(self.slice(1), other.slice(1), bindings2, formula); - m = nbs2.length; - for (j = 0; j < m; j++) { - nb2 = nbs2[j][0]; // @@@@ no idea whether this is used or right - for (v in nb) { - if (nb.hasOwnProperty(v)) { - nb2[v] = nb[v]; + // Sign in button with PopUP + var signInPopUpButton = dom.createElement('input'); // multi + box.appendChild(signInPopUpButton); + signInPopUpButton.setAttribute('type', 'button'); + signInPopUpButton.setAttribute('value', 'Log in'); + signInPopUpButton.setAttribute('style', "".concat(signInButtonStyle, "background-color: #eef;").concat(style.headerBannerLoginInput)); + _solidLogic.authSession.onLogin(function () { + var me = _solidLogic.authn.currentUser(); + // const sessionInfo = authSession.info + // if (sessionInfo && sessionInfo.isLoggedIn) { + if (me) { + // const webIdURI = sessionInfo.webId + var webIdURI = me.uri; + // setUserCallback(webIdURI) + var divs = dom.getElementsByClassName(magicClassName); + debug.log("Logged in, ".concat(divs.length, " panels to be serviced")); + // At the same time, satisfy all the other login boxes + for (var i = 0; i < divs.length; i++) { + var div = divs[i]; + // @@ TODO Remove the need to manipulate HTML elements + if (div.setUserCallback) { + try { + div.setUserCallback(webIdURI); + var parent = div.parentNode; + if (parent) { + parent.removeChild(div); + } + } catch (e) { + debug.log("## Error satisfying login box: ".concat(e)); + div.appendChild(widgets.errorMessageBlock(dom, e)); } } - res.push([nb2, null]); } } - return res; - } // unifyContents + }); + signInPopUpButton.addEventListener('click', function () { + var offline = (0, _solidLogic.offlineTestID)(); + if (offline) return setUserCallback(offline.uri); + renderSignInPopup(dom); + }, false); - // Matching - // - // Matching finds all bindings such that when the binding is applied - // to one term it is equal to the other term. We only match formulae. + // Sign up button + var signupButton = dom.createElement('input'); + box.appendChild(signupButton); + signupButton.setAttribute('type', 'button'); + signupButton.setAttribute('value', 'Sign Up for Solid'); + signupButton.setAttribute('style', "".concat(signInButtonStyle, "background-color: #efe;").concat(style.headerBannerLoginInput)); + signupButton.addEventListener('click', function (_event) { + var signupMgr = new _signup.Signup(); + signupMgr.signup().then(function (uri) { + debug.log('signInOrSignUpBox signed up ' + uri); + setUserCallback(uri); + }); + }, false); + return box; +} +function renderSignInPopup(dom) { + /** + * Issuer Menu + */ + var issuerPopup = dom.createElement('div'); + issuerPopup.setAttribute('style', 'position: fixed; top: 0; left: 0; right: 0; bottom: 0; display: flex; justify-content: center; align-items: center;'); + dom.body.appendChild(issuerPopup); + var issuerPopupBox = dom.createElement('div'); + issuerPopupBox.setAttribute('style', "\n background-color: white;\n box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);\n -webkit-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);\n -moz-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);\n -o-box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.2);\n border-radius: 4px;\n min-width: 400px;\n padding: 10px;\n z-index : 10;\n "); + issuerPopup.appendChild(issuerPopupBox); + var issuerPopupBoxTopMenu = dom.createElement('div'); + issuerPopupBoxTopMenu.setAttribute('style', "\n border-bottom: 1px solid #DDD;\n display: flex;\n flex-direction: row;\n align-items: center;\n justify-content: space-between;\n "); + issuerPopupBox.appendChild(issuerPopupBoxTopMenu); + var issuerPopupBoxLabel = dom.createElement('label'); + issuerPopupBoxLabel.setAttribute('style', 'margin-right: 5px; font-weight: 800'); + issuerPopupBoxLabel.innerText = 'Select an identity provider'; + var issuerPopupBoxCloseButton = dom.createElement('button'); + issuerPopupBoxCloseButton.innerHTML = ''; + issuerPopupBoxCloseButton.setAttribute('style', 'background-color: transparent; border: none;'); + issuerPopupBoxCloseButton.addEventListener('click', function () { + issuerPopup.remove(); + }); + issuerPopupBoxTopMenu.appendChild(issuerPopupBoxLabel); + issuerPopupBoxTopMenu.appendChild(issuerPopupBoxCloseButton); + var loginToIssuer = /*#__PURE__*/function () { + var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(issuerUri) { + var preLoginRedirectHash, locationUrl; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + // clear authorization metadata from store + _solidLogic.solidLogicSingleton.store.updater.flagAuthorizationMetadata(); + // Save hash + preLoginRedirectHash = new URL(window.location.href).hash; + if (preLoginRedirectHash) { + window.localStorage.setItem('preLoginRedirectHash', preLoginRedirectHash); + } + window.localStorage.setItem('loginIssuer', issuerUri); + // Login + locationUrl = new URL(window.location.href); + locationUrl.hash = ''; // remove hash part + _context.next = 9; + return _solidLogic.authSession.login({ + redirectUrl: locationUrl.href, + oidcIssuer: issuerUri + }); + case 9: + _context.next = 14; + break; + case 11: + _context.prev = 11; + _context.t0 = _context["catch"](0); + (0, _log.alert)(_context.t0.message); + case 14: + case "end": + return _context.stop(); + } + }, _callee, null, [[0, 11]]); + })); + return function loginToIssuer(_x11) { + return _ref.apply(this, arguments); + }; + }(); - /** if x is not in the bindings array, return the var; otherwise, return the bindings **/ - function bind(x, binding) { - var y = binding[x]; - if (y === undefined) { - return x; - } - return y; - } + /** + * Text-based idp selection + */ + var issuerTextContainer = dom.createElement('div'); + issuerTextContainer.setAttribute('style', "\n border-bottom: 1px solid #DDD;\n display: flex;\n flex-direction: column;\n padding-top: 10px;\n "); + var issuerTextInputContainer = dom.createElement('div'); + issuerTextInputContainer.setAttribute('style', "\n display: flex;\n flex-direction: row;\n "); + var issuerTextLabel = dom.createElement('label'); + issuerTextLabel.innerText = 'Enter the URL of your identity provider:'; + issuerTextLabel.setAttribute('style', 'color: #888'); + var issuerTextInput = dom.createElement('input'); + issuerTextInput.setAttribute('type', 'text'); + issuerTextInput.setAttribute('style', 'margin-left: 0 !important; flex: 1; margin-right: 5px !important'); + issuerTextInput.setAttribute('placeholder', 'https://example.com'); + issuerTextInput.value = localStorage.getItem('loginIssuer') || ''; + var issuerTextGoButton = dom.createElement('button'); + issuerTextGoButton.innerText = 'Go'; + issuerTextGoButton.setAttribute('style', 'margin-top: 12px; margin-bottom: 12px;'); + issuerTextGoButton.addEventListener('click', function () { + loginToIssuer(issuerTextInput.value); + }); + issuerTextContainer.appendChild(issuerTextLabel); + issuerTextInputContainer.appendChild(issuerTextInput); + issuerTextInputContainer.appendChild(issuerTextGoButton); + issuerTextContainer.appendChild(issuerTextInputContainer); + issuerPopupBox.appendChild(issuerTextContainer); - // When there are OPTIONAL clauses, we must return bindings without them if none of them - // succeed. However, if any of them do succeed, we should not. (This is what branchCount() - // tracked. The problem currently is (2011/7) that when several optionals exist, and they - // all match, multiple sets of bindings are returned, each with one optional filled in.) + /** + * Button-based idp selection + */ + var issuerButtonContainer = dom.createElement('div'); + issuerButtonContainer.setAttribute('style', "\n display: flex;\n flex-direction: column;\n padding-top: 10px;\n "); + var issuerBottonLabel = dom.createElement('label'); + issuerBottonLabel.innerText = 'Or pick an identity provider from the list below:'; + issuerBottonLabel.setAttribute('style', 'color: #888'); + issuerButtonContainer.appendChild(issuerBottonLabel); + (0, _solidLogic.getSuggestedIssuers)().forEach(function (issuerInfo) { + var issuerButton = dom.createElement('button'); + issuerButton.innerText = issuerInfo.name; + issuerButton.setAttribute('style', 'height: 38px; margin-top: 10px'); + issuerButton.addEventListener('click', function () { + loginToIssuer(issuerInfo.uri); + }); + issuerButtonContainer.appendChild(issuerButton); + }); + issuerPopupBox.appendChild(issuerButtonContainer); +} - function union(a, b) { - var c = {}; - var x; - for (x in a) { - if (a.hasOwnProperty(x)) { - c[x] = a[x]; - } - } - for (x in b) { - if (b.hasOwnProperty(x)) { - c[x] = b[x]; - } +/** + * Login status box + * + * A big sign-up/sign in box or a logout box depending on the state + * + * @param dom + * @param listener + * + * @returns + */ +function loginStatusBox(dom) { + var listener = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + // 20190630 + var me = (0, _solidLogic.offlineTestID)(); + // @@ TODO Remove the need to cast HTML element to any + var box = dom.createElement('div'); + function setIt(newidURI) { + if (!newidURI) { + return; } - return c; + + // const uri = newidURI.uri || newidURI + // me = sym(uri) + me = _solidLogic.authn.saveUser(newidURI); + box.refresh(); + if (listener) listener(me.uri); } - function OptionalBranchJunction(originalCallback, trunkBindings) { - this.trunkBindings = trunkBindings; - this.originalCallback = originalCallback; - this.branches = []; - // this.results = []; // result[i] is an array of bindings for branch i - // this.done = {}; // done[i] means all/any results are in for branch i - // this.count = {} - return this; + function logoutButtonHandler(_event) { + var oldMe = me; + _solidLogic.authSession.logout().then(function () { + var message = "Your WebID was ".concat(oldMe, ". It has been forgotten."); + me = null; + try { + (0, _log.alert)(message); + } catch (e) { + window.alert(message); + } + box.refresh(); + if (listener) listener(null); + }, function (err) { + (0, _log.alert)('Fail to log out:' + err); + }); } - OptionalBranchJunction.prototype.checkAllDone = function () { - var i; - for (i = 0; i < this.branches.length; i++) { - if (!this.branches[i].done) { - return; + function logoutButton(me, options) { + var signInButtonStyle = options.buttonStyle || getDefaultSignInButtonStyle(); + var logoutLabel = 'WebID logout'; + if (me) { + var nick = _solidLogic.solidLogicSingleton.store.any(me, ns.foaf('nick')) || _solidLogic.solidLogicSingleton.store.any(me, ns.foaf('name')); + if (nick) { + logoutLabel = 'Logout ' + nick.value; } } - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('OPTIONAL BIDNINGS ALL DONE:'); - this.doCallBacks(this.branches.length - 1, this.trunkBindings); - }; - // Recrursively generate the cross product of the bindings - OptionalBranchJunction.prototype.doCallBacks = function (b, bindings) { - var j; - if (b < 0) { - return this.originalCallback(bindings); + var signOutButton = dom.createElement('input'); + // signOutButton.className = 'WebIDCancelButton' + signOutButton.setAttribute('type', 'button'); + signOutButton.setAttribute('value', logoutLabel); + signOutButton.setAttribute('style', "".concat(signInButtonStyle, "background-color: #eee;")); + signOutButton.addEventListener('click', logoutButtonHandler, false); + return signOutButton; + } + box.refresh = function () { + var sessionInfo = _solidLogic.authSession.info; + if (sessionInfo && sessionInfo.webId && sessionInfo.isLoggedIn) { + me = _solidLogic.solidLogicSingleton.store.sym(sessionInfo.webId); + } else { + me = null; } - for (j = 0; j < this.branches[b].results.length; j++) { - this.doCallBacks(b - 1, union(bindings, this.branches[b].results[j])); + if (me && box.me !== me.uri || !me && box.me) { + widgets.clearElement(box); + if (me) { + box.appendChild(logoutButton(me, options)); + } else { + box.appendChild(signInOrSignUpBox(dom, setIt, options)); + } } + box.me = me ? me.uri : null; }; - - // A mandatory branch is the normal one, where callbacks - // are made immediately and no junction is needed. - // Might be useful for onFinsihed callback for query API. - function MandatoryBranch(callback, onDone) { - this.count = 0; - this.success = false; - this.done = false; - // this.results = [] - this.callback = callback; - this.onDone = onDone; - // this.junction = junction - // junction.branches.push(this) - return this; + box.refresh(); + function trackSession() { + me = _solidLogic.authn.currentUser(); + box.refresh(); } - MandatoryBranch.prototype.reportMatch = function (bindings) { - // log.error("@@@@ query.js 1"); // @@ - this.callback(bindings); - this.success = true; - }; - MandatoryBranch.prototype.reportDone = function () { - this.done = true; - _log__WEBPACK_IMPORTED_MODULE_4__["default"].info('Mandatory query branch finished.***'); - if (this.onDone !== undefined) { - this.onDone(); - } - }; - - // An optional branch hoards its results. - var OptionalBranch = function OptionalBranch(junction) { - this.count = 0; - this.done = false; - this.results = []; - this.junction = junction; - junction.branches.push(this); - return this; - }; - OptionalBranch.prototype.reportMatch = function (bindings) { - this.results.push(bindings); - }; - OptionalBranch.prototype.reportDone = function () { - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Optional branch finished - results.length = ' + this.results.length); - if (this.results.length === 0) { - // This is what optional means: if no hits, - this.results.push({}); // mimic success, but with no bindings - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug("Optional branch FAILED - that's OK."); - } - this.done = true; - this.junction.checkAllDone(); - }; - - /** prepare -- sets the index of the item to the possible matches - * @param f - formula - * @param item - an Statement, possibly w/ vars in it - * @param bindings - Bindings so far - * @returns false if the query fails -- there are no items that match - */ - function prepare(f, item, bindings) { - var terms, termIndex, i, ind; - item.nvars = 0; - item.index = null; - // if (!f.statements) log.warn("@@@ prepare: f is "+f) - // log.debug("Prepare: f has "+ f.statements.length) - // log.debug("Prepare: Kb size "+f.statements.length+" Preparing "+item) - - terms = [item.subject, item.predicate, item.object, item.why]; - ind = [f.subjectIndex, f.predicateIndex, f.objectIndex, f.whyIndex]; - for (i = 0; i < 4; i++) { - var t = terms[i]; - // console.log(" Prepare (" + t + ") "+(t in bindings)) - if (t.uri && t.uri === _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_3__.defaultGraphURI) {// chrome:session - // console.log(' query: Ignoring slot ' + i) - } else if (t.isVar && !(bindings[t] !== undefined)) { - item.nvars++; - } else { - t = bind(terms[i], bindings); // returns the RDF binding if bound, otherwise itself - // if (terms[i]!=bind(terms[i],bindings) alert("Term: "+terms[i]+"Binding: "+bind(terms[i], bindings)) - if (f.redirections[f.id(t)]) { - t = f.redirections[f.id(t)]; // redirect + trackSession(); + _solidLogic.authSession.onLogin(trackSession); + _solidLogic.authSession.onLogout(trackSession); + box.me = '99999'; // Force refresh + box.refresh(); + return box; +} +_solidLogic.authSession.onLogout( /*#__PURE__*/(0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2() { + var issuer, wellKnownUri, wellKnownResult, openidConfiguration; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + issuer = window.localStorage.getItem('loginIssuer'); + if (!issuer) { + _context2.next = 20; + break; } - - termIndex = ind[i][f.id(t)]; - if (!termIndex) { - item.index = []; - return false; // Query line cannot match + _context2.prev = 2; + // clear authorization metadata from store + _solidLogic.solidLogicSingleton.store.updater.flagAuthorizationMetadata(); + wellKnownUri = new URL(issuer); + wellKnownUri.pathname = '/.well-known/openid-configuration'; + _context2.next = 8; + return fetch(wellKnownUri.toString()); + case 8: + wellKnownResult = _context2.sent; + if (!(wellKnownResult.status === 200)) { + _context2.next = 16; + break; } - - if (item.index === null || item.index.length > termIndex.length) { - // Find smallest index - item.index = termIndex; + _context2.next = 12; + return wellKnownResult.json(); + case 12: + openidConfiguration = _context2.sent; + if (!(openidConfiguration && openidConfiguration.end_session_endpoint)) { + _context2.next = 16; + break; } - } - } - if (item.index === null) { - // All 4 are variables? - item.index = f.statements; + _context2.next = 16; + return fetch(openidConfiguration.end_session_endpoint, { + credentials: 'include' + }); + case 16: + _context2.next = 20; + break; + case 18: + _context2.prev = 18; + _context2.t0 = _context2["catch"](2); + case 20: + window.location.reload(); + case 21: + case "end": + return _context2.stop(); } - return true; - } // prepare + }, _callee2, null, [[2, 18]]); +}))); - /** sorting function -- negative if self is easier **/ - // We always prefer to start with a URI to be able to browse a graph - // this is why we put off items with more variables till later. - function easiestQuery(self, other) { - if (self.nvars !== other.nvars) { - return self.nvars - other.nvars; +/** + * Workspace selection etc + * See https://github.com/solidos/userguide/issues/16 + */ + +/** + * Returns a UI object which, if it selects a workspace, + * will callback(workspace, newBase). + * See https://github.com/solidos/userguide/issues/16 for more info on workspaces. + * + * If necessary, will get an account, preference file, etc. In sequence: + * + * - If not logged in, log in. + * - Load preference file + * - Prompt user for workspaces + * - Allows the user to just type in a URI by hand + * + * Calls back with the workspace and the base URI + * + * @param dom + * @param appDetails + * @param callbackWS + */ +function selectWorkspace(dom, appDetails, callbackWS) { + var noun = appDetails.noun; + var appPathSegment = appDetails.appPathSegment; + var me = (0, _solidLogic.offlineTestID)(); + var box = dom.createElement('div'); + var context = { + me: me, + dom: dom, + div: box + }; + function say(s, background) { + box.appendChild(widgets.errorMessageBlock(dom, s, background)); + } + function figureOutBase(ws) { + var newBaseNode = _solidLogic.solidLogicSingleton.store.any(ws, ns.space('uriPrefix')); + var newBaseString; + if (!newBaseNode) { + newBaseString = ws.uri.split('#')[0]; + } else { + newBaseString = newBaseNode.value; } - return self.index.length - other.index.length; + if (newBaseString.slice(-1) !== '/') { + debug.log("".concat(appPathSegment, ": No / at end of uriPrefix ").concat(newBaseString)); // @@ paramater? + newBaseString = "".concat(newBaseString, "/"); + } + var now = new Date(); + newBaseString += "".concat(appPathSegment, "/id").concat(now.getTime(), "/"); // unique id + return newBaseString; } - var matchIndex = 0; // index - /** matches a pattern formula against the knowledge base, e.g. to find matches for table-view - * - * @param f - knowledge base formula - * @param g - pattern formula (may have vars) - * @param bindingsSoFar - bindings accumulated in matching to date - * @param level - spaces to indent stuff also lets you know what level of recursion you're at - * @param fetcher - function (term, requestedBy) If you want link following - * @param localCallback - function(bindings, pattern, branch) called on sucess - * @returns nothing - * - * Will fetch linked data from the web iff the knowledge base an associated source fetcher (f.fetcher) - ***/ - var match = function match(f, g, bindingsSoFar, level, fetcher, localCallback, branch) { - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Match begins, Branch count now: ' + branch.count + ' for ' + branch.pattern_debug); + function displayOptions(context) { + // console.log('displayOptions!', context) + function makeNewWorkspace(_x12) { + return _makeNewWorkspace.apply(this, arguments); + } // const status = '' + function _makeNewWorkspace() { + _makeNewWorkspace = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(_event) { + var row, cell, newBase, newWs, newData; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) switch (_context3.prev = _context3.next) { + case 0: + row = table.appendChild(dom.createElement('tr')); + cell = row.appendChild(dom.createElement('td')); + cell.setAttribute('colspan', '3'); + cell.style.padding = '0.5em'; + _context3.t0 = encodeURI; + _context3.next = 7; + return widgets.askName(dom, _solidLogic.solidLogicSingleton.store, cell, ns.solid('URL'), ns.space('Workspace'), 'Workspace'); + case 7: + _context3.t1 = _context3.sent; + newBase = (0, _context3.t0)(_context3.t1); + newWs = widgets.newThing(context.preferencesFile); + newData = [(0, _rdflib.st)(context.me, ns.space('workspace'), newWs, context.preferencesFile), + // eslint-disable-next-line camelcase + (0, _rdflib.st)(newWs, ns.space('uriPrefix'), newBase, context.preferencesFile)]; + if (_solidLogic.solidLogicSingleton.store.updater) { + _context3.next = 13; + break; + } + throw new Error('store has no updater'); + case 13: + _context3.next = 15; + return _solidLogic.solidLogicSingleton.store.updater.update([], newData); + case 15: + case "end": + return _context3.stop(); + } + }, _callee3); + })); + return _makeNewWorkspace.apply(this, arguments); + } + var id = context.me; + var preferencesFile = context.preferencesFile; + var newBase = null; - // log.debug("match: f has "+f.statements.length+", g has "+g.statements.length) - var pattern = g.statements; - if (pattern.length === 0) { - // when it's satisfied all the pattern triples - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('FOUND MATCH WITH BINDINGS:' + bindingDebug(bindingsSoFar)); - if (g.optional.length === 0) { - branch.reportMatch(bindingsSoFar); - } else { - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('OPTIONAL: ' + g.optional); - var junction = new OptionalBranchJunction(callback, bindingsSoFar); // @@ won't work with nested optionals? nest callbacks - var br = []; - var b; - for (b = 0; b < g.optional.length; b++) { - br[b] = new OptionalBranch(junction); // Allocate branches to prevent premature ending - br[b].pattern_debug = g.optional[b]; // for diagnotics only - } + // A workspace specifically defined in the private preference file: + var w = _solidLogic.solidLogicSingleton.store.each(id, ns.space('workspace'), undefined, preferencesFile); // Only trust preference file here - for (b = 0; b < g.optional.length; b++) { - br[b].count = br[b].count + 1; // Count how many matches we have yet to complete - match(f, g.optional[b], bindingsSoFar, '', fetcher, callback, br[b]); - } - } - branch.count--; - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Match ends -- success , Branch count now: ' + branch.count + ' for ' + branch.pattern_debug); - return; // Success + // A workspace in a storage in the public profile: + var storages = _solidLogic.solidLogicSingleton.store.each(id, ns.space('storage')); // @@ No provenance requirement at the moment + if (w.length === 0 && storages) { + say("You don't seem to have any workspaces. You have ".concat(storages.length, " storage spaces."), 'white'); + storages.map(function (s) { + w = w.concat(_solidLogic.solidLogicSingleton.store.each(s, ns.ldp('contains'))); + return w; + }).filter(function (file) { + return file.id ? ['public', 'private'].includes(file.id().toLowerCase()) : ''; + }); + } + if (w.length === 1) { + say("Workspace used: ".concat(w[0].uri), 'white'); // @@ allow user to see URI + newBase = figureOutBase(w[0]); + // callbackWS(w[0], newBase) + // } else if (w.length === 0) { } - var item; - var i; - var n = pattern.length; - // log.debug(level + "Match "+n+" left, bs so far:"+bindingDebug(bindingsSoFar)) + // Prompt for ws selection or creation + // say( w.length + " workspaces for " + id + "Choose one."); + var table = dom.createElement('table'); + table.setAttribute('style', 'border-collapse:separate; border-spacing: 0.5em;'); - // Follow links from variables in query - if (fetcher) { - // Fetcher is used to fetch URIs, function first term is a URI term, second is the requester - var id = 'match' + matchIndex++; - var fetchResource = function fetchResource(requestedTerm, id) { - var docuri = requestedTerm.uri.split('#')[0]; - fetcher.nowOrWhenFetched(docuri, undefined, function (ok, body, xhr) { - if (!ok) { - console.log('Error following link to <' + requestedTerm.uri + '> in query: ' + body); - } - match(f, g, bindingsSoFar, level, fetcher, - // match not match2 to look up any others necessary. - localCallback, branch); - }); - }; - for (i = 0; i < n; i++) { - item = pattern[i]; // for each of the triples in the query - if (bindingsSoFar[item.subject] !== undefined && bindingsSoFar[item.subject].uri && fetcher && fetcher.getState((0,_uri__WEBPACK_IMPORTED_MODULE_5__.docpart)(bindingsSoFar[item.subject].uri)) === 'unrequested') { - // fetch the subject info and return to id - fetchResource(bindingsSoFar[item.subject], id); - return; // only look up one per line this time, but we will come back again though match - } + // const popup = window.open(undefined, '_blank', { height: 300, width:400 }, false) + box.appendChild(table); - if (bindingsSoFar[item.object] !== undefined && bindingsSoFar[item.object].uri && fetcher && fetcher.getState((0,_uri__WEBPACK_IMPORTED_MODULE_5__.docpart)(bindingsSoFar[item.object].uri)) === 'unrequested') { - fetchResource(bindingsSoFar[item.object], id); - return; - } - } - } // if fetcher - match2(f, g, bindingsSoFar, level, fetcher, localCallback, branch); - }; // match + // Add a field for directly adding the URI yourself - var constraintsSatisfied = function constraintsSatisfied(bindings, constraints) { - var res = true; - var x; - var test; - for (x in bindings) { - if (bindings.hasOwnProperty(x)) { - if (constraints[x]) { - test = constraints[x].test; - if (test && !test(bindings[x])) { - res = false; - } - } - } - } - return res; - }; + // const hr = box.appendChild(dom.createElement('hr')) // @@ + box.appendChild(dom.createElement('hr')); // @@ - /** match2 -- stuff after the fetch **/ - var match2 = function match2(f, g, bindingsSoFar, level, fetcher, callback, branch) { - // post fetch - var pattern = g.statements; - var n = pattern.length; - var i; - var k; - var nk; - var v; - var bindings2; - var newBindings1; - var item; - for (i = 0; i < n; i++) { - // For each statement left in the query, run prepare - item = pattern[i]; - // log.info('match2: item=' + item + ', bindingsSoFar=' + bindingDebug(bindingsSoFar)) - prepare(f, item, bindingsSoFar); - // if (item.index) console.log(' item.index.length ' + item.index.length) + var p = box.appendChild(dom.createElement('p')); + p.setAttribute('style', style.commentStyle); + p.textContent = "Where would you like to store the data for the ".concat(noun, "?\n Give the URL of the folder where you would like the data stored.\n It can be anywhere in solid world - this URI is just an idea."); + // @@ TODO Remove the need to cast baseField to any + var baseField = box.appendChild(dom.createElement('input')); + baseField.setAttribute('type', 'text'); + baseField.setAttribute('style', style.textInputStyle); + baseField.size = 80; // really a string + baseField.label = 'base URL'; + baseField.autocomplete = 'on'; + if (newBase) { + // set to default + baseField.value = newBase; } + context.baseField = baseField; + box.appendChild(dom.createElement('br')); // @@ - pattern.sort(easiestQuery); - item = pattern[0]; - // log.debug("Sorted pattern:\n"+pattern) - var rest = f.formula(); - rest.optional = g.optional; - rest.constraints = g.constraints; - rest.statements = pattern.slice(1); // No indexes: we will not query g. - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug(level + 'match2 searching ' + item.index.length + ' for ' + item + '; bindings so far=' + bindingDebug(bindingsSoFar)); - // var results = [] - var c; - var nc = item.index.length; - var nbs1; - var st; - var onward = 0; - // var x - for (c = 0; c < nc; c++) { - // For each candidate statement - st = item.index[c]; // for each statement in the item's index, spawn a new match with that binding - nbs1 = unifyContents([item.subject, item.predicate, item.object, item.why], [st.subject, st.predicate, st.object, st.why], bindingsSoFar, f); - _log__WEBPACK_IMPORTED_MODULE_4__["default"].info(level + ' From first: ' + nbs1.length + ': ' + bindingsDebug(nbs1)); - nk = nbs1.length; - // branch.count += nk - // log.debug("Branch count bumped "+nk+" to: "+branch.count) - for (k = 0; k < nk; k++) { - // For each way that statement binds - bindings2 = []; - newBindings1 = nbs1[k][0]; - if (!constraintsSatisfied(newBindings1, g.constraints)) { - // branch.count-- - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Branch count CS: ' + branch.count); - } else { - for (v in newBindings1) { - if (newBindings1.hasOwnProperty(v)) { - bindings2[v] = newBindings1[v]; // copy - } - } + var button = box.appendChild(dom.createElement('button')); + button.setAttribute('style', style.buttonStyle); + button.textContent = "Start new ".concat(noun, " at this URI"); + button.addEventListener('click', function (_event) { + var newBase = baseField.value.replace(' ', '%20'); // do not re-encode in general, as % encodings may exist + if (newBase.slice(-1) !== '/') { + newBase += '/'; + } + callbackWS(null, newBase); + }); - for (v in bindingsSoFar) { - if (bindingsSoFar.hasOwnProperty(v)) { - bindings2[v] = bindingsSoFar[v]; // copy - } - } + // Now go set up the table of spaces - branch.count++; // Count how many matches we have yet to complete - onward++; - match(f, rest, bindings2, level + ' ', fetcher, callback, branch); // call match - } + // const row = 0 + w = w.filter(function (x) { + return !_solidLogic.solidLogicSingleton.store.holds(x, ns.rdf('type'), + // Ignore master workspaces + ns.space('MasterWorkspace')); + }); + var col1, col2, col3, tr, ws, localStyle, comment; + var cellStyle = 'height: 3em; margin: 1em; padding: 1em white; border-radius: 0.3em;'; + var deselectedStyle = "".concat(cellStyle, "border: 0px;"); + // const selectedStyle = cellStyle + 'border: 1px solid black;' + for (var i = 0; i < w.length; i++) { + ws = w[i]; + tr = dom.createElement('tr'); + if (i === 0) { + col1 = dom.createElement('td'); + col1.setAttribute('rowspan', "".concat(w.length)); + col1.textContent = 'Choose a workspace for this:'; + col1.setAttribute('style', 'vertical-align:middle;'); + tr.appendChild(col1); } - } + col2 = dom.createElement('td'); + localStyle = _solidLogic.solidLogicSingleton.store.anyValue(ws, ns.ui('style')); + if (!localStyle) { + // Otherwise make up arbitrary colour + var hash = function hash(x) { + return x.split('').reduce(function (a, b) { + a = (a << 5) - a + b.charCodeAt(0); + return a & a; + }, 0); + }; + var bgcolor = "#".concat((hash(ws.uri) & 0xffffff | 0xc0c0c0).toString(16)); // c0c0c0 forces pale + localStyle = "color: black ; background-color: ".concat(bgcolor, ";"); + } + col2.setAttribute('style', deselectedStyle + localStyle); + tr.target = ws.uri; + var label = _solidLogic.solidLogicSingleton.store.any(ws, ns.rdfs('label')); + if (!label) { + label = ws.uri.split('/').slice(-1)[0] || ws.uri.split('/').slice(-2)[0]; + } + col2.textContent = label || '???'; + tr.appendChild(col2); + if (i === 0) { + col3 = dom.createElement('td'); + col3.setAttribute('rowspan', "".concat(w.length, "1")); + // col3.textContent = '@@@@@ remove'; + col3.setAttribute('style', 'width:50%;'); + tr.appendChild(col3); + } + table.appendChild(tr); + comment = _solidLogic.solidLogicSingleton.store.any(ws, ns.rdfs('comment')); + comment = comment ? comment.value : 'Use this workspace'; + col2.addEventListener('click', function (_event) { + col3.textContent = comment ? comment.value : ''; + col3.setAttribute('style', deselectedStyle + localStyle); + var button = dom.createElement('button'); + button.textContent = 'Continue'; + // button.setAttribute('style', style); + var newBase = figureOutBase(ws); + baseField.value = newBase; // show user proposed URI - branch.count--; - if (onward === 0) { - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Match2 fails completely on ' + item); - } - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Match2 ends, Branch count: ' + branch.count + ' for ' + branch.pattern_debug); - if (branch.count === 0) { - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Branch finished.'); - branch.reportDone(); + button.addEventListener('click', function (_event) { + button.disabled = true; + callbackWS(ws, newBase); + button.textContent = '---->'; + }, true); // capture vs bubble + col3.appendChild(button); + }, true); // capture vs bubble } - }; // match2 - // ////////////////////////// Body of query() /////////////////////// - var f = this; - _log__WEBPACK_IMPORTED_MODULE_4__["default"].debug('Query on ' + this.statements.length); - var trunck = new MandatoryBranch(callback, onDone); - trunck.count++; // count one branch to complete at the moment - if (myQuery.sync) { - match(f, myQuery.pat, myQuery.pat.initBindings, '', fetcher, callback, trunck); - } else { - // Give up thread: Allow other activities to run - setTimeout(function () { - match(f, myQuery.pat, myQuery.pat.initBindings, '', fetcher, callback, trunck); - }, 0); - } - - // returns nothing; callback does the work -} // query -/***/ }), + // last line with "Make new workspace" + var trLast = dom.createElement('tr'); + col2 = dom.createElement('td'); + col2.setAttribute('style', cellStyle); + col2.textContent = '+ Make a new workspace'; + col2.addEventListener('click', makeNewWorkspace); + trLast.appendChild(col2); + table.appendChild(trLast); + } // displayOptions -/***/ "../rdflib/esm/rdfaparser.js": -/*!***********************************!*\ - !*** ../rdflib/esm/rdfaparser.js ***! - \***********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ RDFaProcessor), -/* harmony export */ "parseRDFaDOM": () => (/* binding */ parseRDFaDOM) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./blank-node */ "../rdflib/esm/blank-node.js"); -/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./literal */ "../rdflib/esm/literal.js"); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); -/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "../rdflib/esm/factories/canonical-data-factory.js"); + // console.log('kicking off async operation') + ensureLoadedPreferences(context) // kick off async operation + .then(displayOptions)["catch"](function (err) { + // console.log("err from async op") + box.appendChild(widgets.errorMessageBlock(context.dom, err)); + }); + return box; // return the box element, while login proceeds +} // selectWorkspace +/** + * Creates a new instance of an app. + * + * An instance of an app could be e.g. an issue tracker for a given project, + * or a chess game, or calendar, or a health/fitness record for a person. + * + * Note that this use of the term 'app' refers more to entries in the user's + * type index than to actual software applications that use the personal data + * to which these entries point. + * + * @param dom + * @param appDetails + * @param callback + * + * @returns A div with a button in it for making a new app instance + */ +function newAppInstance(dom, appDetails, callback) { + var gotWS = function gotWS(ws, base) { + // log.debug("newAppInstance: Selected workspace = " + (ws? ws.uri : 'none')) + callback(ws, base); + }; + var div = dom.createElement('div'); + var b = dom.createElement('button'); + b.setAttribute('type', 'button'); + div.appendChild(b); + b.innerHTML = "Make new ".concat(appDetails.noun); + b.addEventListener('click', function (_event) { + div.appendChild(selectWorkspace(dom, appDetails, gotWS)); + }, false); + div.appendChild(b); + return div; +} +/** + * Retrieves whether the currently logged in user is a power user + * and/or a developer + */ +function getUserRoles() { + return _getUserRoles.apply(this, arguments); +} +/** + * Filters which panes should be available, based on the result of [[getUserRoles]] + */ +function _getUserRoles() { + _getUserRoles = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10() { + var _yield$ensureLoadedPr, me, preferencesFile, preferencesFileError; + return _regenerator["default"].wrap(function _callee10$(_context11) { + while (1) switch (_context11.prev = _context11.next) { + case 0: + _context11.prev = 0; + _context11.next = 3; + return ensureLoadedPreferences({}); + case 3: + _yield$ensureLoadedPr = _context11.sent; + me = _yield$ensureLoadedPr.me; + preferencesFile = _yield$ensureLoadedPr.preferencesFile; + preferencesFileError = _yield$ensureLoadedPr.preferencesFileError; + if (!(!preferencesFile || preferencesFileError)) { + _context11.next = 9; + break; + } + throw new Error(preferencesFileError); + case 9: + return _context11.abrupt("return", _solidLogic.solidLogicSingleton.store.each(me, ns.rdf('type'), null, preferencesFile.doc())); + case 12: + _context11.prev = 12; + _context11.t0 = _context11["catch"](0); + debug.warn('Unable to fetch your preferences - this was the error: ', _context11.t0); + case 15: + return _context11.abrupt("return", []); + case 16: + case "end": + return _context11.stop(); + } + }, _callee10, null, [[0, 12]]); + })); + return _getUserRoles.apply(this, arguments); +} +function filterAvailablePanes(_x13) { + return _filterAvailablePanes.apply(this, arguments); +} +function _filterAvailablePanes() { + _filterAvailablePanes = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(panes) { + var userRoles; + return _regenerator["default"].wrap(function _callee11$(_context12) { + while (1) switch (_context12.prev = _context12.next) { + case 0: + _context12.next = 2; + return getUserRoles(); + case 2: + userRoles = _context12.sent; + return _context12.abrupt("return", panes.filter(function (pane) { + return isMatchingAudience(pane, userRoles); + })); + case 4: + case "end": + return _context12.stop(); + } + }, _callee11); + })); + return _filterAvailablePanes.apply(this, arguments); +} +function isMatchingAudience(pane, userRoles) { + var audience = pane.audience || []; + return audience.reduce(function (isMatch, audienceRole) { + return isMatch && !!userRoles.find(function (role) { + return role.equals(audienceRole); + }); + }, true); +} +//# sourceMappingURL=login.js.map -// RDFa Parser for rdflib.js +/***/ }), -// Originally by: Alex Milowski -// From https://github.com/alexmilowski/green-turtle -// Converted: timbl 2015-08-25 not yet working -// Added wrapper: csarven 2016-05-09 working +/***/ "./lib/matrix/index.js": +/*!*****************************!*\ + !*** ./lib/matrix/index.js ***! + \*****************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -// RDFaProcessor.prototype = new Object() // Was URIResolver +"use strict"; -// RDFaProcessor.prototype.constructor=RDFaProcessor -// options.base = base URI not really an option, shopuld always be set. -// +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.matrix = void 0; +var _matrix = __webpack_require__(/*! ./matrix */ "./lib/matrix/matrix.js"); +var matrix = { + matrixForQuery: _matrix.matrixForQuery +}; +exports.matrix = matrix; +//# sourceMappingURL=index.js.map +/***/ }), +/***/ "./lib/matrix/matrix.js": +/*!******************************!*\ + !*** ./lib/matrix/matrix.js ***! + \******************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +"use strict"; +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.matrixForQuery = matrixForQuery; +var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); +var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +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); } +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; } +// Build a 2D matrix of values +// +// dom AKA document +// query a Query object of rdflib.js with a valid pattern +// vx A variable object, the one to be used for the X variable (horiz) +// vy A variable object, the one to be used for the Y variable (vertical) +// vvalue A variable object, the one to be used for the cell value +// returns A DOM element with the matrix in it, which has a .refresh() function. +// +// Options: +// cellFunction(td, x, y, value) fill the TD element of a single cell +// xDecreasing set true for x axis to be in decreasing order. +// yDecreasing set true for y axis to be in decreasing order. +// set_x array of X values to be define initial rows (order irrelevant) +// set_y array of Y values to be define initial columns +// +// Features: +// Header row at top (x axis) and left (y-axis) generated automatically. +// Extra rows and columns are inserted as needed to hold new data points +// matrix.refresh() will re-run the query and adjust the display +var kb = _solidLogic.solidLogicSingleton.store; +function matrixForQuery(dom, query, vx, vy, vvalue, options, whenDone) { + // @@ TODO Remove need to cast to any + var matrix = dom.createElement('table'); + var header = dom.createElement('tr'); + var corner = header.appendChild(dom.createElement('td')); + corner.setAttribute('class', 'MatrixCorner'); + matrix.appendChild(header); // just one for now + matrix.lastHeader = header; // Element before data + var columns = []; // Vector + var rows = []; // Associative array -if (typeof Node === 'undefined') { - // @@@@@@ Global. Interface to xmldom. - var Node = { - ELEMENT_NODE: 1, - ATTRIBUTE_NODE: 2, - TEXT_NODE: 3, - CDATA_SECTION_NODE: 4, - ENTITY_REFERENCE_NODE: 5, - ENTITY_NODE: 6, - PROCESSING_INSTRUCTION_NODE: 7, - COMMENT_NODE: 8, - DOCUMENT_NODE: 9, - DOCUMENT_TYPE_NODE: 10, - DOCUMENT_FRAGMENT_NODE: 11, - NOTATION_NODE: 12 + var setCell = function setCell(cell, x, y, value) { + while (cell.firstChild) { + // Empty any previous + cell.removeChild(cell.firstChild); + } + cell.setAttribute('style', ''); + cell.style.textAlign = 'center'; + if (options.cellFunction) { + options.cellFunction(cell, x, y, value); + } else { + cell.textContent = utils.label(value); + cell.setAttribute('style', 'padding: 0.3em'); + } + delete cell.old; }; -} -var RDFaProcessor = /*#__PURE__*/function () { - function RDFaProcessor(kb, options) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, RDFaProcessor); - this.options = options || {}; - this.kb = kb; - this.target = options.target || { - graph: { - subjects: {}, - prefixes: {}, - terms: {} - } - }; - // XXX: Added to track bnodes - this.blankNodes = []; - // XXX: Added for normalisation - this.htmlOptions = { - 'selfClosing': 'br img input area base basefont col colgroup source wbr isindex link meta param hr' - }; - this.theOne = '_:' + new Date().getTime(); - this.language = null; - this.vocabulary = null; - this.blankCounter = 0; - this.langAttributes = [{ - namespaceURI: 'http://www.w3.org/XML/1998/namespace', - localName: 'lang' - }]; - this.inXHTMLMode = false; - this.absURIRE = /[\w\_\-]+:\S+/; - this.finishedHandlers = []; - this.init(); - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(RDFaProcessor, [{ - key: "addTriple", - value: function addTriple(origin, subject, predicate, object) { - var su, ob, pr, or; - if (typeof subject === 'undefined') { - su = _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].namedNode(this.options.base); - } else { - su = this.toRDFNodeObject(subject); - } - pr = this.toRDFNodeObject(predicate); - ob = this.toRDFNodeObject(object); - or = _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].namedNode(this.options.base); - // console.log('Adding { ' + su + ' ' + pr + ' ' + ob + ' ' + or + ' }') - this.kb.add(su, pr, ob, or); + var rowFor = function rowFor(y1) { + var y = y1.toNT(); + if (rows[y]) return rows[y]; + // @@ TODO Remove need for casting to any + var tr = dom.createElement('tr'); + var header = tr.appendChild(dom.createElement('td')); + header.setAttribute('style', 'padding: 0.3em;'); + header.textContent = utils.label(y1); // first approximation + if (y1.termType === 'NamedNode') { + kb.fetcher.nowOrWhenFetched(y1.uri.split('#')[0], undefined, function (ok, _body, _response) { + if (ok) header.textContent = utils.label(y1); + }); } - }, { - key: "ancestorPath", - value: function ancestorPath(node) { - var path = ''; - while (node && node.nodeType !== Node.DOCUMENT_NODE) { - path = '/' + node.localName + path; - node = node.parentNode; - } - return path; + for (var i = 0; i < columns.length; i++) { + setCell(tr.appendChild(dom.createElement('td')), $rdf.fromNT(columns[i]), y1, null); } - }, { - key: "copyMappings", - value: function copyMappings(mappings) { - var newMappings = {}; - for (var k in mappings) { - newMappings[k] = mappings[k]; + tr.dataValueNT = y; + rows[y] = tr; + for (var ele = matrix.lastHeader.nextSibling; ele; ele = ele.nextSibling) { + // skip header + if (y > ele.dataValueNT && options && options.yDecreasing || y < ele.dataValueNT && !(options && options.yDecreasing)) { + return matrix.insertBefore(tr, ele); // return the tr } - return newMappings; } - }, { - key: "copyProperties", - value: function copyProperties() {} - }, { - key: "deriveDateTimeType", - value: function deriveDateTimeType(value) { - for (var i = 0; i < RDFaProcessor.dateTimeTypes.length; i++) { - // console.log("Checking "+value+" against "+RDFaProcessor.dateTimeTypes[i].type) - var matched = RDFaProcessor.dateTimeTypes[i].pattern.exec(value); - if (matched && matched[0].length === value.length) { - // console.log("Matched!") - return RDFaProcessor.dateTimeTypes[i].type; - } + + return matrix.appendChild(tr); // return the tr + }; + + var columnNumberFor = function columnNumberFor(x1) { + var xNT = x1.toNT(); // xNT is a NT string + var col = null; + // These are data columns (not headings) + for (var i = 0; i < columns.length; i++) { + if (columns[i] === xNT) { + return i; + } + if (xNT > columns[i] && options.xDecreasing || xNT < columns[i] && !options.xDecreasing) { + columns = columns.slice(0, i).concat([xNT]).concat(columns.slice(i)); + col = i; + break; } - return null; } - }, { - key: "init", - value: function init() {} - }, { - key: "newBlankNode", - value: function newBlankNode() { - this.blankCounter++; - return '_:' + this.blankCounter; + if (col === null) { + col = columns.length; + columns.push(xNT); } - }, { - key: "newSubjectOrigin", - value: function newSubjectOrigin(origin, subject) {} - }, { - key: "parseCURIE", - value: function parseCURIE(value, prefixes, base) { - var colon = value.indexOf(':'); - var uri; - if (colon >= 0) { - var prefix = value.substring(0, colon); - if (prefix === '') { - // default prefix - uri = prefixes['']; - return uri ? uri + value.substring(colon + 1) : null; - } else if (prefix === '_') { - // blank node - return '_:' + value.substring(colon + 1); - } else if (RDFaProcessor.NCNAME.test(prefix)) { - uri = prefixes[prefix]; - if (uri) { - return uri + value.substring(colon + 1); - } + + // col is the number of the new column, starting from 0 + for (var row = matrix.firstChild; row; row = row.nextSibling) { + // For every row header or not + var y = row.dataValueNT; + var td = dom.createElement('td'); // Add a new cell + td.style.textAlign = 'center'; + if (row === matrix.firstChild) { + td.textContent = utils.label(x1); + } else { + setCell(td, x1, $rdf.fromNT(y), null); + } + if (col === columns.length - 1) { + row.appendChild(td); + } else { + var t = row.firstChild; + for (var j = 0; j < col + 1; j++) { + // Skip header col too + t = t.nextSibling; } + row.insertBefore(td, t); } - return null; } - }, { - key: "parseCURIEOrURI", - value: function parseCURIEOrURI(value, prefixes, base) { - var curie = this.parseCURIE(value, prefixes, base); - if (curie) { - return curie; + return col; + }; + var markOldCells = function markOldCells() { + for (var i = 1; i < matrix.children.length; i++) { + var row = matrix.children[i]; + for (var j = 1; j < row.children.length; j++) { + row.children[j].old = true; } - return this.resolveAndNormalize(base, value); } - }, { - key: "parsePredicate", - value: function parsePredicate(value, defaultVocabulary, terms, prefixes, base, ignoreTerms) { - if (value === '') { - return null; - } - var predicate = this.parseTermOrCURIEOrAbsURI(value, defaultVocabulary, ignoreTerms ? null : terms, prefixes, base); - if (predicate && predicate.indexOf('_:') === 0) { - return null; + }; + var clearOldCells = function clearOldCells() { + var row, cell; + var colsUsed = []; + var rowsUsed = []; + if (options.set_y) { + // Knows y values create rows + for (var k = 0; k < options.set_y.length; k++) { + rowsUsed[options.set_y[k]] = true; } - return predicate; } - }, { - key: "parsePrefixMappings", - value: function parsePrefixMappings(str, target) { - var values = this.tokenize(str); - var prefix = null; - // var uri = null - for (var i = 0; i < values.length; i++) { - if (values[i][values[i].length - 1] === ':') { - prefix = values[i].substring(0, values[i].length - 1); - } else if (prefix) { - target[prefix] = this.options.base ? _uri__WEBPACK_IMPORTED_MODULE_3__.join(values[i], this.options.base) : values[i]; - prefix = null; - } + if (options.set_x) { + for (var _k = 0; _k < options.set_x.length; _k++) { + colsUsed[columnNumberFor(options.set_x[_k]) + 1] = true; } } - }, { - key: "parseSafeCURIEOrCURIEOrURI", - value: function parseSafeCURIEOrCURIEOrURI(value, prefixes, base) { - value = this.trim(value); - if (value.charAt(0) === '[' && value.charAt(value.length - 1) === ']') { - value = value.substring(1, value.length - 1); - value = value.trim(value); - if (value.length === 0) { - return null; - } - if (value === '_:') { - // the one node - return this.theOne; + for (var i = 1; i < matrix.children.length; i++) { + row = matrix.children[i]; + for (var j = 1; j < row.children.length; j++) { + cell = row.children[j]; + if (cell.old) { + var y = $rdf.fromNT(row.dataValueNT); + var x = $rdf.fromNT(columns[j - 1]); + setCell(cell, x, y, null); + } else { + rowsUsed[row.dataValueNT] = true; + colsUsed[j] = true; } - return this.parseCURIE(value, prefixes, base); - } else { - return this.parseCURIEOrURI(value, prefixes, base); } } - }, { - key: "parseTermOrCURIEOrAbsURI", - value: function parseTermOrCURIEOrAbsURI(value, defaultVocabulary, terms, prefixes, base) { - // alert("Parsing "+value+" with default vocab "+defaultVocabulary) - value = this.trim(value); - var curie = this.parseCURIE(value, prefixes, base); - if (curie) { - return curie; - } else if (terms) { - if (defaultVocabulary && !this.absURIRE.exec(value)) { - return defaultVocabulary + value; - } - var term = terms[value]; - if (term) { - return term; - } - var lcvalue = value.toLowerCase(); - term = terms[lcvalue]; - if (term) { - return term; + for (var _i = 0; _i < matrix.children.length; _i++) { + row = matrix.children[_i]; + if (_i > 0 && !rowsUsed[row.dataValueNT]) { + delete rows[row.dataValueNT]; + matrix.removeChild(row); + } else { + for (var _j = row.children.length - 1; _j > 0; _j--) { + // backwards + var _cell = row.children[_j]; + if (!colsUsed[_j]) { + row.removeChild(_cell); + } } } - if (this.absURIRE.exec(value)) { - return this.resolveAndNormalize(base, value); + } + var newcolumns = []; + for (var _j2 = 0; _j2 < columns.length; _j2++) { + if (colsUsed[_j2 + 1]) { + newcolumns.push(columns[_j2]); } - return null; } - }, { - key: "parseTermOrCURIEOrURI", - value: function parseTermOrCURIEOrURI(value, defaultVocabulary, terms, prefixes, base) { - // alert("Parsing "+value+" with default vocab "+defaultVocabulary) - value = this.trim(value); - var curie = this.parseCURIE(value, prefixes, base); - if (curie) { - return curie; - } else { - var term = terms[value]; - if (term) { - return term; - } - var lcvalue = value.toLowerCase(); - term = terms[lcvalue]; - if (term) { - return term; - } - if (defaultVocabulary && !this.absURIRE.exec(value)) { - return defaultVocabulary + value; - } - } - return this.resolveAndNormalize(base, value); + columns = newcolumns; + }; + matrix.refresh = function () { + markOldCells(); + kb.query(query, addCellFromBindings, undefined, clearOldCells); + }; + var addCellFromBindings = function addCellFromBindings(bindings) { + var x = bindings[vx.toString()]; + var y = bindings[vy.toString()]; + var value = bindings[vvalue.toString()]; + var row = rowFor(y); + var colNo = columnNumberFor(x); + var cell = row.children[colNo + 1]; // number of Y axis headings + setCell(cell, x, y, value); + }; + if (options.set_y) { + // Knows y values create rows + for (var k = 0; k < options.set_y.length; k++) { + rowFor(options.set_y[k]); } - }, { - key: "parseURI", - value: function parseURI(uri) { - return uri; // We just use strings as URIs, not objects now. + } + if (options.set_x) { + for (var _k2 = 0; _k2 < options.set_x.length; _k2++) { + columnNumberFor(options.set_x[_k2]); } - }, { - key: "process", - value: function process(node, options) { - /* - if (!window.console) { - window.console = { log: function() {} } - } */ - options = options || {}; - var base; - if (node.nodeType === Node.DOCUMENT_NODE) { - if (node.baseURI && !options.baseURI) { - options.baseURI = node.baseURI; // be defensive as DOM implementations vary - } + } + kb.query(query, addCellFromBindings, undefined, whenDone); // Populate the matrix + return matrix; +} +//# sourceMappingURL=matrix.js.map - base = node.baseURI; - node = node.documentElement; - if (!node.baseURI) { - node.baseURI = base; +/***/ }), + +/***/ "./lib/media/index.js": +/*!****************************!*\ + !*** ./lib/media/index.js ***! + \****************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.media = void 0; +var _mediaCapture = __webpack_require__(/*! ./media-capture */ "./lib/media/media-capture.js"); +var media = { + cameraCaptureControl: _mediaCapture.cameraCaptureControl, + cameraButton: _mediaCapture.cameraButton +}; +exports.media = media; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ "./lib/media/media-capture.js": +/*!************************************!*\ + !*** ./lib/media/media-capture.js ***! + \************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.cameraButton = cameraButton; +exports.cameraCaptureControl = cameraCaptureControl; +var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); +var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); +var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); +var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); +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); } +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; } +/// ///////////////////////////////////////////// +// +// Media input widget +// +// +// Workflow: +// The HTML5 functionality (on mobille) is to prompt for either +// a realtime camera capture , OR a selection from images already ont the device +// (eg camera roll). +// +// The solid alternative is to either take a phtoto +// or access cemra roll (etc) OR to access solid cloud storage of favorite photo almbums. +// (Especially latest taken ones) +// + +/** @module mediaCapture */ + +var cameraIcon = _iconBase.icons.iconBase + 'noun_Camera_1618446_000000.svg'; // Get it from github +var retakeIcon = _iconBase.icons.iconBase + 'noun_479395.svg'; // Get it from github + +var canvasWidth = '640'; +var canvasHeight = '480'; +var controlStyle = "border-radius: 0.5em; margin: 0.8em; width: ".concat(canvasWidth, "; height:").concat(canvasHeight, ";"); +// const controlStyle = 'border-radius: 0.5em; margin: 0.8em; width: 320; height:240;' +var contentType = 'image/png'; + +/** A control to capture a picture using camera + * @param {Docuemnt} dom - The Document object + * @param {IndexedForumla} store - The quadstore to store data in + * @param {NamedNode} getImageDoc() - NN of the image file to be created + * @param {function} doneCallback - Called when a picture has been taken + */ +function cameraCaptureControl(dom, store, getImageDoc, doneCallback) { + var div = dom.createElement('div'); + var destination, imageBlob, player, canvas; + var table = div.appendChild(dom.createElement('table')); + var mainTR = table.appendChild(dom.createElement('tr')); + var main = mainTR.appendChild(dom.createElement('td')); + main.setAttribute('colspan', '4'); + var buttons = table.appendChild(dom.createElement('tr')); + buttons.appendChild(dom.createElement('td')) // Cancel button + .appendChild(widgets.cancelButton(dom)).addEventListener('click', function (_event) { + stopVideo(); + doneCallback(null); + }); + var retakeButton = buttons.appendChild(dom.createElement('td')) // Retake button + .appendChild(widgets.button(dom, retakeIcon, 'Retake')); + retakeButton.addEventListener('click', function (_event) { + retake(); + }); + retakeButton.style.visibility = 'collapse'; // Hide for now + + var shutterButton = buttons.appendChild(dom.createElement('td')) // Trigger capture button + .appendChild(widgets.button(dom, _iconBase.icons.iconBase + 'noun_10636.svg', 'Snap')); + shutterButton.addEventListener('click', grabCanvas); + shutterButton.style.visibility = 'collapse'; // Hide for now + + var sendButton = buttons.appendChild(dom.createElement('td')) // Confirm and save button + .appendChild(widgets.continueButton(dom)); // @@ or send icon?? + sendButton.addEventListener('click', function (_event) { + saveBlob(imageBlob, destination); + }); + sendButton.style.visibility = 'collapse'; // Hide for now + + function displayPlayer() { + player = main.appendChild(dom.createElement('video')); + player.setAttribute('controls', '1'); + player.setAttribute('autoplay', '1'); + player.setAttribute('style', controlStyle); + if (!navigator.mediaDevices) { + throw new Error('navigator.mediaDevices not available'); + } + navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { + player.srcObject = stream; + shutterButton.style.visibility = 'visible'; // Enable + sendButton.style.visibility = 'collapse'; + retakeButton.style.visibility = 'collapse'; + }); + } + var constraints = { + video: true + }; + function retake() { + main.removeChild(canvas); + displayPlayer(); // Make new one as old one is stuck black + } + + function grabCanvas() { + // Draw the video frame to the canvas. + canvas = dom.createElement('canvas'); + canvas.setAttribute('width', canvasWidth); + canvas.setAttribute('height', canvasHeight); + canvas.setAttribute('style', controlStyle); + main.appendChild(canvas); + var context = canvas.getContext('2d'); + context.drawImage(player, 0, 0, canvas.width, canvas.height); + player.parentNode.removeChild(player); + canvas.toBlob(function (blob) { + var msg = "got blob type ".concat(blob.type, " size ").concat(blob.size); + debug.log(msg); + destination = getImageDoc(); + imageBlob = blob; // save for review + reviewImage(); + // alert(msg) + }, contentType); // toBlob + } + + function reviewImage() { + sendButton.style.visibility = 'visible'; + retakeButton.style.visibility = 'visible'; + shutterButton.style.visibility = 'collapse'; // Hide for now + } + + function stopVideo() { + if (player && player.srcObject) { + player.srcObject.getVideoTracks().forEach(function (track) { + return track.stop(); + }); + } + } + function saveBlob(blob, destination) { + var contentType = blob.type; + // if (!confirm('Save picture to ' + destination + ' ?')) return + debug.log('Putting ' + blob.size + ' bytes of ' + contentType + ' to ' + destination) + // @@ TODO Remove casting + ; + store.fetcher.webOperation('PUT', destination.uri, { + data: blob, + contentType: contentType + }).then(function (_resp) { + debug.log('ok saved ' + destination); + stopVideo(); + doneCallback(destination); + }, function (err) { + stopVideo(); + alert(err); + }); + } + + // Attach the video stream to the video element and autoplay. + displayPlayer(); + return div; +} + +/** A button to capture a picture using camera + * @param {Docuemnt} dom - The Document object + * @param {IndexedForumla} store - The quadstore to store data in + * @param {fuunction} getImageDoc - returns NN of the image file to be created + * @param {function} doneCallback - called with the image taken + * @returns {DomElement} - A div element with the buton in it + * + * This expacts the buttton to a large control when it is pressed + */ + +function cameraButton(dom, store, getImageDoc, doneCallback) { + var div = dom.createElement('div'); + var but = widgets.button(dom, cameraIcon, 'Take picture'); + var control; + function restoreButton(_x) { + return _restoreButton.apply(this, arguments); + } + function _restoreButton() { + _restoreButton = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(imageDoc) { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + div.removeChild(control); + div.appendChild(but); + doneCallback(imageDoc); + case 3: + case "end": + return _context.stop(); } - this.setContext(node); - } else if (node.parentNode.nodeType === Node.DOCUMENT_NODE) { - this.setContext(node); + }, _callee); + })); + return _restoreButton.apply(this, arguments); + } + div.appendChild(but); + but.addEventListener('click', function (_event) { + div.removeChild(but); + control = cameraCaptureControl(dom, store, getImageDoc, restoreButton); + div.appendChild(control); + }); + return div; +} +//# sourceMappingURL=media-capture.js.map + +/***/ }), + +/***/ "./lib/messageArea.js": +/*!****************************!*\ + !*** ./lib/messageArea.js ***! + \****************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.messageArea = messageArea; +var _iconBase = __webpack_require__(/*! ./iconBase */ "./lib/iconBase.js"); +var login = _interopRequireWildcard(__webpack_require__(/*! ./login/login */ "./lib/login/login.js")); +var _solidLogic = __webpack_require__(/*! solid-logic */ "./node_modules/solid-logic/lib/index.js"); +var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); +var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "./node_modules/rdflib/esm/index.js")); +var style = _interopRequireWildcard(__webpack_require__(/*! ./style */ "./lib/style.js")); +var utils = _interopRequireWildcard(__webpack_require__(/*! ./utils */ "./lib/utils/index.js")); +var widgets = _interopRequireWildcard(__webpack_require__(/*! ./widgets */ "./lib/widgets/index.js")); +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); } +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; } +// Common code for a discussion are a of messages about something +// + +// pull in first avoid cross-refs + +var UI = { + icons: _iconBase.icons, + ns: ns, + rdf: rdf, + style: style, + widgets: widgets +}; +function messageArea(dom, kb, subject, messageStore, options) { + kb = kb || _solidLogic.solidLogicSingleton.store; + messageStore = messageStore.doc(); // No hash + var ns = UI.ns; + var WF = rdf.Namespace('http://www.w3.org/2005/01/wf/flow#'); + var DCT = rdf.Namespace('http://purl.org/dc/terms/'); + options = options || {}; + var newestFirst = !!options.newestFirst; + var messageBodyStyle = 'white-space: pre-wrap; width: 90%; font-size:100%; border: 0.07em solid #eee; padding: .2em 0.5em; margin: 0.1em 1em 0.1em 1em;'; + // 'font-size: 100%; margin: 0.1em 1em 0.1em 1em; background-color: white; white-space: pre-wrap; padding: 0.1em;' + + var div = dom.createElement('div'); + // eslint-disable-next-line prefer-const + var messageTable; // Shared by initial build and addMessageFromBindings + + var me; + var updater = _solidLogic.solidLogicSingleton.store.updater; + var anchor = function anchor(text, term) { + // If there is no link return an element anyway + var a = dom.createElement('a'); + if (term && term.uri) { + a.setAttribute('href', term.uri); + a.addEventListener('click', UI.widgets.openHrefInOutlineMode, true); + a.setAttribute('style', 'color: #3B5998; text-decoration: none; '); // font-weight: bold + } + + a.textContent = text; + return a; + }; + var mention = function mention(message, style) { + var pre = dom.createElement('pre'); + pre.setAttribute('style', style || 'color: grey'); + div.appendChild(pre); + pre.appendChild(dom.createTextNode(message)); + return pre; + }; + var announce = { + log: function log(message) { + mention(message, 'color: #111;'); + }, + warn: function warn(message) { + mention(message, 'color: #880;'); + }, + error: function error(message) { + mention(message, 'color: #800;'); + } + }; + + // Form for a new message + // + var newMessageForm = function newMessageForm() { + var form = dom.createElement('tr'); + var lhs = dom.createElement('td'); + var middle = dom.createElement('td'); + var rhs = dom.createElement('td'); + form.appendChild(lhs); + form.appendChild(middle); + form.appendChild(rhs); + form.AJAR_date = '9999-01-01T00:00:00Z'; // ISO format for field sort + + var sendMessage = function sendMessage() { + // titlefield.setAttribute('class','pendingedit') + // titlefield.disabled = true + field.setAttribute('class', 'pendingedit'); + field.disabled = true; + var sts = []; + var now = new Date(); + var timestamp = '' + now.getTime(); + var dateStamp = rdf.term(now); + // http://www.w3schools.com/jsref/jsref_obj_date.asp + var message = kb.sym(messageStore.uri + '#' + 'Msg' + timestamp); + sts.push(new rdf.Statement(subject, ns.wf('message'), message, messageStore)); + sts.push(new rdf.Statement(message, ns.sioc('content'), kb.literal(field.value), messageStore)); + sts.push(new rdf.Statement(message, DCT('created'), dateStamp, messageStore)); + if (me) { + sts.push(new rdf.Statement(message, ns.foaf('maker'), me, messageStore)); } - var queue = []; - // Fix for Firefox that includes the hash in the base URI - var removeHash = function removeHash(baseURI) { - // Fix for undefined baseURI property - if (!baseURI && options && options.baseURI) { - return options.baseURI; - } - var hash = baseURI.indexOf('#'); - if (hash >= 0) { - baseURI = baseURI.substring(0, hash); - } - if (options && options.baseURIMap) { - baseURI = options.baseURIMap(baseURI); + var sendComplete = function sendComplete(uri, success, body) { + if (!success) { + form.appendChild(UI.widgets.errorMessageBlock(dom, 'Error writing message: ' + body)); + } else { + var bindings = { + '?msg': message, + '?content': kb.literal(field.value), + '?date': dateStamp, + '?creator': me + }; + renderMessage(bindings, false); // not green + + field.value = ''; // clear from out for reuse + field.setAttribute('class', ''); + field.disabled = false; } - return baseURI; }; - queue.push({ - current: node, - context: this.push(null, removeHash(node.baseURI)) - }); - while (queue.length > 0) { - var item = queue.shift(); - if (item.parent) { - // Sequence Step 14: list triple generation - if (item.context.parent && item.context.parent.listMapping === item.listMapping) { - // Skip a child context with exactly the same mapping - continue; - } - // console.log("Generating lists for "+item.subject+", tag "+item.parent.localName) - for (var _predicate in item.listMapping) { - var list = item.listMapping[_predicate]; - if (list.length === 0) { - this.addTriple(item.parent, item.subject, _predicate, { - type: RDFaProcessor.objectURI, - value: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' - }); - continue; - } - var bnodes = []; - for (var _i = 0; _i < list.length; _i++) { - bnodes.push(this.newBlankNode()); - // this.newSubject(item.parent,bnodes[i]) - } - - for (var _i2 = 0; _i2 < bnodes.length; _i2++) { - this.addTriple(item.parent, bnodes[_i2], 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first', list[_i2]); - this.addTriple(item.parent, bnodes[_i2], 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest', { - type: RDFaProcessor.objectURI, - value: _i2 + 1 < bnodes.length ? bnodes[_i2 + 1] : 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' - }); - } - this.addTriple(item.parent, item.subject, _predicate, { - type: RDFaProcessor.objectURI, - value: bnodes[0] - }); + updater.update([], sts, sendComplete); + }; + form.appendChild(dom.createElement('br')); + var field, sendButton; + var turnOnInput = function turnOnInput() { + creatorAndDate(lhs, me, '', null); + field = dom.createElement('textarea'); + middle.innerHTML = ''; + middle.appendChild(field); + field.rows = 3; + // field.cols = 40 + field.setAttribute('style', messageBodyStyle + 'background-color: #eef;'); + field.addEventListener('keyup', function (e) { + // User preference? + if (e.keyCode === 13) { + if (!e.altKey) { + // Alt-Enter just adds a new line + sendMessage(); } - continue; } - var current = item.current; - var context = item.context; - // console.log("Tag: "+current.localName+", listMapping="+JSON.stringify(context.listMapping)) - // Sequence Step 1 - var skip = false; - var newSubject = null; - var currentObjectResource = null; - var typedResource = null; - var prefixes = context.prefixes; - var prefixesCopied = false; - var incomplete = []; - var listMapping = context.listMapping; - var listMappingDifferent = !context.parent; - var language = context.language; - var vocabulary = context.vocabulary; - // TODO: the "base" element may be used for HTML+RDFa 1.1 - base = this.parseURI(removeHash(current.baseURI)); - current.item = null; - // Sequence Step 2: set the default vocabulary - var vocabAtt = current.getAttributeNode('vocab'); - if (vocabAtt) { - var value = this.trim(vocabAtt.value); - if (value.length > 0) { - vocabulary = value; - var baseSubject = base.spec; - // this.newSubject(current,baseSubject) - this.addTriple(current, baseSubject, 'http://www.w3.org/ns/rdfa#usesVocabulary', { - type: RDFaProcessor.objectURI, - value: vocabulary - }); - } else { - vocabulary = this.vocabulary; - } - } - // Sequence Step 3: IRI mappings - // handle xmlns attributes - for (var i = 0; i < current.attributes.length; i++) { - var att = current.attributes[i]; - // if (att.namespaceURI=="http://www.w3.org/2000/xmlns/") { - if (att.nodeName.charAt(0) === 'x' && att.nodeName.indexOf('xmlns:') === 0) { - if (!prefixesCopied) { - prefixes = this.copyMappings(prefixes); - prefixesCopied = true; - } - var prefix = att.nodeName.substring(6); - // TODO: resolve relative? - var ref = RDFaProcessor.trim(att.value); - prefixes[prefix] = this.options.base ? _uri__WEBPACK_IMPORTED_MODULE_3__.join(ref, this.options.base) : ref; - } - } - // Handle prefix mappings (@prefix) - var prefixAtt = current.getAttributeNode('prefix'); - if (prefixAtt) { - if (!prefixesCopied) { - prefixes = this.copyMappings(prefixes); - prefixesCopied = true; - } - this.parsePrefixMappings(prefixAtt.value, prefixes); - } - // Sequence Step 4: language - var xmlLangAtt = null; - for (var _i3 = 0; !xmlLangAtt && _i3 < this.langAttributes.length; _i3++) { - xmlLangAtt = current.getAttributeNodeNS(this.langAttributes[_i3].namespaceURI, this.langAttributes[_i3].localName); - } - if (xmlLangAtt) { - var _value = RDFaProcessor.trim(xmlLangAtt.value); - if (_value.length > 0) { - language = _value; - } else { - language = null; - } - } - var relAtt = current.getAttributeNode('rel'); - var revAtt = current.getAttributeNode('rev'); - var typeofAtt = current.getAttributeNode('typeof'); - var propertyAtt = current.getAttributeNode('property'); - var datatypeAtt = current.getAttributeNode('datatype'); - var datetimeAtt = this.inHTMLMode ? current.getAttributeNode('datetime') : null; - var contentAtt = current.getAttributeNode('content'); - var aboutAtt = current.getAttributeNode('about'); - var srcAtt = current.getAttributeNode('src'); - var resourceAtt = current.getAttributeNode('resource'); - var hrefAtt = current.getAttributeNode('href'); - var inlistAtt = current.getAttributeNode('inlist'); - var relAttPredicates = []; - var predicate, values; - if (relAtt) { - values = this.tokenize(relAtt.value); - for (var _i4 = 0; _i4 < values.length; _i4++) { - predicate = this.parsePredicate(values[_i4], vocabulary, context.terms, prefixes, base, this.inHTMLMode && propertyAtt !== null); - if (predicate) { - relAttPredicates.push(predicate); - } - } - } - var revAttPredicates = []; - if (revAtt) { - values = this.tokenize(revAtt.value); - for (var _i5 = 0; _i5 < values.length; _i5++) { - predicate = this.parsePredicate(values[_i5], vocabulary, context.terms, prefixes, base, this.inHTMLMode && propertyAtt); - if (predicate) { - revAttPredicates.push(predicate); - } - } - } - // Section 3.1, bullet 7 - if (this.inHTMLMode && (relAtt || revAtt) && propertyAtt) { - if (relAttPredicates.length === 0) { - relAtt = null; - } - if (revAttPredicates.length === 0) { - revAtt = null; - } - } - if (relAtt || revAtt) { - // Sequence Step 6: establish new subject and value - if (aboutAtt) { - newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base); - } - if (typeofAtt) { - typedResource = newSubject; - } - if (!newSubject) { - if (current.parentNode.nodeType === Node.DOCUMENT_NODE) { - newSubject = removeHash(current.baseURI); - } else if (context.parentObject) { - // TODO: Verify: If the xml:base has been set and the parentObject is the baseURI of the parent, then the subject needs to be the new base URI - newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; - } - } - if (resourceAtt) { - currentObjectResource = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base); - } - if (!currentObjectResource) { - if (hrefAtt) { - currentObjectResource = this.resolveAndNormalize(base, encodeURI(hrefAtt.value)); - } else if (srcAtt) { - currentObjectResource = this.resolveAndNormalize(base, encodeURI(srcAtt.value)); - } else if (typeofAtt && !aboutAtt && !(this.inXHTMLMode && (current.localName === 'head' || current.localName === 'body'))) { - currentObjectResource = this.newBlankNode(); - } - } - if (typeofAtt && !aboutAtt && this.inXHTMLMode && (current.localName === 'head' || current.localName === 'body')) { - typedResource = newSubject; - } else if (typeofAtt && !aboutAtt) { - typedResource = currentObjectResource; - } - } else if (propertyAtt && !contentAtt && !datatypeAtt) { - // Sequence Step 5.1: establish a new subject - if (aboutAtt) { - newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base); - if (typeofAtt) { - typedResource = newSubject; - } - } - if (!newSubject && current.parentNode.nodeType === Node.DOCUMENT_NODE) { - newSubject = removeHash(current.baseURI); - if (typeofAtt) { - typedResource = newSubject; - } - } else if (!newSubject && context.parentObject) { - // TODO: Verify: If the xml:base has been set and the parentObject is the baseURI of the parent, then the subject needs to be the new base URI - newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; - } - if (typeofAtt && !typedResource) { - if (resourceAtt) { - typedResource = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base); - } - if (!typedResource && hrefAtt) { - typedResource = this.resolveAndNormalize(base, encodeURI(hrefAtt.value)); - } - if (!typedResource && srcAtt) { - typedResource = this.resolveAndNormalize(base, encodeURI(srcAtt.value)); - } - if (!typedResource && (this.inXHTMLMode || this.inHTMLMode) && (current.localName === 'head' || current.localName === 'body')) { - typedResource = newSubject; - } - if (!typedResource) { - typedResource = this.newBlankNode(); - } - currentObjectResource = typedResource; - } - // console.log(current.localName+", newSubject="+newSubject+", typedResource="+typedResource+", currentObjectResource="+currentObjectResource) - } else { - // Sequence Step 5.2: establish a new subject - if (aboutAtt) { - newSubject = this.parseSafeCURIEOrCURIEOrURI(aboutAtt.value, prefixes, base); - } - if (!newSubject && resourceAtt) { - newSubject = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base); - } - if (!newSubject && hrefAtt) { - newSubject = this.resolveAndNormalize(base, encodeURI(hrefAtt.value)); - } - if (!newSubject && srcAtt) { - newSubject = this.resolveAndNormalize(base, encodeURI(srcAtt.value)); - } - if (!newSubject) { - if (current.parentNode.nodeType === Node.DOCUMENT_NODE) { - newSubject = removeHash(current.baseURI); - } else if ((this.inXHTMLMode || this.inHTMLMode) && (current.localName === 'head' || current.localName === 'body')) { - newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; - } else if (typeofAtt) { - newSubject = this.newBlankNode(); - } else if (context.parentObject) { - // TODO: Verify: If the xml:base has been set and the parentObject is the baseURI of the parent, then the subject needs to be the new base URI - newSubject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; - if (!propertyAtt) { - skip = true; - } - } - } - if (typeofAtt) { - typedResource = newSubject; - } - } - // console.log(current.tagName+": newSubject="+newSubject+", currentObjectResource="+currentObjectResource+", typedResource="+typedResource+", skip="+skip) - // var rdfaData = null - if (newSubject) { - // this.newSubject(current,newSubject) - if (aboutAtt || resourceAtt || typedResource) { - var id = newSubject; - if (typeofAtt && !aboutAtt && !resourceAtt && currentObjectResource) { - id = currentObjectResource; - } - // console.log("Setting data attribute for "+current.localName+" for subject "+id) - this.newSubjectOrigin(current, id); - } - } - // Sequence Step 7: generate type triple - if (typedResource) { - values = this.tokenize(typeofAtt.value); - for (var _i6 = 0; _i6 < values.length; _i6++) { - var object = this.parseTermOrCURIEOrAbsURI(values[_i6], vocabulary, context.terms, prefixes, base); - if (object) { - this.addTriple(current, typedResource, RDFaProcessor.typeURI, { - type: RDFaProcessor.objectURI, - value: object - }); - } - } - } - // Sequence Step 8: new list mappings if there is a new subject - // console.log("Step 8: newSubject="+newSubject+", context.parentObject="+context.parentObject) - if (newSubject && newSubject !== context.parentObject) { - // console.log("Generating new list mapping for "+newSubject) - listMapping = {}; - listMappingDifferent = true; - } - // Sequence Step 9: generate object triple - if (currentObjectResource) { - if (relAtt && inlistAtt) { - for (var _i7 = 0; _i7 < relAttPredicates.length; _i7++) { - var _list = listMapping[relAttPredicates[_i7]]; - if (!_list) { - _list = []; - listMapping[relAttPredicates[_i7]] = _list; - } - _list.push({ - type: RDFaProcessor.objectURI, - value: currentObjectResource - }); - } - } else if (relAtt) { - for (var _i8 = 0; _i8 < relAttPredicates.length; _i8++) { - this.addTriple(current, newSubject, relAttPredicates[_i8], { - type: RDFaProcessor.objectURI, - value: currentObjectResource - }); - } - } - if (revAtt) { - for (var _i9 = 0; _i9 < revAttPredicates.length; _i9++) { - this.addTriple(current, currentObjectResource, revAttPredicates[_i9], { - type: RDFaProcessor.objectURI, - value: newSubject - }); - } - } - } else { - // Sequence Step 10: incomplete triples - if (newSubject && !currentObjectResource && (relAtt || revAtt)) { - currentObjectResource = this.newBlankNode(); - // alert(current.tagName+": generated blank node, newSubject="+newSubject+" currentObjectResource="+currentObjectResource) - } - - if (relAtt && inlistAtt) { - for (var _i10 = 0; _i10 < relAttPredicates.length; _i10++) { - var _list2 = listMapping[relAttPredicates[_i10]]; - if (!_list2) { - _list2 = []; - listMapping[predicate] = _list2; - } - // console.log("Adding incomplete list for "+predicate) - incomplete.push({ - predicate: relAttPredicates[_i10], - list: _list2 - }); - } - } else if (relAtt) { - for (var _i11 = 0; _i11 < relAttPredicates.length; _i11++) { - incomplete.push({ - predicate: relAttPredicates[_i11], - forward: true - }); - } - } - if (revAtt) { - for (var _i12 = 0; _i12 < revAttPredicates.length; _i12++) { - incomplete.push({ - predicate: revAttPredicates[_i12], - forward: false - }); - } - } - } - // Step 11: Current property values - if (propertyAtt) { - var datatype = null; - var content = null; - if (datatypeAtt) { - datatype = datatypeAtt.value === '' ? RDFaProcessor.PlainLiteralURI : this.parseTermOrCURIEOrAbsURI(datatypeAtt.value, vocabulary, context.terms, prefixes, base); - if (datetimeAtt && !contentAtt) { - content = datetimeAtt.value; - } else { - content = datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI ? null : contentAtt ? contentAtt.value : current.textContent; - } - } else if (contentAtt) { - datatype = RDFaProcessor.PlainLiteralURI; - content = contentAtt.value; - } else if (datetimeAtt) { - content = datetimeAtt.value; - datatype = RDFaProcessor.deriveDateTimeType(content); - if (!datatype) { - datatype = RDFaProcessor.PlainLiteralURI; - } - } else if (!relAtt && !revAtt) { - if (resourceAtt) { - content = this.parseSafeCURIEOrCURIEOrURI(resourceAtt.value, prefixes, base); - } - if (!content && hrefAtt) { - content = this.resolveAndNormalize(base, encodeURI(hrefAtt.value)); - } else if (!content && srcAtt) { - content = this.resolveAndNormalize(base, encodeURI(srcAtt.value)); - } - if (content) { - datatype = RDFaProcessor.objectURI; - } - } - if (!datatype) { - if (typeofAtt && !aboutAtt) { - datatype = RDFaProcessor.objectURI; - content = typedResource; - } else { - content = current.textContent; - if (this.inHTMLMode && current.localName === 'time') { - datatype = RDFaProcessor.deriveDateTimeType(content); - } - if (!datatype) { - datatype = RDFaProcessor.PlainLiteralURI; - } - } - } - values = this.tokenize(propertyAtt.value); - for (var _i13 = 0; _i13 < values.length; _i13++) { - var _predicate2 = this.parsePredicate(values[_i13], vocabulary, context.terms, prefixes, base); - if (_predicate2) { - if (inlistAtt) { - var _list3 = listMapping[_predicate2]; - if (!_list3) { - _list3 = []; - listMapping[_predicate2] = _list3; - } - _list3.push(datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI ? { - type: datatype, - value: current.childNodes - } : { - type: datatype || RDFaProcessor.PlainLiteralURI, - value: content, - language: language - }); - } else { - if (datatype === RDFaProcessor.XMLLiteralURI || datatype === RDFaProcessor.HTMLLiteralURI) { - this.addTriple(current, newSubject, _predicate2, { - type: datatype, - value: current.childNodes - }); - } else { - this.addTriple(current, newSubject, _predicate2, { - type: datatype || RDFaProcessor.PlainLiteralURI, - value: content, - language: language - }); - // console.log(newSubject+" "+predicate+"="+content) - } - } - } - } - } - // Sequence Step 12: complete incomplete triples with new subject - if (newSubject && !skip) { - for (var _i14 = 0; _i14 < context.incomplete.length; _i14++) { - if (context.incomplete[_i14].list) { - // console.log("Adding subject "+newSubject+" to list for "+context.incomplete[i].predicate) - // TODO: it is unclear what to do here - context.incomplete[_i14].list.push({ - type: RDFaProcessor.objectURI, - value: newSubject - }); - } else if (context.incomplete[_i14].forward) { - // console.log(current.tagName+": completing forward triple "+context.incomplete[i].predicate+" with object="+newSubject) - this.addTriple(current, context.subject, context.incomplete[_i14].predicate, { - type: RDFaProcessor.objectURI, - value: newSubject - }); - } else { - // console.log(current.tagName+": completing reverse triple with object="+context.subject) - this.addTriple(current, newSubject, context.incomplete[_i14].predicate, { - type: RDFaProcessor.objectURI, - value: context.subject - }); - } - } - } - var childContext = null; - var listSubject = newSubject; - if (skip) { - // TODO: should subject be null? - childContext = this.push(context, context.subject); - // TODO: should the entObject be passed along? If not, then intermediary children will keep properties from being associated with incomplete triples. - // TODO: Verify: if the current baseURI has changed and the parentObject is the parent's base URI, then the baseURI should change - childContext.parentObject = removeHash(current.parentNode.baseURI) === context.parentObject ? removeHash(current.baseURI) : context.parentObject; - childContext.incomplete = context.incomplete; - childContext.language = language; - childContext.prefixes = prefixes; - childContext.vocabulary = vocabulary; - } else { - childContext = this.push(context, newSubject); - childContext.parentObject = currentObjectResource || newSubject || context.subject; - childContext.prefixes = prefixes; - childContext.incomplete = incomplete; - if (currentObjectResource) { - // console.log("Generating new list mapping for "+currentObjectResource) - listSubject = currentObjectResource; - listMapping = {}; - listMappingDifferent = true; - } - childContext.listMapping = listMapping; - childContext.language = language; - childContext.vocabulary = vocabulary; - } - if (listMappingDifferent) { - // console.log("Pushing list parent "+current.localName) - queue.unshift({ - parent: current, - context: context, - subject: listSubject, - listMapping: listMapping - }); - } - for (var child = current.lastChild; child; child = child.previousSibling) { - if (child.nodeType === Node.ELEMENT_NODE) { - // console.log("Pushing child "+child.localName) - // child.baseURI = current.baseURI - queue.unshift({ - current: child, - context: childContext - }); - } - } - } - if (this.inHTMLMode) { - this.copyProperties(); - } - for (var _i15 = 0; _i15 < this.finishedHandlers.length; _i15++) { - this.finishedHandlers[_i15](node); - } - } - }, { - key: "push", - value: function push(parent, subject) { - return { - parent: parent, - subject: subject || (parent ? parent.subject : null), - parentObject: null, - incomplete: [], - listMapping: parent ? parent.listMapping : {}, - language: parent ? parent.language : this.language, - prefixes: parent ? parent.prefixes : this.target.graph.prefixes, - terms: parent ? parent.terms : this.target.graph.terms, - vocabulary: parent ? parent.vocabulary : this.vocabulary - }; - } - }, { - key: "resolveAndNormalize", - value: function resolveAndNormalize(base, uri) { - // console.log("Joining " + uri + " to " + base + " making " + Uri.join(uri, base)) - return _uri__WEBPACK_IMPORTED_MODULE_3__.join(uri, base); // @@ normalize? - } - }, { - key: "setContext", - value: function setContext(node) { - // We only recognized XHTML+RDFa 1.1 if the version is set propertyly - if (node.localName === 'html' && node.getAttribute('version') === 'XHTML+RDFa 1.1') { - this.setXHTMLContext(); - } else if (node.localName === 'html' || node.namespaceURI === 'http://www.w3.org/1999/xhtml') { - if (typeof document !== 'undefined' && document.doctype) { - if (document.doctype.publicId === '-//W3C//DTD XHTML+RDFa 1.0//EN' && document.doctype.systemId === 'http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd') { - console.log('WARNING: RDF 1.0 is not supported. Defaulting to HTML5 mode.'); - this.setHTMLContext(); - } else if (document.doctype.publicId === '-//W3C//DTD XHTML+RDFa 1.1//EN' && document.doctype.systemId === 'http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd') { - this.setXHTMLContext(); - } else { - this.setHTMLContext(); - } - } else { - this.setHTMLContext(); - } - } else { - this.setXMLContext(); - } - } - }, { - key: "setHTMLContext", - value: function setHTMLContext() { - this.setInitialContext(); - this.langAttributes = [{ - namespaceURI: 'http://www.w3.org/XML/1998/namespace', - localName: 'lang' - }, { - namespaceURI: null, - localName: 'lang' - }]; - this.inXHTMLMode = false; - this.inHTMLMode = true; - } - }, { - key: "setInitialContext", - value: function setInitialContext() { - this.vocabulary = null; - // By default, the prefixes are terms are loaded to the RDFa 1.1. standard within the graph constructor - this.langAttributes = [{ - namespaceURI: 'http://www.w3.org/XML/1998/namespace', - localName: 'lang' - }]; - } - }, { - key: "setXHTMLContext", - value: function setXHTMLContext() { - this.setInitialContext(); - this.inXHTMLMode = true; - this.inHTMLMode = false; - this.langAttributes = [{ - namespaceURI: 'http://www.w3.org/XML/1998/namespace', - localName: 'lang' - }, { - namespaceURI: null, - localName: 'lang' - }]; - // From http://www.w3.org/2011/rdfa-context/xhtml-rdfa-1.1 - this.target.graph.terms['alternate'] = 'http://www.w3.org/1999/xhtml/vocab#alternate'; - this.target.graph.terms['appendix'] = 'http://www.w3.org/1999/xhtml/vocab#appendix'; - this.target.graph.terms['bookmark'] = 'http://www.w3.org/1999/xhtml/vocab#bookmark'; - this.target.graph.terms['cite'] = 'http://www.w3.org/1999/xhtml/vocab#cite'; - this.target.graph.terms['chapter'] = 'http://www.w3.org/1999/xhtml/vocab#chapter'; - this.target.graph.terms['contents'] = 'http://www.w3.org/1999/xhtml/vocab#contents'; - this.target.graph.terms['copyright'] = 'http://www.w3.org/1999/xhtml/vocab#copyright'; - this.target.graph.terms['first'] = 'http://www.w3.org/1999/xhtml/vocab#first'; - this.target.graph.terms['glossary'] = 'http://www.w3.org/1999/xhtml/vocab#glossary'; - this.target.graph.terms['help'] = 'http://www.w3.org/1999/xhtml/vocab#help'; - this.target.graph.terms['icon'] = 'http://www.w3.org/1999/xhtml/vocab#icon'; - this.target.graph.terms['index'] = 'http://www.w3.org/1999/xhtml/vocab#index'; - this.target.graph.terms['last'] = 'http://www.w3.org/1999/xhtml/vocab#last'; - this.target.graph.terms['license'] = 'http://www.w3.org/1999/xhtml/vocab#license'; - this.target.graph.terms['meta'] = 'http://www.w3.org/1999/xhtml/vocab#meta'; - this.target.graph.terms['next'] = 'http://www.w3.org/1999/xhtml/vocab#next'; - this.target.graph.terms['prev'] = 'http://www.w3.org/1999/xhtml/vocab#prev'; - this.target.graph.terms['previous'] = 'http://www.w3.org/1999/xhtml/vocab#previous'; - this.target.graph.terms['section'] = 'http://www.w3.org/1999/xhtml/vocab#section'; - this.target.graph.terms['stylesheet'] = 'http://www.w3.org/1999/xhtml/vocab#stylesheet'; - this.target.graph.terms['subsection'] = 'http://www.w3.org/1999/xhtml/vocab#subsection'; - this.target.graph.terms['start'] = 'http://www.w3.org/1999/xhtml/vocab#start'; - this.target.graph.terms['top'] = 'http://www.w3.org/1999/xhtml/vocab#top'; - this.target.graph.terms['up'] = 'http://www.w3.org/1999/xhtml/vocab#up'; - this.target.graph.terms['p3pv1'] = 'http://www.w3.org/1999/xhtml/vocab#p3pv1'; - // other - this.target.graph.terms['related'] = 'http://www.w3.org/1999/xhtml/vocab#related'; - this.target.graph.terms['role'] = 'http://www.w3.org/1999/xhtml/vocab#role'; - this.target.graph.terms['transformation'] = 'http://www.w3.org/1999/xhtml/vocab#transformation'; - } - }, { - key: "setXMLContext", - value: function setXMLContext() { - this.setInitialContext(); - this.inXHTMLMode = false; - this.inHTMLMode = false; - } - }, { - key: "tokenize", - value: function tokenize(str) { - return this.trim(str).split(/\s+/); - } - }, { - key: "toRDFNodeObject", - value: function toRDFNodeObject(x) { - var _this = this; - if (typeof x === 'undefined') return undefined; - if (typeof x === 'string') { - if (x.substring(0, 2) === '_:') { - if (typeof this.blankNodes[x.substring(2)] === 'undefined') { - this.blankNodes[x.substring(2)] = new _blank_node__WEBPACK_IMPORTED_MODULE_4__["default"](x.substring(2)); - } - return this.blankNodes[x.substring(2)]; - } - return _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].namedNode(x); - } - switch (x.type) { - case RDFaProcessor.objectURI: - if (x.value.substring(0, 2) === '_:') { - if (typeof this.blankNodes[x.value.substring(2)] === 'undefined') { - this.blankNodes[x.value.substring(2)] = new _blank_node__WEBPACK_IMPORTED_MODULE_4__["default"](x.value.substring(2)); - } - return this.blankNodes[x.value.substring(2)]; - } - return _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].namedNode(x.value); - case RDFaProcessor.PlainLiteralURI: - return new _literal__WEBPACK_IMPORTED_MODULE_5__["default"](x.value, x.language || ''); - case RDFaProcessor.XMLLiteralURI: - case RDFaProcessor.HTMLLiteralURI: - var string = ''; - Object.keys(x.value).forEach(function (i) { - string += _utils_js__WEBPACK_IMPORTED_MODULE_6__.domToString(x.value[i], _this.htmlOptions); - }); - return new _literal__WEBPACK_IMPORTED_MODULE_5__["default"](string, '', new _named_node__WEBPACK_IMPORTED_MODULE_7__["default"](x.type)); - default: - return new _literal__WEBPACK_IMPORTED_MODULE_5__["default"](x.value, '', new _named_node__WEBPACK_IMPORTED_MODULE_7__["default"](x.type)); - } - } - }, { - key: "trim", - value: function trim(str) { - return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); - } - }], [{ - key: "parseRDFaDOM", - value: function parseRDFaDOM(dom, kb, base) { - var p = new RDFaProcessor(kb, { - 'base': base - }); - // Cannot assign to read only property 'baseURI' of object '#': - if (!dom.baseURI) { - // Note this became a read-only attribute some time before 2018 - dom.baseURI = base; // oinly set if not already set - } - - p.process(dom, { - baseURI: base - }); - } - }, { - key: "tokenize", - value: function tokenize(str) { - return this.trim(str).split(/\s+/); - } - }, { - key: "trim", - value: function trim(str) { - return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); - } - }]); - return RDFaProcessor; -}(); - -RDFaProcessor.XMLLiteralURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#XMLLiteral'; -RDFaProcessor.HTMLLiteralURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML'; -RDFaProcessor.PlainLiteralURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#PlainLiteral'; -RDFaProcessor.objectURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#object'; -RDFaProcessor.typeURI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'; -RDFaProcessor.nameChar = "[-A-Z_a-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u10000-\uEFFFF.0-9\xB7\u0300-\u036F\u203F-\u2040]"; -RDFaProcessor.nameStartChar = "[A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\xFF\u0100-\u0131\u0134-\u013E\u0141-\u0148\u014A-\u017E\u0180-\u01C3\u01CD-\u01F0\u01F4-\u01F5\u01FA-\u0217\u0250-\u02A8\u02BB-\u02C1\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03CE\u03D0-\u03D6\u03DA\u03DC\u03DE\u03E0\u03E2-\u03F3\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E-\u0481\u0490-\u04C4\u04C7-\u04C8\u04CB-\u04CC\u04D0-\u04EB\u04EE-\u04F5\u04F8-\u04F9\u0531-\u0556\u0559\u0561-\u0586\u05D0-\u05EA\u05F0-\u05F2\u0621-\u063A\u0641-\u064A\u0671-\u06B7\u06BA-\u06BE\u06C0-\u06CE\u06D0-\u06D3\u06D5\u06E5-\u06E6\u0905-\u0939\u093D\u0958-\u0961\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8B\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AE0\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B36-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB5\u0BB7-\u0BB9\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CDE\u0CE0-\u0CE1\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D28\u0D2A-\u0D39\u0D60-\u0D61\u0E01-\u0E2E\u0E30\u0E32-\u0E33\u0E40-\u0E45\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EAE\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0F40-\u0F47\u0F49-\u0F69\u10A0-\u10C5\u10D0-\u10F6\u1100\u1102-\u1103\u1105-\u1107\u1109\u110B-\u110C\u110E-\u1112\u113C\u113E\u1140\u114C\u114E\u1150\u1154-\u1155\u1159\u115F-\u1161\u1163\u1165\u1167\u1169\u116D-\u116E\u1172-\u1173\u1175\u119E\u11A8\u11AB\u11AE-\u11AF\u11B7-\u11B8\u11BA\u11BC-\u11C2\u11EB\u11F0\u11F9\u1E00-\u1E9B\u1EA0-\u1EF9\u1F00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2126\u212A-\u212B\u212E\u2180-\u2182\u3041-\u3094\u30A1-\u30FA\u3105-\u312C\uAC00-\uD7A3\u4E00-\u9FA5\u3007\u3021-\u3029_]"; -RDFaProcessor.NCNAME = new RegExp('^' + RDFaProcessor.nameStartChar + RDFaProcessor.nameChar + '*$'); - -/* -RDFaProcessor.prototype.resolveAndNormalize = function(base,href) { - var u = base.resolve(href) - var parsed = this.parseURI(u) - parsed.normalize() - return parsed.spec -} -*/ - -RDFaProcessor.dateTimeTypes = [{ - pattern: /-?P(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+(?:\.[0-9]+)?S)?)?/, - type: 'http://www.w3.org/2001/XMLSchema#duration' -}, { - pattern: /-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9]T(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/, - type: 'http://www.w3.org/2001/XMLSchema#dateTime' -}, { - pattern: /-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]-[0-9][0-9](?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/, - type: 'http://www.w3.org/2001/XMLSchema#date' -}, { - pattern: /(?:[0-1][0-9]|2[0-4]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]+)?(?:Z|[+\-][0-9][0-9]:[0-9][0-9])?/, - type: 'http://www.w3.org/2001/XMLSchema#time' -}, { - pattern: /-?(?:[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9])-[0-9][0-9]/, - type: 'http://www.w3.org/2001/XMLSchema#gYearMonth' -}, { - pattern: /-?[1-9][0-9][0-9][0-9]|0[1-9][0-9][0-9]|00[1-9][0-9]|000[1-9]/, - type: 'http://www.w3.org/2001/XMLSchema#gYear' -}]; -var parseRDFaDOM = RDFaProcessor.parseRDFaDOM; - - -/***/ }), - -/***/ "../rdflib/esm/rdfxmlparser.js": -/*!*************************************!*\ - !*** ../rdflib/esm/rdfxmlparser.js ***! - \*************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ RDFParser) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); - - - -/** - * RDF/XML PARSER - * - * Parser believed to be in full positive RDF/XML parsing compliance - * with the possible exception of handling deprecated RDF attributes - * appropriately. Parser is believed to comply fully with other W3C - * and industry standards where appropriate (DOM, ECMAScript, &c.) - * - * Author: David Sheets - * - * W3C® SOFTWARE NOTICE AND LICENSE - * http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231 - * This work (and included software, documentation such as READMEs, or - * other related items) is being provided by the copyright holders under - * the following license. By obtaining, using and/or copying this work, - * you (the licensee) agree that you have read, understood, and will - * comply with the following terms and conditions. - * - * Permission to copy, modify, and distribute this software and its - * documentation, with or without modification, for any purpose and - * without fee or royalty is hereby granted, provided that you include - * the following on ALL copies of the software and documentation or - * portions thereof, including modifications: - * - * 1. The full text of this NOTICE in a location viewable to users of - * the redistributed or derivative work. - * 2. Any pre-existing intellectual property disclaimers, notices, or terms and - * conditions. If none exist, the W3C Software Short Notice should be - * included (hypertext is preferred, text is permitted) within the body - * of any redistributed or derivative code. - * 3. Notice of any changes or modifications to the files, including the - * date changes were made. (We recommend you provide URIs to the location - * from which the code is derived.) - * - * THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT - * HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS - * FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR - * DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, - * TRADEMARKS OR OTHER RIGHTS. - * - * COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL - * OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR - * DOCUMENTATION. - * - * The name and trademarks of copyright holders may NOT be used in - * advertising or publicity pertaining to the software without specific, - * written prior permission. Title to copyright in this software and any - * associated documentation will at all times remain with copyright - * holders. - */ -/** - * @class RDFParser resource object tied to an RDFStore - * - * @author David Sheets - * -*/ - -var RDFParser = /*#__PURE__*/function () { - /* - * @constructor - * @param {RDFStore} store An RDFStore object - */ - function RDFParser(store) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, RDFParser); - /** Our triple store reference @private */ - - this.store = store; /** Our identified blank nodes @private */ - this.bnodes = {}; /** A context for context-aware stores @private */ - this.why = null; /** Reification flag */ - this.reify = false; - } - - /** Standard namespaces that we know how to handle @final - * @member RDFParser - */ - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(RDFParser, [{ - key: "frameFactory", - value: - /** - * Frame class for namespace and base URI lookups - * Base lookups will always resolve because the parser knows - * the default base. - * - * @private - */ - - function frameFactory(parser, parent, element) { - return { - 'NODE': 1, - 'ARC': 2, - 'parent': parent, - 'parser': parser, - 'store': parser.store, - 'element': element, - 'lastChild': 0, - 'base': null, - 'lang': null, - 'node': null, - 'nodeType': null, - 'listIndex': 1, - 'rdfid': null, - 'datatype': null, - 'collection': false, - /** Terminate the frame and notify the store that we're done */ - 'terminateFrame': function terminateFrame() { - if (this.collection) { - this.node.close(); - } - }, - /** Add a symbol of a certain type to the this frame */'addSymbol': function addSymbol(type, uri) { - uri = _uri__WEBPACK_IMPORTED_MODULE_3__.join(uri, this.base); - this.node = this.store.sym(uri); - this.nodeType = type; - }, - /** Load any constructed triples into the store */'loadTriple': function loadTriple() { - if (this.parent.parent.collection) { - this.parent.parent.node.append(this.node); - } else { - this.store.add(this.parent.parent.node, this.parent.node, this.node, this.parser.why); - } - if (this.parent.rdfid != null) { - // reify - var triple = this.store.sym(_uri__WEBPACK_IMPORTED_MODULE_3__.join('#' + this.parent.rdfid, this.base)); - this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'type'), this.store.sym(RDFParser.ns.RDF + 'Statement'), this.parser.why); - this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'subject'), this.parent.parent.node, this.parser.why); - this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'predicate'), this.parent.node, this.parser.why); - this.store.add(triple, this.store.sym(RDFParser.ns.RDF + 'object'), this.node, this.parser.why); - } - }, - /** Check if it's OK to load a triple */'isTripleToLoad': function isTripleToLoad() { - return this.parent != null && this.parent.parent != null && this.nodeType === this.NODE && this.parent.nodeType === this.ARC && this.parent.parent.nodeType === this.NODE; - }, - /** Add a symbolic node to this frame */'addNode': function addNode(uri) { - this.addSymbol(this.NODE, uri); - if (this.isTripleToLoad()) { - this.loadTriple(); - } - }, - /** Add a collection node to this frame */'addCollection': function addCollection() { - this.nodeType = this.NODE; - this.node = this.store.collection(); - this.collection = true; - if (this.isTripleToLoad()) { - this.loadTriple(); - } - }, - /** Add a collection arc to this frame */'addCollectionArc': function addCollectionArc() { - this.nodeType = this.ARC; - }, - /** Add a bnode to this frame */'addBNode': function addBNode(id) { - if (id != null) { - if (this.parser.bnodes[id] != null) { - this.node = this.parser.bnodes[id]; - } else { - this.node = this.parser.bnodes[id] = this.store.bnode(); - } - } else { - this.node = this.store.bnode(); - } - this.nodeType = this.NODE; - if (this.isTripleToLoad()) { - this.loadTriple(); - } - }, - /** Add an arc or property to this frame */'addArc': function addArc(uri) { - if (uri === RDFParser.ns.RDF + 'li') { - uri = RDFParser.ns.RDF + '_' + this.parent.listIndex; - this.parent.listIndex++; - } - this.addSymbol(this.ARC, uri); - }, - /** Add a literal to this frame */'addLiteral': function addLiteral(value) { - if (this.parent.datatype && this.parent.datatype !== RDFParser.ns.RDF + 'langString') { - this.node = this.store.literal(value, this.store.sym(this.parent.datatype)); - } else { - this.node = this.store.literal(value, this.lang); - } - this.nodeType = this.NODE; - if (this.isTripleToLoad()) { - this.loadTriple(); - } - } - }; - } - - // from the OpenLayers source .. needed to get around IE problems. - }, { - key: "getAttributeNodeNS", - value: function getAttributeNodeNS(node, uri, name) { - var attributeNode = null; - if (node.getAttributeNodeNS) { - attributeNode = node.getAttributeNodeNS(uri, name); - } else { - var attributes = node.attributes; - var potentialNode, fullName; - for (var i = 0; i < attributes.length; ++i) { - potentialNode = attributes[i]; - if (potentialNode.namespaceURI === uri) { - fullName = potentialNode.prefix ? potentialNode.prefix + ':' + name : name; - if (fullName === potentialNode.nodeName) { - attributeNode = potentialNode; - break; - } - } - } - } - return attributeNode; - } - - /** - * Build our initial scope frame and parse the DOM into triples - * @param {HTMLDocument} document The DOM to parse - * @param {String} base The base URL to use - * @param {Object} why The context to which this resource belongs - */ - }, { - key: "parse", - value: function parse(document, base, why) { - var children = document.childNodes; // clean up for the next run - this.cleanParser(); // figure out the root element - var root; - if (document.nodeType === RDFParser.nodeType.DOCUMENT) { - for (var c = 0; c < children.length; c++) { - if (children[c].nodeType === RDFParser.nodeType.ELEMENT) { - root = children[c]; - break; - } - } - } else if (document.nodeType === RDFParser.nodeType.ELEMENT) { - root = document; - } else { - throw new Error("RDFParser: can't find root in " + base + '. Halting. '); - // return false - } - - this.why = why; // our topmost frame - var f = this.frameFactory(this); - this.base = base; - f.base = base; - f.lang = null; // was '' but can't have langs like that 2015 (!) - this.parseDOM(this.buildFrame(f, root)); - return true; - } - }, { - key: "parseDOM", - value: function parseDOM(frame) { - // a DOM utility function used in parsing - var rdfid; - var elementURI = function (el) { - var result = ''; - if (el.namespaceURI == null) { - throw new Error('RDF/XML syntax error: No namespace for ' + el.localName + ' in ' + this.base); - } - if (el.namespaceURI) { - result = result + el.namespaceURI; - } - if (el.localName) { - result = result + el.localName; - } else if (el.nodeName) { - if (el.nodeName.indexOf(':') >= 0) result = result + el.nodeName.split(':')[1];else result = result + el.nodeName; - } - return result; - }.bind(this); - var dig = true; // if we'll dig down in the tree on the next iter - while (frame.parent) { - var dom = frame.element; - var attrs = dom.attributes; - if (dom.nodeType === RDFParser.nodeType.TEXT || dom.nodeType === RDFParser.nodeType.CDATA_SECTION) { - // we have a literal - if (frame.parent.nodeType === frame.NODE) { - // must have had attributes, store as rdf:value - frame.addArc(RDFParser.ns.RDF + 'value'); - frame = this.buildFrame(frame); - } - frame.addLiteral(dom.nodeValue); - } else if (elementURI(dom) !== RDFParser.ns.RDF + 'RDF') { - // not root - if (frame.parent && frame.parent.collection) { - // we're a collection element - frame.addCollectionArc(); - frame = this.buildFrame(frame, frame.element); - frame.parent.element = null; - } - if (!frame.parent || !frame.parent.nodeType || frame.parent.nodeType === frame.ARC) { - // we need a node - var about = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'about'); - rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'ID'); - if (about && rdfid) { - throw new Error('RDFParser: ' + dom.nodeName + ' has both rdf:id and rdf:about.' + ' Halting. Only one of these' + ' properties may be specified on a' + ' node.'); - } - if (!about && rdfid) { - frame.addNode('#' + rdfid.nodeValue); - dom.removeAttributeNode(rdfid); - } else if (about == null && rdfid == null) { - var bnid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'nodeID'); - if (bnid) { - frame.addBNode(bnid.nodeValue); - dom.removeAttributeNode(bnid); - } else { - frame.addBNode(); - } - } else { - frame.addNode(about.nodeValue); - dom.removeAttributeNode(about); - } - // Typed nodes - var rdftype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'type'); - if (RDFParser.ns.RDF + 'Description' !== elementURI(dom)) { - rdftype = { - 'nodeValue': elementURI(dom) - }; - } - if (rdftype != null) { - this.store.add(frame.node, this.store.sym(RDFParser.ns.RDF + 'type'), this.store.sym(_uri__WEBPACK_IMPORTED_MODULE_3__.join(rdftype.nodeValue, frame.base)), this.why); - if (rdftype.nodeName) { - dom.removeAttributeNode(rdftype); - } - } - // Property Attributes - for (var x = attrs.length - 1; x >= 0; x--) { - this.store.add(frame.node, this.store.sym(elementURI(attrs[x])), this.store.literal(attrs[x].nodeValue, frame.lang), this.why); - } - } else { - // we should add an arc (or implicit bnode+arc) - frame.addArc(elementURI(dom)); // save the arc's rdf:ID if it has one - if (this.reify) { - rdfid = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'ID'); - if (rdfid) { - frame.rdfid = rdfid.nodeValue; - dom.removeAttributeNode(rdfid); - } - } - var parsetype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'parseType'); - var datatype = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'datatype'); - if (datatype) { - frame.datatype = datatype.nodeValue; - dom.removeAttributeNode(datatype); - } - if (parsetype) { - var nv = parsetype.nodeValue; - if (nv === 'Literal') { - frame.datatype = RDFParser.ns.RDF + 'XMLLiteral'; - frame = this.buildFrame(frame); - // Don't include the literal node, only its children - frame.addLiteral(dom.childNodes); - dig = false; - } else if (nv === 'Resource') { - frame = this.buildFrame(frame, frame.element); - frame.parent.element = null; - frame.addBNode(); - } else if (nv === 'Collection') { - frame = this.buildFrame(frame, frame.element); - frame.parent.element = null; - frame.addCollection(); - } - dom.removeAttributeNode(parsetype); - } - if (attrs.length !== 0) { - var resource = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'resource'); - var bnid2 = this.getAttributeNodeNS(dom, RDFParser.ns.RDF, 'nodeID'); - frame = this.buildFrame(frame); - if (resource) { - frame.addNode(resource.nodeValue); - dom.removeAttributeNode(resource); - } else { - if (bnid2) { - frame.addBNode(bnid2.nodeValue); - dom.removeAttributeNode(bnid2); - } else { - frame.addBNode(); - } - } - for (var x1 = attrs.length - 1; x1 >= 0; x1--) { - var f = this.buildFrame(frame); - f.addArc(elementURI(attrs[x1])); - if (elementURI(attrs[x1]) === RDFParser.ns.RDF + 'type') { - this.buildFrame(f).addNode(attrs[x1].nodeValue); - } else { - this.buildFrame(f).addLiteral(attrs[x1].nodeValue); - } - } - } else if (dom.childNodes.length === 0) { - this.buildFrame(frame).addLiteral(''); - } - } - } // rdf:RDF - // dig dug - dom = frame.element; - while (frame.parent) { - var pframe = frame; - while (dom == null) { - frame = frame.parent; - dom = frame.element; - } - var candidate = dom.childNodes && dom.childNodes[frame.lastChild]; - if (!candidate || !dig) { - frame.terminateFrame(); - if (!(frame = frame.parent)) { - break; - } // done - dom = frame.element; - dig = true; - } else if (candidate.nodeType !== RDFParser.nodeType.ELEMENT && candidate.nodeType !== RDFParser.nodeType.TEXT && candidate.nodeType !== RDFParser.nodeType.CDATA_SECTION || (candidate.nodeType === RDFParser.nodeType.TEXT || candidate.nodeType === RDFParser.nodeType.CDATA_SECTION) && dom.childNodes.length !== 1) { - frame.lastChild++; - } else { - // not a leaf - frame.lastChild++; - frame = this.buildFrame(pframe, dom.childNodes[frame.lastChild - 1]); - break; - } - } - } // while - } - - /** - * Cleans out state from a previous parse run - * @private - */ - }, { - key: "cleanParser", - value: function cleanParser() { - this.bnodes = {}; - this.why = null; - } - - /** - * Builds scope frame - * @private - */ - }, { - key: "buildFrame", - value: function buildFrame(parent, element) { - var frame = this.frameFactory(this, parent, element); - if (parent) { - frame.base = parent.base; - frame.lang = parent.lang; - } - if (!element || element.nodeType === RDFParser.nodeType.TEXT || element.nodeType === RDFParser.nodeType.CDATA_SECTION) { - return frame; - } - var attrs = element.attributes; - var base = element.getAttributeNode('xml:base'); - if (base != null) { - frame.base = base.nodeValue; - element.removeAttribute('xml:base'); - } - var lang = element.getAttributeNode('xml:lang'); - if (lang != null) { - frame.lang = lang.nodeValue; - element.removeAttribute('xml:lang'); - } - // remove all extraneous xml and xmlns attributes - for (var x = attrs.length - 1; x >= 0; x--) { - if (attrs[x].nodeName.substr(0, 3) === 'xml') { - if (attrs[x].name.slice(0, 6) === 'xmlns:') { - var uri = attrs[x].nodeValue; // alert('base for namespac attr:'+this.base) - if (this.base) uri = _uri__WEBPACK_IMPORTED_MODULE_3__.join(uri, this.base); - this.store.setPrefixForURI(attrs[x].name.slice(6), uri); - } - // alert('rdfparser: xml atribute: '+attrs[x].name) //@@ - element.removeAttributeNode(attrs[x]); - } - } - return frame; - } - }]); - return RDFParser; -}(); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(RDFParser, "ns", { - 'RDF': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', - 'RDFS': 'http://www.w3.org/2000/01/rdf-schema#' -}); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(RDFParser, "nodeType", { - 'ELEMENT': 1, - 'ATTRIBUTE': 2, - 'TEXT': 3, - 'CDATA_SECTION': 4, - 'ENTITY_REFERENCE': 5, - 'ENTITY': 6, - 'PROCESSING_INSTRUCTION': 7, - 'COMMENT': 8, - 'DOCUMENT': 9, - 'DOCUMENT_TYPE': 10, - 'DOCUMENT_FRAGMENT': 11, - 'NOTATION': 12 -}); - - -/***/ }), - -/***/ "../rdflib/esm/serialize.js": -/*!**********************************!*\ - !*** ../rdflib/esm/serialize.js ***! - \**********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ serialize) -/* harmony export */ }); -/* harmony import */ var _serializer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./serializer */ "../rdflib/esm/serializer.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); - - -/** - * Serialize to the appropriate format - */ -function serialize( /** The graph or nodes that should be serialized */ -target, /** The store */ -kb, base, -/** - * The mime type. - * Defaults to Turtle. - */ -contentType, callback, options) { - base = base || (target === null || target === void 0 ? void 0 : target.value); - var opts = options || {}; - contentType = contentType || _types__WEBPACK_IMPORTED_MODULE_0__.TurtleContentType; // text/n3 if complex? - var documentString = undefined; - try { - var sz = (0,_serializer__WEBPACK_IMPORTED_MODULE_1__["default"])(kb); - if (opts.flags) sz.setFlags(opts.flags); - var newSts = kb.statementsMatching(undefined, undefined, undefined, target); - - // If an IndexedFormula, use the namespaces from the given graph as suggestions - if ('namespaces' in kb) { - sz.suggestNamespaces(kb.namespaces); - } - - // use the provided options.namespaces are mandatory prefixes - if (opts.namespaces) { - sz.setNamespaces(opts.namespaces); - } - sz.setBase(base); - switch (contentType) { - case _types__WEBPACK_IMPORTED_MODULE_0__.RDFXMLContentType: - documentString = sz.statementsToXML(newSts); - return executeCallback(null, documentString); - case _types__WEBPACK_IMPORTED_MODULE_0__.N3ContentType: - case _types__WEBPACK_IMPORTED_MODULE_0__.N3LegacyContentType: - documentString = sz.statementsToN3(newSts); - return executeCallback(null, documentString); - case _types__WEBPACK_IMPORTED_MODULE_0__.TurtleContentType: - case _types__WEBPACK_IMPORTED_MODULE_0__.TurtleLegacyContentType: - sz.setFlags('si'); // Suppress = for sameAs and => for implies - documentString = sz.statementsToN3(newSts); - return executeCallback(null, documentString); - case _types__WEBPACK_IMPORTED_MODULE_0__.NTriplesContentType: - sz.setFlags('deinprstux'); // Suppress nice parts of N3 to make ntriples - documentString = sz.statementsToNTriples(newSts); - return executeCallback(null, documentString); - case _types__WEBPACK_IMPORTED_MODULE_0__.JSONLDContentType: - sz.setFlags('si dr'); // turtle + dr (means no default, no relative prefix) - documentString = sz.statementsToJsonld(newSts); // convert via turtle - return executeCallback(null, documentString); - case _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsContentType: - case _types__WEBPACK_IMPORTED_MODULE_0__.NQuadsAltContentType: - // @@@ just outpout the quads? Does not work for collections - sz.setFlags('deinprstux q'); // Suppress nice parts of N3 to make ntriples - documentString = sz.statementsToNTriples(newSts); // q in flag means actually quads - return executeCallback(null, documentString); - default: - throw new Error('Serialize: Content-type ' + contentType + ' not supported for data write.'); - } - } catch (err) { - if (callback) { - // @ts-ignore - return callback(err, undefined); - } - throw err; // Don't hide problems from caller in sync mode - } - - function executeCallback(err, result) { - if (callback) { - callback(err, result); - return; - } else { - return result; - } - } -} - -/***/ }), - -/***/ "../rdflib/esm/serializer.js": -/*!***********************************!*\ - !*** ../rdflib/esm/serializer.js ***! - \***********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "Serializer": () => (/* binding */ Serializer), -/* harmony export */ "default": () => (/* binding */ createSerializer) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/uri.js"); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); -/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "../rdflib/esm/factories/canonical-data-factory.js"); -/* harmony import */ var _xsd__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./xsd */ "../rdflib/esm/xsd.js"); -/* harmony import */ var solid_namespace__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! solid-namespace */ "../rdflib/node_modules/solid-namespace/index.js"); -/* harmony import */ var solid_namespace__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(solid_namespace__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _frogcat_ttl2jsonld__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @frogcat/ttl2jsonld */ "../rdflib/node_modules/@frogcat/ttl2jsonld/ttl2jsonld.js"); -/* harmony import */ var _frogcat_ttl2jsonld__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_frogcat_ttl2jsonld__WEBPACK_IMPORTED_MODULE_4__); - - - -/* Serialization of RDF Graphs -** -** Tim Berners-Lee 2006 -** This is was http://dig.csail.mit.edu/2005/ajar/ajaw/js/rdf/serialize.js -** This is or was https://github.com/linkeddata/rdflib.js/blob/main/src/serializer.js -** Licence: MIT -*/ - - - - - - - - -function createSerializer(store) { - return new Serializer(store); -} -; -var Serializer = /*#__PURE__*/function () { - function Serializer(store) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Serializer); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "_notQNameChars", '\t\r\n !"#$%&\'()*.,+/;<=>?@[\\]^`{|}~'); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "_notNameChars", this._notQNameChars + ':'); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "validPrefix", new RegExp(/^[a-zA-Z][a-zA-Z0-9]*$/)); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "forbidden1", new RegExp(/[\\"\b\f\r\v\t\n\u0080-\uffff]/gm)); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "forbidden3", new RegExp(/[\\"\b\f\r\v\u0080-\uffff]/gm)); - this.flags = ''; - this.base = null; - this.prefixes = []; // suggested prefixes - this.namespaces = []; // complementary - var nsKeys = Object.keys(solid_namespace__WEBPACK_IMPORTED_MODULE_3___default()()); - for (var i in nsKeys) { - var uri = solid_namespace__WEBPACK_IMPORTED_MODULE_3___default()()[nsKeys[i]](''); - var prefix = nsKeys[i]; - this.prefixes[uri] = prefix; - this.namespaces[prefix] = uri; - } - this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); // XML code assumes this! - this.suggestPrefix('xml', 'reserved:reservedForFutureUse'); // XML reserves xml: in the spec. - - this.namespacesUsed = []; // Count actually used and so needed in @prefixes - this.keywords = ['a']; // The only one we generate at the moment - this.prefixchars = 'abcdefghijklmnopqustuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - this.incoming = null; // Array not calculated yet - this.formulas = []; // remembering original formulae from hashes - this.store = store; - this.rdfFactory = store.rdfFactory || _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_5__["default"]; - this.xsd = (0,_xsd__WEBPACK_IMPORTED_MODULE_6__.createXSD)(this.rdfFactory); - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Serializer, [{ - key: "setBase", - value: function setBase(base) { - this.base = base; - return this; - } - }, { - key: "setFlags", - value: function setFlags(flags) { - this.flags = flags || ''; - return this; - } - }, { - key: "toStr", - value: function toStr(x) { - var s = x.toNT(); - if (x.termType === 'Graph') { - this.formulas[s] = x; // remember as reverse does not work - } - - return s; - } - }, { - key: "fromStr", - value: function fromStr(s) { - if (s[0] === '{') { - var x = this.formulas[s]; - if (!x) console.log('No formula object for ' + s); - return x; - } - return this.store.fromNT(s); - } - - /** - * Defines a set of [prefix, namespace] pairs to be used by this Serializer instance. - * Overrides previous prefixes if any - * @param namespaces - * @return {Serializer} - */ - }, { - key: "setNamespaces", - value: function setNamespaces(namespaces) { - for (var px in namespaces) { - this.setPrefix(px, namespaces[px]); - } - return this; - } - - /** - * Defines a namespace prefix, overriding any existing prefix for that URI - * @param prefix - * @param uri - */ - }, { - key: "setPrefix", - value: function setPrefix(prefix, uri) { - if (prefix.slice(0, 7) === 'default') return; // Try to weed these out - if (prefix.slice(0, 2) === 'ns') return; // From others inferior algos - if (!prefix || !uri) return; // empty strings not suitable - - // remove any existing prefix targeting this uri - // for (let existingPrefix in this.namespaces) { - // if (this.namespaces[existingPrefix] == uri) - // delete this.namespaces[existingPrefix]; - // } - - // remove any existing mapping for this prefix - for (var existingNs in this.prefixes) { - if (this.prefixes[existingNs] == prefix) delete this.prefixes[existingNs]; - } - this.prefixes[uri] = prefix; - this.namespaces[prefix] = uri; - } - - /* Accumulate Namespaces - ** - ** These are only hints. If two overlap, only one gets used - ** There is therefore no guarantee in general. - */ - }, { - key: "suggestPrefix", - value: function suggestPrefix(prefix, uri) { - if (prefix.slice(0, 7) === 'default') return; // Try to weed these out - if (prefix.slice(0, 2) === 'ns') return; // From others inferior algos - if (!prefix || !uri) return; // empty strings not suitable - if (prefix in this.namespaces || uri in this.prefixes) return; // already used - this.prefixes[uri] = prefix; - this.namespaces[prefix] = uri; - } - - // Takes a namespace -> prefix map - }, { - key: "suggestNamespaces", - value: function suggestNamespaces(namespaces) { - for (var px in namespaces) { - this.suggestPrefix(px, namespaces[px]); - } - return this; - } - }, { - key: "checkIntegrity", - value: function checkIntegrity() { - var p, ns; - for (p in this.namespaces) { - if (this.prefixes[this.namespaces[p]] !== p) { - throw new Error('Serializer integity error 1: ' + p + ', ' + this.namespaces[p] + ', ' + this.prefixes[this.namespaces[p]] + '!'); - } - } - for (ns in this.prefixes) { - if (this.namespaces[this.prefixes[ns]] !== ns) { - throw new Error('Serializer integity error 2: ' + ns + ', ' + this.prefixs[ns] + ', ' + this.namespaces[this.prefixes[ns]] + '!'); - } - } - } - - // Make up an unused prefix for a random namespace - }, { - key: "makeUpPrefix", - value: function makeUpPrefix(uri) { - var p = uri; - function canUseMethod(pp) { - if (!this.validPrefix.test(pp)) return false; // bad format - if (pp === 'ns') return false; // boring - if (pp in this.namespaces) return false; // already used - this.prefixes[uri] = pp; - this.namespaces[pp] = uri; - return pp; - } - var canUse = canUseMethod.bind(this); - if ('#/'.indexOf(p[p.length - 1]) >= 0) p = p.slice(0, -1); - var slash = p.lastIndexOf('/'); - if (slash >= 0) p = p.slice(slash + 1); - var i = 0; - while (i < p.length) { - if (this.prefixchars.indexOf(p[i])) { - i++; - } else { - break; - } - } - p = p.slice(0, i); - if (p.length < 6 && canUse(p)) return p; // exact is best - if (canUse(p.slice(0, 3))) return p.slice(0, 3); - if (canUse(p.slice(0, 2))) return p.slice(0, 2); - if (canUse(p.slice(0, 4))) return p.slice(0, 4); - if (canUse(p.slice(0, 1))) return p.slice(0, 1); - if (canUse(p.slice(0, 5))) return p.slice(0, 5); - if (!this.validPrefix.test(p)) { - p = 'n'; // Otherwise the loop below may never termimnate - } - - for (var j = 0;; j++) if (canUse(p.slice(0, 3) + j)) return p.slice(0, 3) + j; - } - }, { - key: "rootSubjects", - value: function rootSubjects(sts) { - var incoming = {}; - var subjects = {}; - var allBnodes = {}; - - /* This scan is to find out which nodes will have to be the roots of trees - ** in the serialized form. This will be any symbols, and any bnodes - ** which hve more or less than one incoming arc, and any bnodes which have - ** one incoming arc but it is an uninterrupted loop of such nodes back to itself. - ** This should be kept linear time with repect to the number of statements. - ** Note it does not use any indexing of the store. - */ - for (var i = 0; i < sts.length; i++) { - var st = sts[i]; - var checkMentions = function checkMentions(x) { - if (!incoming.hasOwnProperty(x)) incoming[x] = []; - incoming[x].push(st.subject); // List of things which will cause this to be printed - }; - - var st2 = [st.subject, st.predicate, st.object]; - st2.map(function (y) { - if (y.termType === 'BlankNode') { - allBnodes[y.toNT()] = true; - } else if (y.termType === 'Collection') { - y.elements.forEach(function (z) { - checkMentions(z); // bnodes in collections important - }); - } - }); - - checkMentions(sts[i].object); - var ss = subjects[this.toStr(st.subject)]; // Statements with this as subject - if (!ss) ss = []; - ss.push(st); - subjects[this.toStr(st.subject)] = ss; // Make hash. @@ too slow for formula? - } - - var roots = []; - for (var xNT in subjects) { - if (!subjects.hasOwnProperty(xNT)) continue; - var y = this.fromStr(xNT); - if (y.termType !== 'BlankNode' || !incoming[y] || incoming[y].length !== 1) { - roots.push(y); - continue; - } - } - this.incoming = incoming; // Keep for serializing @@ Bug for nested formulas - - // Now do the scan using existing roots - var rootsHash = {}; - for (var k = 0; k < roots.length; k++) { - rootsHash[roots[k].toNT()] = true; - } - return { - 'roots': roots, - 'subjects': subjects, - 'rootsHash': rootsHash, - 'incoming': incoming - }; - } - - // ////////////////////////////////////////////////////// - }, { - key: "toN3", - value: function toN3(f) { - return this.statementsToN3(f.statements); - } - }, { - key: "explicitURI", - value: function explicitURI(uri) { - if (this.flags.indexOf('r') < 0 && this.base) { - uri = _uri__WEBPACK_IMPORTED_MODULE_7__.refTo(this.base, uri); - } else if (this.flags.indexOf('u') >= 0) { - // Unicode encoding NTriples style - uri = backslashUify(uri); - } else { - uri = hexify(uri); - } - return '<' + uri + '>'; - } - }, { - key: "statementsToNTriples", - value: function statementsToNTriples(sts) { - var sorted = sts.slice(); - sorted.sort(); - var str = ''; - var rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; - var self = this; - var kb = this.store; - var factory = this.rdfFactory; - var termToNT = function termToNT(x) { - if (x.termType !== 'Collection') { - return self.atomicTermToN3(x); - } - var list = x.elements; - var rest = kb.sym(rdfns + 'nill'); - for (var i = list.length - 1; i >= 0; i--) { - var bnode = factory.blankNode(); - str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'first')) + ' ' + termToNT(list[i]) + '.\n'; - str += termToNT(bnode) + ' ' + termToNT(kb.sym(rdfns + 'rest')) + ' ' + termToNT(rest) + '.\n'; - rest = bnode; - } - return self.atomicTermToN3(rest); - }; - for (var i = 0; i < sorted.length; i++) { - var st = sorted[i]; - var s = ''; - s += termToNT(st.subject) + ' '; - s += termToNT(st.predicate) + ' '; - s += termToNT(st.object) + ' '; - if (this.flags.indexOf('q') >= 0) { - // Do quads not nrtiples - s += termToNT(st.why) + ' '; - } - s += '.\n'; - str += s; - } - return str; - } - }, { - key: "statementsToN3", - value: function statementsToN3(sts) { - var indent = 4; - var width = 80; - var kb = this.store; - // A URI Map alows us to put the type statemnts at the top. - var uriMap = { - 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': 'aaa:00' - }; - var SPO = function SPO(x, y) { - // Do limited canonicalization of bnodes - return _utils_js__WEBPACK_IMPORTED_MODULE_8__.heavyCompareSPO(x, y, kb, uriMap); - }; - sts.sort(SPO); - if (this.base && !this.defaultNamespace) { - this.defaultNamespace = this.base + '#'; - } - var predMap = {}; - if (this.flags.indexOf('s') < 0) { - predMap['http://www.w3.org/2002/07/owl#sameAs'] = '='; - } - if (this.flags.indexOf('t') < 0) { - predMap['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'] = 'a'; - } - if (this.flags.indexOf('i') < 0) { - predMap['http://www.w3.org/2000/10/swap/log#implies'] = '=>'; - } - // //////////////////////// Arrange the bits of text - - var spaces = function spaces(n) { - var s = ''; - for (var i = 0; i < n; i++) s += ' '; - return s; - }; - var treeToLine = function treeToLine(tree) { - var str = ''; - for (var i = 0; i < tree.length; i++) { - var branch = tree[i]; - var s2 = typeof branch === 'string' ? branch : treeToLine(branch); - // Note the space before the dot in case statement ends with 123 or colon. which is in fact allowed but be conservative. - if (i !== 0) { - var ch = str.slice(-1) || ' '; - if (s2 === ',' || s2 === ';') { - // no gap - } else if (s2 === '.' && !'0123456789.:'.includes(ch)) {// no gap except after number and colon - // no gap - } else { - str += ' '; // separate from previous token - } - } - - str += s2; - } - return str; - }; - - // Convert a nested tree of lists and strings to a string - var treeToString = function treeToString(tree, level) { - var str = ''; - var lastLength = 100000; - if (level === undefined) level = -1; - for (var i = 0; i < tree.length; i++) { - var branch = tree[i]; - if (typeof branch !== 'string') { - var substr = treeToString(branch, level + 1); - if (substr.length < 10 * (width - indent * level) && substr.indexOf('"""') < 0) { - // Don't mess up multiline strings - var line = treeToLine(branch); - if (line.length < width - indent * level) { - branch = line; // Note! treat as string below - substr = ''; - } - } - if (substr) lastLength = 10000; - str += substr; - } - if (typeof branch === 'string') { - if (branch.length === 1 && str.slice(-1) === '\n') { - if (',.;'.indexOf(branch) >= 0) { - str = str.slice(0, -1); - // be conservative and ensure a whitespace between some chars and a final dot, as in treeToLine above - if (branch == '.' && '0123456789.:'.includes(str.charAt(str.length - 1))) { - str += ' '; - lastLength += 1; - } - str += branch + '\n'; // slip punct'n on end - lastLength += 1; - continue; - } - } - if (lastLength < indent * level + 4 || - // if new line not necessary - lastLength + branch.length + 1 < width && ';.'.indexOf(str[str.length - 2]) < 0) { - // or the string fits on last line - str = str.slice(0, -1) + ' ' + branch + '\n'; // then continue on this line - lastLength += branch.length + 1; - } else { - var _line = spaces(indent * level) + branch; - str += _line + '\n'; - lastLength = _line.length; - if (level < 0) { - str += '\n'; // extra blank line - lastLength = 100000; // don't touch - } - } - } - } - - return str; - }; - - // //////////////////////////////////////////// Structure for N3 - // Convert a set of statements into a nested tree of lists and strings - function statementListToTreeMethod(statements) { - var stats = this.rootSubjects(statements); - var roots = stats.roots; - var results = []; - for (var i = 0; i < roots.length; i++) { - var root = roots[i]; - results.push(subjectTree(root, stats)); - } - return results; - } - var statementListToTree = statementListToTreeMethod.bind(this); - - // The tree for a subject - function subjectTree(subject, stats) { - if (subject.termType === 'BlankNode' && !stats.incoming[subject]) { - return objectTree(subject, stats, true).concat(['.']); // Anonymous bnode subject - } - - return [termToN3(subject, stats)].concat([propertyTree(subject, stats)]).concat(['.']); - } - // The property tree for a single subject or anonymous node - function propertyTreeMethod(subject, stats) { - var results = []; - var lastPred = null; - var sts = stats.subjects[this.toStr(subject)] || []; // relevant statements - if (typeof sts === 'undefined') { - throw new Error('Cant find statements for ' + subject); - } - var objects = []; - for (var i = 0; i < sts.length; i++) { - var st = sts[i]; - if (st.predicate.uri === lastPred) { - objects.push(','); - } else { - if (lastPred) { - results = results.concat([objects]).concat([';']); - objects = []; - } - results.push(predMap[st.predicate.uri] ? predMap[st.predicate.uri] : termToN3(st.predicate, stats)); - } - lastPred = st.predicate.uri; - objects.push(objectTree(st.object, stats)); - } - results = results.concat([objects]); - return results; - } - var propertyTree = propertyTreeMethod.bind(this); - function objectTreeMethod(obj, stats, force) { - if (obj.termType === 'BlankNode' && (force || stats.rootsHash[obj.toNT()] === undefined)) { - // if not a root - if (stats.subjects[this.toStr(obj)]) { - return ['[', propertyTree(obj, stats), ']']; - } else { - return '[]'; - } - } - return termToN3(obj, stats); - } - var objectTree = objectTreeMethod.bind(this); - function termToN3Method(expr, stats) { - // - var i, res; - switch (expr.termType) { - case 'Graph': - res = ['{']; - res = res.concat(statementListToTree(expr.statements)); - return res.concat(['}']); - case 'Collection': - res = ['(']; - for (i = 0; i < expr.elements.length; i++) { - res.push([objectTree(expr.elements[i], stats)]); - } - res.push(')'); - return res; - default: - return this.atomicTermToN3(expr); - } - } - Serializer.prototype.termToN3 = termToN3; - var termToN3 = termToN3Method.bind(this); - function prefixDirectivesMethod() { - var str = ''; - if (this.flags.indexOf('d') < 0 && this.defaultNamespace) { - str += '@prefix : ' + this.explicitURI(this.defaultNamespace) + '.\n'; - } - for (var ns in this.prefixes) { - if (!this.prefixes.hasOwnProperty(ns)) continue; - if (!this.namespacesUsed[ns]) continue; - str += '@prefix ' + this.prefixes[ns] + ': ' + this.explicitURI(ns) + '.\n'; - } - return str + '\n'; - } - var prefixDirectives = prefixDirectivesMethod.bind(this); - // Body of statementsToN3: - var tree = statementListToTree(sts); - return prefixDirectives() + treeToString(tree); - } - // //////////////////////////////////////////// Atomic Terms - - // Deal with term level things and nesting with no bnode structure - }, { - key: "atomicTermToN3", - value: function atomicTermToN3(expr, stats) { - switch (expr.termType) { - case 'BlankNode': - case 'Variable': - return expr.toNT(); - case 'Literal': - var val = expr.value; - if (typeof val !== 'string') { - throw new TypeError('Value of RDF literal node must be a string'); - } - // var val = expr.value.toString() // should be a string already - if (expr.datatype && this.flags.indexOf('x') < 0) { - // Supress native numbers - switch (expr.datatype.uri) { - case 'http://www.w3.org/2001/XMLSchema#integer': - return val; - case 'http://www.w3.org/2001/XMLSchema#decimal': - // In Turtle, must have dot - if (val.indexOf('.') < 0) val += '.0'; - return val; - case 'http://www.w3.org/2001/XMLSchema#double': - { - // Must force use of 'e' - var eNotation = val.toLowerCase().indexOf('e') > 0; - if (val.indexOf('.') < 0 && !eNotation) val += '.0'; - if (!eNotation) val += 'e0'; - return val; - } - case 'http://www.w3.org/2001/XMLSchema#boolean': - return expr.value === '1' ? 'true' : 'false'; - } - } - var str = this.stringToN3(expr.value); - if (expr.language) { - str += '@' + expr.language; - } else if (!expr.datatype.equals(this.xsd.string)) { - str += '^^' + this.atomicTermToN3(expr.datatype, stats); - } - return str; - case 'NamedNode': - return this.symbolToN3(expr); - case 'DefaultGraph': - return ''; - default: - throw new Error('Internal: atomicTermToN3 cannot handle ' + expr + ' of termType: ' + expr.termType); - } - } - - // stringToN3: String escaping for N3 - }, { - key: "stringToN3", - value: function stringToN3(str, flags) { - if (!flags) flags = 'e'; - var res = ''; - var i, j, k; - var delim; - var forbidden; - if (str.length > 20 && - // Long enough to make sense - str.slice(-1) !== '"' && - // corner case' - flags.indexOf('n') < 0 && ( - // Force single line - str.indexOf('\n') > 0 || str.indexOf('"') > 0)) { - delim = '"""'; - forbidden = this.forbidden3; - } else { - delim = '"'; - forbidden = this.forbidden1; - } - for (i = 0; i < str.length;) { - forbidden.lastIndex = 0; - var m = forbidden.exec(str.slice(i)); - if (m == null) break; - j = i + forbidden.lastIndex - 1; - res += str.slice(i, j); - var ch = str[j]; - if (ch === '"' && delim === '"""' && str.slice(j, j + 3) !== '"""') { - res += ch; - } else { - k = '\b\f\r\t\v\n\\"'.indexOf(ch); // No escaping of bell (7)? - if (k >= 0) { - res += '\\' + 'bfrtvn\\"'[k]; - } else { - if (flags.indexOf('e') >= 0) { - // Unicode escaping in strings not unix style - res += "\\u" + ('000' + ch.charCodeAt(0).toString(16).toLowerCase()).slice(-4); - } else { - // no 'e' flag - res += ch; - } - } - } - i = j + 1; - } - return delim + res + str.slice(i) + delim; - } - // A single symbol, either in <> or namespace notation - }, { - key: "symbolToN3", - value: function symbolToN3(x) { - // c.f. symbolString() in notation3.py - var uri = x.uri; - var j = uri.indexOf('#'); - if (j < 0 && this.flags.indexOf('/') < 0) { - j = uri.lastIndexOf('/'); - } - if (j >= 0 && this.flags.indexOf('p') < 0 && ( - // Can split at namespace but only if http[s]: URI or file: or ws[s] (why not others?) - uri.indexOf('http') === 0 || uri.indexOf('ws') === 0 || uri.indexOf('file') === 0)) { - var canSplit = true; - for (var k = j + 1; k < uri.length; k++) { - if (this._notNameChars.indexOf(uri[k]) >= 0) { - canSplit = false; - break; - } - } - /* - if (uri.slice(0, j + 1) === this.base + '#') { // base-relative - if (canSplit) { - return ':' + uri.slice(j + 1) // assume deafult ns is local - } else { - return '<#' + uri.slice(j + 1) + '>' - } - } - */ - if (canSplit) { - var localid = uri.slice(j + 1); - var namesp = uri.slice(0, j + 1); - if (this.defaultNamespace && this.defaultNamespace === namesp && this.flags.indexOf('d') < 0) { - // d -> suppress default - if (this.flags.indexOf('k') >= 0 && this.keyords.indexOf(localid) < 0) { - return localid; - } - return ':' + localid; - } - // this.checkIntegrity() // @@@ Remove when not testing - var prefix = this.prefixes[namesp]; - if (!prefix) prefix = this.makeUpPrefix(namesp); - if (prefix) { - this.namespacesUsed[namesp] = true; - return prefix + ':' + localid; - } - // Fall though if can't do qname - } - } - - return this.explicitURI(uri); - } - - // /////////////////////////// Quad store serialization - - // @para. write - a function taking a single string to be output - // - }, { - key: "writeStore", - value: function writeStore(write) { - var kb = this.store; - var fetcher = kb.fetcher; - var session = fetcher && fetcher.appNode; - - // The core data - - var sources = this.store.index[3]; - for (var s in sources) { - // -> assume we can use -> as short for log:semantics - var source = kb.fromNT(s); - if (session && source.equals(session)) continue; - write('\n' + this.atomicTermToN3(source) + ' ' + this.atomicTermToN3(kb.sym('http://www.w3.org/2000/10/swap/log#semantics')) + ' { ' + this.statementsToN3(kb.statementsMatching(undefined, undefined, undefined, source)) + ' }.\n'); - } - - // The metadata from HTTP interactions: - - kb.statementsMatching(undefined, kb.sym('http://www.w3.org/2007/ont/link#requestedURI')).map(function (st) { - write('\n<' + st.object.value + '> log:metadata {\n'); - var sts = kb.statementsMatching(undefined, undefined, undefined, st.subject); - write(this.statementsToN3(this.statementsToN3(sts))); - write('}.\n'); - }); - - // Inferences we have made ourselves not attributable to anyone else - - var metaSources = []; - if (session) metaSources.push(session); - var metadata = []; - metaSources.map(function (source) { - metadata = metadata.concat(kb.statementsMatching(undefined, undefined, undefined, source)); - }); - write(this.statementsToN3(metadata)); - } - - // ////////////////////////////////////////////// XML serialization - }, { - key: "statementsToXML", - value: function statementsToXML(sts) { - var indent = 4; - var width = 80; - var namespaceCounts = []; // which have been used - namespaceCounts['http://www.w3.org/1999/02/22-rdf-syntax-ns#'] = true; - var liPrefix = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#_'; // prefix for ordered list items - - // //////////////////////// Arrange the bits of XML text - - var spaces = function spaces(n) { - var s = ''; - for (var i = 0; i < n; i++) s += ' '; - return s; - }; - var XMLtreeToLine = function XMLtreeToLine(tree) { - var str = ''; - for (var i = 0; i < tree.length; i++) { - var branch = tree[i]; - var s2 = typeof branch === 'string' ? branch : XMLtreeToLine(branch); - str += s2; - } - return str; - }; - - // Convert a nested tree of lists and strings to a string - var XMLtreeToString = function XMLtreeToString(tree, level) { - var str = ''; - var line; - var lastLength = 100000; - if (!level) level = 0; - for (var i = 0; i < tree.length; i++) { - var branch = tree[i]; - if (typeof branch !== 'string') { - var substr = XMLtreeToString(branch, level + 1); - if (substr.length < 10 * (width - indent * level) && substr.indexOf('"""') < 0) { - // Don't mess up multiline strings - line = XMLtreeToLine(branch); - if (line.length < width - indent * level) { - branch = ' ' + line; // @@ Hack: treat as string below - substr = ''; - } - } - if (substr) lastLength = 10000; - str += substr; - } - if (typeof branch === 'string') { - if (lastLength < indent * level + 4) { - // continue - str = str.slice(0, -1) + ' ' + branch + '\n'; - lastLength += branch.length + 1; - } else { - line = spaces(indent * level) + branch; - str += line + '\n'; - lastLength = line.length; - } - } else {// not string - } - } - return str; - }; - function statementListToXMLTreeMethod(statements) { - this.suggestPrefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'); - var stats = this.rootSubjects(statements); - var roots = stats.roots; - var results = []; - for (var i = 0; i < roots.length; i++) { - var root = roots[i]; - results.push(subjectXMLTree(root, stats)); - } - return results; - } - var statementListToXMLTree = statementListToXMLTreeMethod.bind(this); - function escapeForXML(str) { - if (typeof str === 'undefined') return '@@@undefined@@@@'; - return str.replace(/[&<"]/g, function (m) { - switch (m[0]) { - case '&': - return '&'; - case '<': - return '<'; - case '"': - return '"'; - // ' - } - }); - } - - function relURIMethod(term) { - return escapeForXML(this.base ? _uri__WEBPACK_IMPORTED_MODULE_7__.refTo(this.base, term.uri) : term.uri); - } - var relURI = relURIMethod.bind(this); - - // The tree for a subject - function subjectXMLTreeMethod(subject, stats) { - var results = []; - var type, t, st, pred; - var sts = stats.subjects[this.toStr(subject)]; // relevant statements - if (typeof sts === 'undefined') { - // empty bnode - return propertyXMLTree(subject, stats); - } - - // Sort only on the predicate, leave the order at object - // level undisturbed. This leaves multilingual content in - // the order of entry (for partner literals), which helps - // readability. - // - // For the predicate sort, we attempt to split the uri - // as a hint to the sequence - sts.sort(function (a, b) { - var ap = a.predicate.uri; - var bp = b.predicate.uri; - if (ap.substring(0, liPrefix.length) === liPrefix || bp.substring(0, liPrefix.length) === liPrefix) { - // we're only interested in sorting list items - return ap.localeCompare(bp); - } - var as = ap.substring(liPrefix.length); - var bs = bp.substring(liPrefix.length); - var an = parseInt(as, 10); - var bn = parseInt(bs, 10); - if (isNaN(an) || isNaN(bn) || an !== as || bn !== bs) { - // we only care about integers - return ap.localeCompare(bp); - } - return an - bn; - }); - for (var i = 0; i < sts.length; i++) { - st = sts[i]; - // look for a type - if (st.predicate.uri === 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type' && !type && st.object.termType === 'NamedNode') { - type = st.object; - continue; // don't include it as a child element - } - - // see whether predicate can be replaced with "li" - pred = st.predicate; - if (pred.uri.substr(0, liPrefix.length) === liPrefix) { - var number = pred.uri.substr(liPrefix.length); - // make sure these are actually numeric list items - var intNumber = parseInt(number, 10); - if (number === intNumber.toString()) { - // was numeric; don't need to worry about ordering since we've already - // sorted the statements - pred = this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#li'); - } - } - t = qname(pred); - switch (st.object.termType) { - case 'BlankNode': - if (stats.incoming[st.object].length === 1) { - // there should always be something in the incoming array for a bnode - results = results.concat(['<' + t + ' rdf:parseType="Resource">', subjectXMLTree(st.object, stats), '']); - } else { - results = results.concat(['<' + t + ' rdf:nodeID="' + st.object.toNT().slice(2) + '"/>']); - } - break; - case 'NamedNode': - results = results.concat(['<' + t + ' rdf:resource="' + relURI(st.object) + '"/>']); - break; - case 'Literal': - results = results.concat(['<' + t + (st.object.datatype.equals(this.xsd.string) ? '' : ' rdf:datatype="' + escapeForXML(st.object.datatype.uri) + '"') + (st.object.language ? ' xml:lang="' + st.object.language + '"' : '') + '>' + escapeForXML(st.object.value) + '']); - break; - case 'Collection': - results = results.concat(['<' + t + ' rdf:parseType="Collection">', collectionXMLTree(st.object, stats), '']); - break; - default: - throw new Error("Can't serialize object of type " + st.object.termType + ' into XML'); - } // switch - } - - var tag = type ? qname(type) : 'rdf:Description'; - var attrs = ''; - if (subject.termType === 'BlankNode') { - if (!stats.incoming[subject] || stats.incoming[subject].length !== 1) { - // not an anonymous bnode - attrs = ' rdf:nodeID="' + subject.toNT().slice(2) + '"'; - } - } else { - attrs = ' rdf:about="' + relURI(subject) + '"'; - } - return ['<' + tag + attrs + '>'].concat([results]).concat(['']); - } - var subjectXMLTree = subjectXMLTreeMethod.bind(this); - function collectionXMLTree(subject, stats) { - var res = []; - for (var i = 0; i < subject.elements.length; i++) { - res.push(subjectXMLTree(subject.elements[i], stats)); - } - return res; - } - - // The property tree for a single subject or anonymos node - function propertyXMLTreeMethod(subject, stats) { - var results = []; - var sts = stats.subjects[this.toStr(subject)]; // relevant statements - if (!sts) return results; // No relevant statements - sts.sort(); - for (var i = 0; i < sts.length; i++) { - var st = sts[i]; - switch (st.object.termType) { - case 'BlankNode': - if (stats.rootsHash[st.object.toNT()]) { - // This bnode has been done as a root -- no content here @@ what bout first time - results = results.concat(['<' + qname(st.predicate) + ' rdf:nodeID="' + st.object.toNT().slice(2) + '">', '']); - } else { - results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType="Resource">', propertyXMLTree(st.object, stats), '']); - } - break; - case 'NamedNode': - results = results.concat(['<' + qname(st.predicate) + ' rdf:resource="' + relURI(st.object) + '"/>']); - break; - case 'Literal': - results = results.concat(['<' + qname(st.predicate) + (st.object.datatype.equals(this.xsd.string) ? '' : ' rdf:datatype="' + escapeForXML(st.object.datatype.value) + '"') + (st.object.language ? ' xml:lang="' + st.object.language + '"' : '') + '>' + escapeForXML(st.object.value) + '']); - break; - case 'Collection': - results = results.concat(['<' + qname(st.predicate) + ' rdf:parseType="Collection">', collectionXMLTree(st.object, stats), '']); - break; - default: - throw new Error("Can't serialize object of type " + st.object.termType + ' into XML'); - } // switch - } - - return results; - } - var propertyXMLTree = propertyXMLTreeMethod.bind(this); - function qnameMethod(term) { - var uri = term.uri; - var j = uri.indexOf('#'); - if (j < 0 && this.flags.indexOf('/') < 0) { - j = uri.lastIndexOf('/'); - } - if (j < 0) throw new Error('Cannot make qname out of <' + uri + '>'); - for (var k = j + 1; k < uri.length; k++) { - if (this._notNameChars.indexOf(uri[k]) >= 0) { - throw new Error('Invalid character "' + uri[k] + '" cannot be in XML qname for URI: ' + uri); - } - } - var localid = uri.slice(j + 1); - var namesp = uri.slice(0, j + 1); - if (this.defaultNamespace && this.defaultNamespace === namesp && this.flags.indexOf('d') < 0) { - // d -> suppress default - return localid; - } - var prefix = this.prefixes[namesp]; - if (!prefix) prefix = this.makeUpPrefix(namesp); - namespaceCounts[namesp] = true; - return prefix + ':' + localid; - } - var qname = qnameMethod.bind(this); - - // Body of toXML: - - var tree = statementListToXMLTree(sts); - var str = '']; // @@ namespace declrations - return XMLtreeToString(tree2, -1); - } // End @@ body - }, { - key: "statementsToJsonld", - value: function statementsToJsonld(sts) { - // ttl2jsonld creates context keys for all ttl prefix - // context keys must be absolute IRI ttl2jsonld@0.0.8 - /* function findId (itemObj) { - if (itemObj['@id']) { - const item = itemObj['@id'].split(':') - if (keys[item[0]]) itemObj['@id'] = jsonldObj['@context'][item[0]] + item[1] - } - const itemValues = Object.values(itemObj) - for (const i in itemValues) { - if (typeof itemValues[i] !== 'string') { // @list contains array - findId(itemValues[i]) - } - } - } */ - var turtleDoc = this.statementsToN3(sts); - var jsonldObj = _frogcat_ttl2jsonld__WEBPACK_IMPORTED_MODULE_4__.parse(turtleDoc); - return JSON.stringify(jsonldObj, null, 2); - } - }]); - return Serializer; -}(); - -// String escaping utilities - -function hexify(str) { - // also used in parser - return encodeURI(str); -} -function backslashUify(str) { - var res = ''; - var k; - for (var i = 0; i < str.length; i++) { - k = str.charCodeAt(i); - if (k > 65535) { - res += "\\U" + ('00000000' + k.toString(16)).slice(-8); // convert to upper? - } else if (k > 126) { - res += "\\u" + ('0000' + k.toString(16)).slice(-4); - } else { - res += str[i]; - } - } - return res; -} - -/***/ }), - -/***/ "../rdflib/esm/sparql-to-query.js": -/*!****************************************!*\ - !*** ../rdflib/esm/sparql-to-query.js ***! - \****************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ SPARQLToQuery) -/* harmony export */ }); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); -/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./query */ "../rdflib/esm/query.js"); -// Converting between SPARQL queries and the $rdf query API -/* - -function SQuery () { - this.terms = [] - return this -} - -STerm.prototype.toString = STerm.val -SQuery.prototype.add = function (str) {this.terms.push()}*/ - - - - -/** - * @SPARQL: SPARQL text that is converted to a query object which is returned. - * @testMode: testing flag. Prevents loading of sources. - */ -function SPARQLToQuery(SPARQL, testMode, kb) { - // AJAR_ClearTable() - var variableHash = []; - function makeVar(name) { - if (variableHash[name]) { - return variableHash[name]; - } - var newVar = kb.variable(name); - variableHash[name] = newVar; - return newVar; - } - - // term type functions - function isRealText(term) { - return typeof term === 'string' && term.match(/[^ \n\t]/); - } - function isVar(term) { - return typeof term === 'string' && term.match(/^[\?\$]/); - } - function fixSymbolBrackets(term) { - if (typeof term === 'string') { - return term.replace(/^</, '<').replace(/>$/, '>'); - } else { - return term; - } - } - function isSymbol(term) { - return typeof term === 'string' && term.match(/^<[^>]*>$/); - } - function isBnode(term) { - return typeof term === 'string' && (term.match(/^_:/) || term.match(/^$/)); - } - function isPrefix(term) { - return typeof term === 'string' && term.match(/:$/); - } - function isPrefixedSymbol(term) { - return typeof term === 'string' && term.match(/^:|^[^_][^:]*:/); - } - function getPrefix(term) { - var a = term.split(':'); - return a[0]; - } - function getSuffix(term) { - var a = term.split(':'); - return a[1]; - } - function removeBrackets(term) { - if (isSymbol(term)) { - return term.slice(1, term.length - 1); - } else { - return term; - } - } - // takes a string and returns an array of strings and Literals in the place of literals - function parseLiterals(str) { - // var sin = (str.indexOf(/[ \n]\'/)==-1)?null:str.indexOf(/[ \n]\'/), doub = (str.indexOf(/[ \n]\"/)==-1)?null:str.indexOf(/[ \n]\"/) - var sin = str.indexOf("'") === -1 ? null : str.indexOf("'"); - var doub = str.indexOf('"') === -1 ? null : str.indexOf('"'); - // alert("S: "+sin+" D: "+doub) - if (!sin && !doub) { - var a = new Array(1); - a[0] = str; - return a; - } - var res = new Array(2); - var br; - var ind; - if (!sin || doub && doub < sin) { - br = '"'; - ind = doub; - } else if (!doub || sin && sin < doub) { - br = "'"; - ind = sin; - } else { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('SQARQL QUERY OOPS!'); - return res; - } - res[0] = str.slice(0, ind); - var end = str.slice(ind + 1).indexOf(br); - if (end === -1) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('SPARQL parsing error: no matching parentheses in literal ' + str); - return str; - } - // alert(str.slice(end + ind + 2).match(/^\^\^/)) - var end2; - if (str.slice(end + ind + 2).match(/^\^\^/)) { - end2 = str.slice(end + ind + 2).indexOf(' '); - // alert(end2) - res[1] = kb.literal(str.slice(ind + 1, ind + 1 + end), kb.sym(removeBrackets(str.slice(ind + 4 + end, ind + 2 + end + end2)))); - // alert(res[1].datatype.uri) - res = res.concat(parseLiterals(str.slice(end + ind + 3 + end2))); - } else if (str.slice(end + ind + 2).match(/^@/)) { - end2 = str.slice(end + ind + 2).indexOf(' '); - // alert(end2) - res[1] = kb.literal(str.slice(ind + 1, ind + 1 + end), str.slice(ind + 3 + end, ind + 2 + end + end2), null); - // alert(res[1].datatype.uri) - res = res.concat(parseLiterals(str.slice(end + ind + 2 + end2))); - } else { - res[1] = kb.literal(str.slice(ind + 1, ind + 1 + end)); - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Literal found: ' + res[1]); - res = res.concat(parseLiterals(str.slice(end + ind + 2))); // finds any other literals - } - - return res; - } - function spaceDelimit(str) { - str = str.replace(/\(/g, ' ( ').replace(/\)/g, ' ) ').replace(//g, '> ').replace(/{/g, ' { ').replace(/}/g, ' } ').replace(/[\t\n\r]/g, ' ').replace(/; /g, ' ; ').replace(/\. /g, ' . ').replace(/, /g, ' , '); - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('New str into spaceDelimit: \n' + str); - var res = []; - var br = str.split(' '); - for (var x in br) { - if (isRealText(br[x])) { - res = res.concat(br[x]); - } - } - return res; - } - function replaceKeywords(input) { - var strarr = input; - for (var x = 0; x < strarr.length; x++) { - if (strarr[x] === 'a') { - strarr[x] = ''; - } - if (strarr[x] === 'is' && strarr[x + 2] === 'of') { - strarr.splice(x, 1); - strarr.splice(x + 1, 1); - var s = strarr[x - 1]; - strarr[x - 1] = strarr[x + 1]; - strarr[x + 1] = s; - } - } - return strarr; - } - function toTerms(input) { - var res = []; - for (var x = 0; x < input.length; x++) { - if (typeof input[x] !== 'string') { - res[x] = input[x]; - continue; - } - input[x] = fixSymbolBrackets(input[x]); - if (isVar(input[x])) { - res[x] = makeVar(input[x].slice(1)); - } else if (isBnode(input[x])) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info(input[x] + ' was identified as a bnode.'); - res[x] = kb.bnode(); - } else if (isSymbol(input[x])) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info(input[x] + ' was identified as a symbol.'); - res[x] = kb.sym(removeBrackets(input[x])); - } else if (isPrefixedSymbol(input[x])) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info(input[x] + ' was identified as a prefixed symbol'); - if (prefixes[getPrefix(input[x])]) { - res[x] = kb.sym(input[x] = prefixes[getPrefix(input[x])] + getSuffix(input[x])); - } else { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('SPARQL error: ' + input[x] + ' with prefix ' + getPrefix(input[x]) + ' does not have a correct prefix entry.'); - res[x] = input[x]; - } - } else { - res[x] = input[x]; - } - } - return res; - } - function tokenize(str) { - var token1 = parseLiterals(str); - var token2 = []; - for (var x in token1) { - if (typeof token1[x] === 'string') { - token2 = token2.concat(spaceDelimit(token1[x])); - } else { - token2 = token2.concat(token1[x]); - } - } - token2 = replaceKeywords(token2); - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('SPARQL Tokens: ' + token2); - return token2; - } - - // CASE-INSENSITIVE - function arrayIndexOf(str, arr) { - for (var i = 0; i < arr.length; i++) { - if (typeof arr[i] !== 'string') { - continue; - } - if (arr[i].toLowerCase() === str.toLowerCase()) { - return i; - } - } - // log.warn("No instance of "+str+" in array "+arr) - return null; - } - - // CASE-INSENSITIVE - function arrayIndicesOf(str, arr) { - var ind = []; - for (var i = 0; i < arr.length; i++) { - if (typeof arr[i] !== 'string') { - continue; - } - if (arr[i].toLowerCase() === str.toLowerCase()) { - ind.push(i); - } - } - return ind; - } - function setVars(input, query) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('SPARQL vars: ' + input); - for (var x in input) { - if (isVar(input[x])) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Added ' + input[x] + ' to query variables from SPARQL'); - var v = makeVar(input[x].slice(1)); - query.vars.push(v); - v.label = input[x].slice(1); - } else { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].warn('Incorrect SPARQL variable in SELECT: ' + input[x]); - } - } - } - function getPrefixDeclarations(input) { - var prefInd = arrayIndicesOf('PREFIX', input); - var res = []; - for (var i in prefInd) { - var a = input[prefInd[i] + 1]; - var b = input[prefInd[i] + 2]; - if (!isPrefix(a)) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Invalid SPARQL prefix: ' + a); - } else if (!isSymbol(b)) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Invalid SPARQL symbol: ' + b); - } else { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Prefix found: ' + a + ' -> ' + b); - var pref = getPrefix(a); - var symbol = removeBrackets(b); - res[pref] = symbol; - } - } - return res; - } - function getMatchingBracket(arr, open, close) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Looking for a close bracket of type ' + close + ' in ' + arr); - var index = 0; - for (var i = 0; i < arr.length; i++) { - if (arr[i] === open) { - index++; - } - if (arr[i] === close) { - index--; - } - if (index < 0) { - return i; - } - } - _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Statement had no close parenthesis in SPARQL query'); - return 0; - } - function constraintGreaterThan(value) { - this.describe = function (varstr) { - return varstr + ' > ' + value.toNT(); - }; - this.test = function (term) { - if (term.value.match(/[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?/)) { - return parseFloat(term.value) > parseFloat(value); - } else { - return term.toNT() > value.toNT(); - } - }; - return this; - } - function constraintLessThan(value) { - // this is not the recommended usage. Should only work on literal, numeric, dateTime - this.describe = function (varstr) { - return varstr + ' < ' + value.toNT(); - }; - this.test = function (term) { - // this.describe = function (varstr) { return varstr + " < "+value } - if (term.value.match(/[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?/)) { - return parseFloat(term.value) < parseFloat(value); - } else { - return term.toNT() < value.toNT(); - } - }; - return this; - } - // This should only work on literals but doesn't. - function ConstraintEqualTo(value) { - this.describe = function (varstr) { - return varstr + ' = ' + value.toNT(); - }; - this.test = function (term) { - return value.equals(term); - }; - return this; - } - - // value must be a literal - function ConstraintRegexp(value) { - this.describe = function (varstr) { - return "REGEXP( '" + value + "' , " + varstr + ' )'; - }; - this.test = function (term) { - var str = value; - // str = str.replace(/^//,"").replace(//$/,"") - var rg = new RegExp(str); - if (term.value) { - return rg.test(term.value); - } else { - return false; - } - }; - } - function setConstraint(input, pat) { - if (input.length === 3 && input[0].termType === 'Variable' && (input[2].termType === 'NamedNode' || input[2].termType === 'Literal')) { - if (input[1] === '=') { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Constraint added: ' + input); - pat.constraints[input[0]] = new ConstraintEqualTo(input[2]); - } else if (input[1] === '>') { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Constraint added: ' + input); - pat.constraints[input[0]] = new ConstraintEqualTo(input[2]); - } else if (input[1] === '<') { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Constraint added: ' + input); - pat.constraints[input[0]] = new ConstraintEqualTo(input[2]); - } else { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].warn("I don't know how to handle the constraint: " + input); - } - } else if (input.length === 6 && typeof input[0] === 'string' && input[0].toLowerCase() === 'regexp' && input[1] === '(' && input[5] === ')' && input[3] === ',' && input[4].termType === 'Variable' && input[2].termType === 'Literal') { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Constraint added: ' + input); - pat.constraints[input[4]] = new ConstraintRegexp(input[2].value); - } - // log.warn("I don't know how to handle the constraint: "+input) - // alert("length: "+input.length+" input 0 type: "+input[0].termType+" input 1: "+input[1]+" input[2] type: "+input[2].termType) - } - - function setOptional(terms, pat) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('Optional query: ' + terms + ' not yet implemented.'); - var opt = kb.formula(); - setWhere(terms, opt); - pat.optional.push(opt); - } - function setWhere(input, pat) { - var terms = toTerms(input); - var end; - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('WHERE: ' + terms); - var opt; - // var opt = arrayIndicesOf("OPTIONAL",terms) - while (arrayIndexOf('OPTIONAL', terms)) { - opt = arrayIndexOf('OPTIONAL', terms); - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('OPT: ' + opt + ' ' + terms[opt] + ' in ' + terms); - if (terms[opt + 1] !== '{') { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].warn('Bad optional opening bracket in word ' + opt); - } - end = getMatchingBracket(terms.slice(opt + 2), '{', '}'); - if (end === -1) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('No matching bracket in word ' + opt); - } else { - setOptional(terms.slice(opt + 2, opt + 2 + end), pat); - // alert(pat.statements[0].toNT()) - opt = arrayIndexOf('OPTIONAL', terms); - end = getMatchingBracket(terms.slice(opt + 2), '{', '}'); - terms.splice(opt, end + 3); - } - } - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('WHERE after optionals: ' + terms); - while (arrayIndexOf('FILTER', terms)) { - var filt = arrayIndexOf('FILTER', terms); - if (terms[filt + 1] !== '(') { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].warn('Bad filter opening bracket in word ' + filt); - } - end = getMatchingBracket(terms.slice(filt + 2), '(', ')'); - if (end === -1) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('No matching bracket in word ' + filt); - } else { - setConstraint(terms.slice(filt + 2, filt + 2 + end), pat); - filt = arrayIndexOf('FILTER', terms); - end = getMatchingBracket(terms.slice(filt + 2), '(', ')'); - terms.splice(filt, end + 3); - } - } - _log__WEBPACK_IMPORTED_MODULE_0__["default"].debug('WHERE after filters and optionals: ' + terms); - extractStatements(terms, pat); - } - function extractStatements(terms, formula) { - var arrayZero = new Array(1); - arrayZero[0] = -1; // this is just to add the beginning of the where to the periods index. - var per = arrayZero.concat(arrayIndicesOf('.', terms)); - var stat = []; - for (var x = 0; x < per.length - 1; x++) { - stat[x] = terms.slice(per[x] + 1, per[x + 1]); - } - // Now it's in an array of statements - for (x in stat) { - // THIS MUST BE CHANGED FOR COMMA, SEMICOLON - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('s+p+o ' + x + ' = ' + stat[x]); - var subj = stat[x][0]; - stat[x].splice(0, 1); - var sem = arrayZero.concat(arrayIndicesOf(';', stat[x])); - sem.push(stat[x].length); - var stat2 = []; - for (var y = 0; y < sem.length - 1; y++) { - stat2[y] = stat[x].slice(sem[y] + 1, sem[y + 1]); - } - for (x in stat2) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('p+o ' + x + ' = ' + stat[x]); - var pred = stat2[x][0]; - stat2[x].splice(0, 1); - var com = arrayZero.concat(arrayIndicesOf(',', stat2[x])); - com.push(stat2[x].length); - var stat3 = []; - for (y = 0; y < com.length - 1; y++) { - stat3[y] = stat2[x].slice(com[y] + 1, com[y + 1]); - } - for (x in stat3) { - var obj = stat3[x][0]; - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('Subj=' + subj + ' Pred=' + pred + ' Obj=' + obj); - formula.add(subj, pred, obj); - } - } - } - } - - // ******************************* Body of SPARQLToQuery ***************************// - _log__WEBPACK_IMPORTED_MODULE_0__["default"].info('SPARQL input: \n' + SPARQL); - var q = new _query__WEBPACK_IMPORTED_MODULE_1__.Query(); - var sp = tokenize(SPARQL); // first tokenize everything - var prefixes = getPrefixDeclarations(sp); - if (!prefixes.rdf) { - prefixes.rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; - } - if (!prefixes.rdfs) { - prefixes.rdfs = 'http://www.w3.org/2000/01/rdf-schema#'; - } - var selectLoc = arrayIndexOf('SELECT', sp); - var whereLoc = arrayIndexOf('WHERE', sp); - if (selectLoc < 0 || whereLoc < 0 || selectLoc > whereLoc) { - _log__WEBPACK_IMPORTED_MODULE_0__["default"].error('Invalid or nonexistent SELECT and WHERE tags in SPARQL query'); - return false; - } - setVars(sp.slice(selectLoc + 1, whereLoc), q); - setWhere(sp.slice(whereLoc + 2, sp.length - 1), q.pat); - if (testMode) { - return q; - } - for (var x in q.pat.statements) { - var st = q.pat.statements[x]; - if (st.subject.termType === 'NamedNode') { - if (kb.fetcher) { - kb.fetcher.lookUpThing(st.subject, 'sparql:' + st.subject); - } - } - if (st.object.termType === 'NamedNode') { - if (kb.fetcher) { - kb.fetcher.lookUpThing(st.object, 'sparql:' + st.object); - } - } - } - // alert(q.pat) - return q; - // checkVars() - // *******************************************************************// -} - -/***/ }), - -/***/ "../rdflib/esm/statement.js": -/*!**********************************!*\ - !*** ../rdflib/esm/statement.js ***! - \**********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Statement) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -/* harmony import */ var _default_graph__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./default-graph */ "../rdflib/esm/default-graph.js"); - - - - - - -var defaultGraph = new _default_graph__WEBPACK_IMPORTED_MODULE_3__["default"](); - -/** A Statement represents an RDF Triple or Quad. */ -var Statement = /*#__PURE__*/function () { - /** The subject of the triple. What the Statement is about. */ - - /** The relationship which is asserted between the subject and object */ - - /** The thing or data value which is asserted to be related to the subject */ - - /** - * The graph param is a named node of the document in which the triple when - * it is stored on the web. - */ - - /** - * Construct a new statement - * - * @param subject - The subject of the triple. What the fact is about - * @param predicate - The relationship which is asserted between the subject and object - * @param object - The thing or data value which is asserted to be related to the subject - * @param {NamedNode} graph - The document where the triple is or was or will be stored on the web. - * - * The graph param is a named node of the document in which the triple when it is stored - * on the web. It exists because when you have read data from various places in the web, - * the “graph” tells you _why_ you have the triple. (At the moment, it is just the - * document, in future it could be an inference step) - * - * When you do UpdateManager.update() then the graph’s of all the statements must be the same, - * and give the document you are patching. In future, we may have a more - * powerful update() which can update more than one document. - */ - function Statement(subject, predicate, object, graph) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Statement); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "subject", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "predicate", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "object", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__["default"])(this, "graph", void 0); - this.subject = _node_internal__WEBPACK_IMPORTED_MODULE_4__["default"].fromValue(subject); - this.predicate = _node_internal__WEBPACK_IMPORTED_MODULE_4__["default"].fromValue(predicate); - this.object = _node_internal__WEBPACK_IMPORTED_MODULE_4__["default"].fromValue(object); - this.graph = graph == undefined ? defaultGraph : _node_internal__WEBPACK_IMPORTED_MODULE_4__["default"].fromValue(graph); // property currently used by rdflib - } - - /** Alias for graph, favored by Tim */ - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Statement, [{ - key: "why", - get: function get() { - return this.graph; - }, - set: function set(g) { - this.graph = g; - } - - /** - * Checks whether two statements are the same - * @param other - The other statement - */ - }, { - key: "equals", - value: function equals(other) { - return other.subject.equals(this.subject) && other.predicate.equals(this.predicate) && other.object.equals(this.object) && other.graph.equals(this.graph); - } - - /** - * Creates a statement with the bindings substituted - * @param bindings The bindings - */ - }, { - key: "substitute", - value: function substitute(bindings) { - var y = new Statement(this.subject.substitute(bindings), this.predicate.substitute(bindings), this.object.substitute(bindings), (0,_default_graph__WEBPACK_IMPORTED_MODULE_3__.isDefaultGraph)(this.graph) ? this.graph : this.graph.substitute(bindings)); // 2016 - // console.log('@@@ statement substitute:' + y) - return y; - } - - /** Creates a canonical string representation of this statement. */ - }, { - key: "toCanonical", - value: function toCanonical() { - var terms = [this.subject.toCanonical(), this.predicate.toCanonical(), this.object.toCanonical()]; - if (this.graph && this.graph.termType !== _types__WEBPACK_IMPORTED_MODULE_5__.DefaultGraphTermType) { - terms.push(this.graph.toCanonical()); - } - return terms.join(' ') + ' .'; - } - - /** Creates a n-triples string representation of this statement */ - }, { - key: "toNT", - value: function toNT() { - return [this.subject.toNT(), this.predicate.toNT(), this.object.toNT()].join(' ') + ' .'; - } - - /** Creates a n-quads string representation of this statement */ - }, { - key: "toNQ", - value: function toNQ() { - return [this.subject.toNT(), this.predicate.toNT(), this.object.toNT(), (0,_default_graph__WEBPACK_IMPORTED_MODULE_3__.isDefaultGraph)(this.graph) ? '' : this.graph.toNT()].join(' ') + ' .'; - } - - /** Creates a string representation of this statement */ - }, { - key: "toString", - value: function toString() { - /* - return [ - this.subject.toString(), - this.predicate.toString(), - this.object.toString(), - ].join(' ') + ' .' - */ - return this.toNT(); - } - }]); - return Statement; -}(); - - -/***/ }), - -/***/ "../rdflib/esm/store.js": -/*!******************************!*\ - !*** ../rdflib/esm/store.js ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ IndexedFormula), -/* harmony export */ "defaultGraphURI": () => (/* reexport safe */ _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_7__.defaultGraphURI) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); -/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "../rdflib/esm/utils/default-graph-uri.js"); -/* harmony import */ var _formula__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./formula */ "../rdflib/esm/formula.js"); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils */ "../rdflib/esm/utils.js"); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); -/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./node */ "../rdflib/esm/node.js"); -/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./variable */ "../rdflib/esm/variable.js"); -/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./query */ "../rdflib/esm/query.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); -/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./index */ "../rdflib/esm/index.js"); -/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./serialize */ "../rdflib/esm/serialize.js"); -/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./blank-node */ "../rdflib/esm/blank-node.js"); -/* harmony import */ var _default_graph__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./default-graph */ "../rdflib/esm/default-graph.js"); -/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./literal */ "../rdflib/esm/literal.js"); - - - - - - - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -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; } } }; } -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); } -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; } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -/* Identity management and indexing for RDF - * - * This file provides IndexedFormula a formula (set of triples) which - * indexed by predicate, subject and object. - * - * It "smushes" (merges into a single node) things which are identical - * according to owl:sameAs or an owl:InverseFunctionalProperty - * or an owl:FunctionalProperty - * - * - * 2005-10 Written Tim Berners-Lee - * 2007 Changed so as not to munge statements from documents when smushing - * 2019 Converted to typescript - * - * -*/ - -/** @module store */ - - - - - - - - - - - - - - - - - -var owlNamespaceURI = 'http://www.w3.org/2002/07/owl#'; - -// var link_ns = 'http://www.w3.org/2007/ont/link#' - -// Handle Functional Property -function handleFP(formula, subj, pred, obj) { - var o1 = formula.any(subj, pred, undefined); - if (!o1) { - return false; // First time with this value - } - // log.warn("Equating "+o1.uri+" and "+obj.uri + " because FP "+pred.uri); //@@ - formula.equate(o1, obj); - return true; -} // handleFP - -// Handle Inverse Functional Property -function handleIFP(formula, subj, pred, obj) { - var s1 = formula.any(undefined, pred, obj); - if (!s1) { - return false; // First time with this value - } - // log.warn("Equating "+s1.uri+" and "+subj.uri + " because IFP "+pred.uri); //@@ - formula.equate(s1, subj); - return true; -} // handleIFP - -function handleRDFType(formula, subj, pred, obj, why) { - //@ts-ignore this method does not seem to exist in this library - if (formula.typeCallback) { - formula.typeCallback(formula, obj, why); - } - var x = formula.classActions[formula.id(obj)]; - var done = false; - if (x) { - for (var i = 0; i < x.length; i++) { - done = done || x[i](formula, subj, pred, obj, why); - } - } - return done; // statement given is not needed if true -} - -/** - * Indexed Formula aka Store - */ -var IndexedFormula = /*#__PURE__*/function (_Formula) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(IndexedFormula, _Formula); - var _super = _createSuper(IndexedFormula); - // IN future - allow pass array of statements to constructor - /** - * An UpdateManager initialised to this store - */ - - /** - * Dictionary of namespace prefixes - */ - - /** Map of iri predicates to functions to call when adding { s type X } */ - - /** Map of iri predicates to functions to call when getting statement with {s X o} */ - - /** Redirect to lexically smaller equivalent symbol */ - - /** Reverse mapping to redirection: aliases for this */ - - /** Redirections we got from HTTP */ - - /** Array of statements with this X as subject */ - - /** Array of statements with this X as predicate */ - - /** Array of statements with this X as object */ - - /** Array of statements with X as provenance */ - - /** Function to remove quads from the store arrays with */ - - /** Callbacks which are triggered after a statement has been added to the store */ - - /** - * Creates a new formula - * @param features - What sort of automatic processing to do? Array of string - * @param features.sameAs - Smush together A and B nodes whenever { A sameAs B } - * @param opts - * @param [opts.rdfFactory] - The data factory that should be used by the store - * @param [opts.rdfArrayRemove] - Function which removes statements from the store - * @param [opts.dataCallback] - Callback when a statement is added to the store, will not trigger when adding duplicates - */ - function IndexedFormula(features) { - var _this; - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, IndexedFormula); - _this = _super.call(this, undefined, undefined, undefined, undefined, opts); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "updater", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "namespaces", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classActions", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "propertyActions", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "redirections", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "aliases", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "HTTPRedirects", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "subjectIndex", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "predicateIndex", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "objectIndex", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "whyIndex", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "index", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "features", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "_universalVariables", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "_existentialVariables", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "rdfArrayRemove", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "dataCallbacks", void 0); - _this.propertyActions = {}; - _this.classActions = {}; - _this.redirections = []; - _this.aliases = []; - _this.HTTPRedirects = []; - _this.subjectIndex = []; - _this.predicateIndex = []; - _this.objectIndex = []; - _this.whyIndex = []; - _this.index = [_this.subjectIndex, _this.predicateIndex, _this.objectIndex, _this.whyIndex]; - _this.namespaces = {}; // Dictionary of namespace prefixes - _this.features = features || [// By default, devs do not expect these features. - // See https://github.com/linkeddata/rdflib.js/issues/458 - // 'sameAs', - // 'InverseFunctionalProperty', - // 'FunctionalProperty', - ]; - _this.rdfArrayRemove = opts.rdfArrayRemove || _utils_js__WEBPACK_IMPORTED_MODULE_8__.RDFArrayRemove; - if (opts.dataCallback) { - _this.dataCallbacks = [opts.dataCallback]; - } - _this.initPropertyActions(_this.features); - return _this; - } - - /** - * Gets the URI of the default graph - */ - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(IndexedFormula, [{ - key: "substitute", - value: - /** - * Gets this graph with the bindings substituted - * @param bindings The bindings - */ - function substitute(bindings) { - var statementsCopy = this.statements.map(function (ea) { - return ea.substitute(bindings); - }); - var y = new IndexedFormula(); - y.add(statementsCopy); - return y; - } - - /** - * Add a callback which will be triggered after a statement has been added to the store. - * @param cb - */ - }, { - key: "addDataCallback", - value: function addDataCallback(cb) { - if (!this.dataCallbacks) { - this.dataCallbacks = []; - } - this.dataCallbacks.push(cb); - } - - /** - * Apply a set of statements to be deleted and to be inserted - * - * @param patch - The set of statements to be deleted and to be inserted - * @param target - The name of the document to patch - * @param patchCallback - Callback to be called when patching is complete - */ - }, { - key: "applyPatch", - value: function applyPatch(patch, target, patchCallback) { - var targetKB = this; - var ds; - var binding = null; - function doPatch(onDonePatch) { - if (patch['delete']) { - ds = patch['delete']; - // console.log(bindingDebug(binding)) - // console.log('ds before substitute: ' + ds) - if (binding) ds = ds.substitute(binding); - // console.log('applyPatch: delete: ' + ds) - ds = ds.statements; - var bad = []; - var ds2 = ds.map(function (st) { - // Find the actual statements in the store - var sts = targetKB.statementsMatching(st.subject, st.predicate, st.object, target); - if (sts.length === 0) { - // log.info("NOT FOUND deletable " + st) - bad.push(st); - return null; - } else { - // log.info("Found deletable " + st) - return sts[0]; - } - }); - if (bad.length) { - // console.log('Could not find to delete ' + bad.length + 'statements') - // console.log('despite ' + targetKB.statementsMatching(bad[0].subject, bad[0].predicate)[0]) - return patchCallback('Could not find to delete: ' + bad.join('\n or ')); - } - ds2.map(function (st) { - targetKB.remove(st); - }); - } - if (patch['insert']) { - // log.info("doPatch insert "+patch['insert']) - ds = patch['insert']; - if (binding) ds = ds.substitute(binding); - ds = ds.statements; - ds.map(function (st) { - st.graph = target; - targetKB.add(st.subject, st.predicate, st.object, st.graph); - }); - } - onDonePatch(); - } - if (patch.where) { - // log.info("Processing WHERE: " + patch.where + '\n') - var query = new _query__WEBPACK_IMPORTED_MODULE_9__.Query('patch'); - query.pat = patch.where; - query.pat.statements.map(function (st) { - st.graph = (0,_index__WEBPACK_IMPORTED_MODULE_10__.namedNode)(target.value); - }); - //@ts-ignore TODO: add sync property to Query when converting Query to typescript - query.sync = true; - var bindingsFound = []; - targetKB.query(query, function onBinding(binding) { - bindingsFound.push(binding); - // console.log(' got a binding: ' + bindingDebug(binding)) - }, targetKB.fetcher, function onDone() { - if (bindingsFound.length === 0) { - return patchCallback('No match found to be patched:' + patch.where); - } - if (bindingsFound.length > 1) { - return patchCallback('Patch ambiguous. No patch done.'); - } - binding = bindingsFound[0]; - doPatch(patchCallback); - }); - } else { - doPatch(patchCallback); - } - } - - /** - * N3 allows for declaring blank nodes, this function enables that support - * - * @param x The blank node to be declared, supported in N3 - */ - }, { - key: "declareExistential", - value: function declareExistential(x) { - if (!this._existentialVariables) this._existentialVariables = []; - this._existentialVariables.push(x); - return x; - } - - /** - * @param features - */ - }, { - key: "initPropertyActions", - value: function initPropertyActions(features) { - // If the predicate is #type, use handleRDFType to create a typeCallback on the object - this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'))] = [handleRDFType]; - - // Assumption: these terms are not redirected @@fixme - if ((0,_utils__WEBPACK_IMPORTED_MODULE_11__.ArrayIndexOf)(features, 'sameAs') >= 0) { - this.propertyActions[this.rdfFactory.id(this.rdfFactory.namedNode("".concat(owlNamespaceURI, "sameAs")))] = [function (formula, subj, pred, obj, why) { - // log.warn("Equating "+subj.uri+" sameAs "+obj.uri); //@@ - formula.equate(subj, obj); - return true; // true if statement given is NOT needed in the store - }]; // sameAs -> equate & don't add to index - } - - if ((0,_utils__WEBPACK_IMPORTED_MODULE_11__.ArrayIndexOf)(features, 'InverseFunctionalProperty') >= 0) { - this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode("".concat(owlNamespaceURI, "InverseFunctionalProperty")))] = [function (formula, subj, pred, obj, addFn) { - // yes subj not pred! - return formula.newPropertyAction(subj, handleIFP); - }]; // IFP -> handleIFP, do add to index - } - - if ((0,_utils__WEBPACK_IMPORTED_MODULE_11__.ArrayIndexOf)(features, 'FunctionalProperty') >= 0) { - this.classActions[this.rdfFactory.id(this.rdfFactory.namedNode("".concat(owlNamespaceURI, "FunctionalProperty")))] = [function (formula, subj, proj, obj, addFn) { - return formula.newPropertyAction(subj, handleFP); - }]; // FP => handleFP, do add to index - } - } - - /** @deprecated Use {add} instead */ - }, { - key: "addStatement", - value: function addStatement(st) { - this.add(st.subject, st.predicate, st.object, st.graph); - return this.statements.length; - } - - /** - * Adds a triple (quad) to the store. - * - * @param subj - The thing about which the fact a relationship is asserted. - * Also accepts a statement or an array of Statements. - * @param pred - The relationship which is asserted - * @param obj - The object of the relationship, e.g. another thing or a value. If passed a string, this will become a literal. - * @param why - The document in which the triple (S,P,O) was or will be stored on the web - * @returns The statement added to the store, or the store - */ - }, { - key: "add", - value: function add(subj, pred, obj, why) { - var i; - if (arguments.length === 1) { - if (subj instanceof Array) { - for (i = 0; i < subj.length; i++) { - this.add(subj[i]); - } - } else if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_12__.isQuad)(subj)) { - this.add(subj.subject, subj.predicate, subj.object, subj.graph); - } else if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_12__.isStore)(subj)) { - this.add(subj.statements); - } - return this; - } - var actions; - var st; - if (!why) { - // system generated - why = this.fetcher ? this.fetcher.appNode : this.rdfFactory.defaultGraph(); - } - if (typeof subj == 'string') { - subj = this.rdfFactory.namedNode(subj); - } - pred = _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(pred); - var objNode = _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(obj); - why = _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(why); - if (!(0,_utils_terms__WEBPACK_IMPORTED_MODULE_12__.isRDFlibSubject)(subj)) { - throw new Error('Subject is not a subject type'); - } - if (!(0,_utils_terms__WEBPACK_IMPORTED_MODULE_12__.isRDFlibPredicate)(pred)) { - throw new Error("Predicate ".concat(pred, " is not a predicate type")); - } - if (!(0,_utils_terms__WEBPACK_IMPORTED_MODULE_12__.isRDFlibObject)(objNode)) { - throw new Error("Object ".concat(objNode, " is not an object type")); - } - if (!(0,_utils_terms__WEBPACK_IMPORTED_MODULE_12__.isGraph)(why)) { - throw new Error("Why is not a graph type"); - } - //@ts-ignore This is not used internally - if (this.predicateCallback) { - //@ts-ignore This is not used internally - this.predicateCallback(this, pred, why); - } - // Action return true if the statement does not need to be added - var predHash = this.id(this.canon(pred)); - actions = this.propertyActions[predHash]; // Predicate hash - var done = false; - if (actions) { - // alert('type: '+typeof actions +' @@ actions='+actions) - for (i = 0; i < actions.length; i++) { - done = done || actions[i](this, subj, pred, objNode, why); - } - } - if (this.holds(subj, pred, objNode, why)) { - // Takes time but saves duplicates - // console.log('rdflib: Ignoring dup! {' + subj + ' ' + pred + ' ' + obj + ' ' + why + '}') - return null; // @@better to return self in all cases? - } - // If we are tracking provenance, every thing should be loaded into the store - // if (done) return this.rdfFactory.quad(subj, pred, obj, why) - // Don't put it in the store - // still return this statement for owl:sameAs input - var hash = [this.id(this.canon(subj)), predHash, this.id(this.canon(objNode)), this.id(this.canon(why))]; - // @ts-ignore this will fail if you pass a collection and the factory does not allow Collections - st = this.rdfFactory.quad(subj, pred, objNode, why); - for (i = 0; i < 4; i++) { - var ix = this.index[i]; - var h = hash[i]; - if (!ix[h]) { - ix[h] = []; - } - ix[h].push(st); // Set of things with this as subject, etc - } - - // log.debug("ADDING {"+subj+" "+pred+" "+objNode+"} "+why) - this.statements.push(st); - if (this.dataCallbacks) { - var _iterator = _createForOfIteratorHelper(this.dataCallbacks), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var callback = _step.value; - callback(st); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - return st; - } - - /** - * Returns the symbol with canonical URI as smushed - * @param term - An RDF node - */ - }, { - key: "canon", - value: function canon(term) { - if (!term) { - // @@ TODO Should improve this to return proper value - doing this to keep it backward compatible - return term; - } - var y = this.redirections[this.id(term)]; - if (y) { - return y; - } - switch (term.termType) { - case _types__WEBPACK_IMPORTED_MODULE_14__.BlankNodeTermType: - return new _blank_node__WEBPACK_IMPORTED_MODULE_15__["default"](term.value); - case _types__WEBPACK_IMPORTED_MODULE_14__.CollectionTermType: - return term; - // non-RDF/JS type, should just need to cast - case _types__WEBPACK_IMPORTED_MODULE_14__.DefaultGraphTermType: - return new _default_graph__WEBPACK_IMPORTED_MODULE_16__["default"](); - case _types__WEBPACK_IMPORTED_MODULE_14__.EmptyTermType: - // non-RDF/JS type, should just need to cast - return term; - case _types__WEBPACK_IMPORTED_MODULE_14__.GraphTermType: - // non-RDF/JS type, should just need to cast - return term; - case _types__WEBPACK_IMPORTED_MODULE_14__.LiteralTermType: - return new _literal__WEBPACK_IMPORTED_MODULE_17__["default"](term.value, term.language, term.datatype); - case _types__WEBPACK_IMPORTED_MODULE_14__.NamedNodeTermType: - return new _named_node__WEBPACK_IMPORTED_MODULE_18__["default"](term.value); - case _types__WEBPACK_IMPORTED_MODULE_14__.VariableTermType: - return new _variable__WEBPACK_IMPORTED_MODULE_19__["default"](term.value); - default: - throw new Error("Term Type not recognized for canonization: ".concat(term.termType)); - } - } - - /** - * Checks this formula for consistency - */ - }, { - key: "check", - value: function check() { - this.checkStatementList(this.statements); - for (var p = 0; p < 4; p++) { - var ix = this.index[p]; - for (var key in ix) { - if (ix.hasOwnProperty(key)) { - // @ts-ignore should this pass an array or a single statement? checkStateMentsList expects an array. - this.checkStatementList(ix[key], p); - } - } - } - } - - /** - * Checks a list of statements for consistency - * @param sts - The list of statements to check - * @param from - An index with the array ['subject', 'predicate', 'object', 'why'] - */ - }, { - key: "checkStatementList", - value: function checkStatementList(sts, from) { - if (from === undefined) { - from = 0; - } - var names = ['subject', 'predicate', 'object', 'why']; - var origin = ' found in ' + names[from] + ' index.'; - var st; - for (var j = 0; j < sts.length; j++) { - st = sts[j]; - var term = [st.subject, st.predicate, st.object, st.graph]; - var arrayContains = function arrayContains(a, x) { - for (var i = 0; i < a.length; i++) { - if (a[i].subject.equals(x.subject) && a[i].predicate.equals(x.predicate) && a[i].object.equals(x.object) && a[i].why.equals(x.graph)) { - return true; - } - } - }; - for (var p = 0; p < 4; p++) { - var c = this.canon(term[p]); - var h = this.id(c); - if (!this.index[p][h]) { - // throw new Error('No ' + name[p] + ' index for statement ' + st + '@' + st.why + origin) - } else { - if (!arrayContains(this.index[p][h], st)) { - // throw new Error('Index for ' + name[p] + ' does not have statement ' + st + '@' + st.why + origin) - } - } - } - if (!arrayContains(this.statements, st)) { - throw new Error('Statement list does not statement ' + st + '@' + st.graph + origin); - } - } - } - - /** - * Closes this formula (and return it) - */ - }, { - key: "close", - value: function close() { - return this; - } - }, { - key: "compareTerms", - value: function compareTerms(u1, u2) { - // Keep compatibility with downstream classOrder changes - if (Object.prototype.hasOwnProperty.call(u1, "compareTerm")) { - return u1.compareTerm(u2); - } - if (_class_order__WEBPACK_IMPORTED_MODULE_20__["default"][u1.termType] < _class_order__WEBPACK_IMPORTED_MODULE_20__["default"][u2.termType]) { - return -1; - } - if (_class_order__WEBPACK_IMPORTED_MODULE_20__["default"][u1.termType] > _class_order__WEBPACK_IMPORTED_MODULE_20__["default"][u2.termType]) { - return +1; - } - if (u1.value < u2.value) { - return -1; - } - if (u1.value > u2.value) { - return +1; - } - return 0; - } - - /** - * replaces @template with @target and add appropriate triples - * removes no triples by default and is a one-direction replication - * @param template node to copy - * @param target node to copy to - * @param flags Whether or not to do a two-directional copy and/or delete triples - */ - }, { - key: "copyTo", - value: function copyTo(template, target, flags) { - if (!flags) flags = []; - var statList = this.statementsMatching(template); - if ((0,_utils__WEBPACK_IMPORTED_MODULE_11__.ArrayIndexOf)(flags, 'two-direction') !== -1) { - statList.concat(this.statementsMatching(undefined, undefined, template)); - } - for (var i = 0; i < statList.length; i++) { - var st = statList[i]; - switch (st.object.termType) { - case 'NamedNode': - this.add(target, st.predicate, st.object); - break; - case 'Literal': - case 'BlankNode': - // @ts-ignore Collections can appear here - case 'Collection': - // @ts-ignore Possible bug: copy is not available on Collections - this.add(target, st.predicate, st.object.copy(this)); - } - if ((0,_utils__WEBPACK_IMPORTED_MODULE_11__.ArrayIndexOf)(flags, 'delete') !== -1) { - this.remove(st); - } - } - } - - /** - * Simplify graph in store when we realize two identifiers are equivalent - * We replace the bigger with the smaller. - * @param u1in The first node - * @param u2in The second node - */ - }, { - key: "equate", - value: function equate(u1in, u2in) { - // log.warn("Equating "+u1+" and "+u2); // @@ - // @@JAMBO Must canonicalize the uris to prevent errors from a=b=c - // 03-21-2010 - var u1 = this.canon(u1in); - var u2 = this.canon(u2in); - var d = this.compareTerms(u1, u2); - if (!d) { - return true; // No information in {a = a} - } - // var big - // var small - if (d < 0) { - // u1 less than u2 - return this.replaceWith(u2, u1); - } else { - return this.replaceWith(u1, u2); - } - } - - /** - * Creates a new empty indexed formula - * Only applicable for IndexedFormula, but TypeScript won't allow a subclass to override a property - * @param features The list of features - */ - }, { - key: "formula", - value: function formula(features) { - return new IndexedFormula(features); - } - - /** - * Returns the number of statements contained in this IndexedFormula. - * (Getter proxy to this.statements). - * Usage: - * ``` - * var kb = rdf.graph() - * kb.length // -> 0 - * ``` - * @returns {Number} - */ - }, { - key: "length", - get: function get() { - return this.statements.length; - } - - /** - * Returns any quads matching the given arguments. - * Standard RDFJS spec method for Source objects, implemented as an - * alias to `statementsMatching()` - * @param subject The subject - * @param predicate The predicate - * @param object The object - * @param graph The graph that contains the statement - */ - }, { - key: "match", - value: function match(subject, predicate, object, graph) { - return this.statementsMatching(_node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(subject), _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(predicate), _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(object), _node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(graph)); - } - - /** - * Find out whether a given URI is used as symbol in the formula - * @param uri The URI to look for - */ - }, { - key: "mentionsURI", - value: function mentionsURI(uri) { - var hash = '<' + uri + '>'; - return !!this.subjectIndex[hash] || !!this.objectIndex[hash] || !!this.predicateIndex[hash]; - } - - /** - * Existentials are BNodes - something exists without naming - * @param uri An URI - */ - }, { - key: "newExistential", - value: function newExistential(uri) { - if (!uri) return this.bnode(); - var x = this.sym(uri); - // @ts-ignore x should be blanknode, but is namedNode. - return this.declareExistential(x); - } - - /** - * Adds a new property action - * @param pred the predicate that the function should be triggered on - * @param action the function that should trigger - */ - }, { - key: "newPropertyAction", - value: function newPropertyAction(pred, action) { - // log.debug("newPropertyAction: "+pred) - var hash = this.id(pred); - if (!this.propertyActions[hash]) { - this.propertyActions[hash] = []; - } - this.propertyActions[hash].push(action); - // Now apply the function to to statements already in the store - var toBeFixed = this.statementsMatching(undefined, pred, undefined); - var done = false; - for (var i = 0; i < toBeFixed.length; i++) { - // NOT optimized - sort toBeFixed etc - done = done || action(this, toBeFixed[i].subject, pred, toBeFixed[i].object); - } - return done; - } - - /** - * Creates a new universal node - * Universals are Variables - * @param uri An URI - */ - }, { - key: "newUniversal", - value: function newUniversal(uri) { - var x = this.sym(uri); - if (!this._universalVariables) this._universalVariables = []; - this._universalVariables.push(x); - return x; - } - - // convenience function used by N3 parser - }, { - key: "variable", - value: function variable(name) { - return new _variable__WEBPACK_IMPORTED_MODULE_19__["default"](name); - } - - /** - * Find an unused id for a file being edited: return a symbol - * (Note: Slow iff a lot of them -- could be O(log(k)) ) - * @param doc A document named node - */ - }, { - key: "nextSymbol", - value: function nextSymbol(doc) { - for (var i = 0;; i++) { - var uri = doc.value + '#n' + i; - if (!this.mentionsURI(uri)) return this.sym(uri); - } - } - - /** - * Query this store asynchronously, return bindings in callback - * - * @param myQuery The query to be run - * @param callback Function to call when bindings - * @param Fetcher | null If you want the query to do link following - * @param onDone OBSOLETE - do not use this // @@ Why not ?? Called when query complete - */ - }, { - key: "query", - value: function query(myQuery, callback, fetcher, onDone) { - return _query__WEBPACK_IMPORTED_MODULE_9__.indexedFormulaQuery.call(this, myQuery, callback, fetcher, onDone); - } - - /** - * Query this store synchronously and return bindings - * - * @param myQuery The query to be run - */ - }, { - key: "querySync", - value: function querySync(myQuery) { - var results = []; - function saveBinginds(bindings) { - results.push(bindings); - } - function onDone() { - done = true; - } - var done = false; - // @ts-ignore TODO: Add .sync to Query - myQuery.sync = true; - _query__WEBPACK_IMPORTED_MODULE_9__.indexedFormulaQuery.call(this, myQuery, saveBinginds, null, onDone); - if (!done) { - throw new Error('Sync query should have called done function'); - } - return results; - } - - /** - * Removes one or multiple statement(s) from this formula - * @param st - A Statement or array of Statements to remove - */ - }, { - key: "remove", - value: function remove(st) { - if (st instanceof Array) { - for (var i = 0; i < st.length; i++) { - this.remove(st[i]); - } - return this; - } - if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_12__.isStore)(st)) { - return this.remove(st.statements); - } - var sts = this.statementsMatching(st.subject, st.predicate, st.object, st.graph); - if (!sts.length) { - throw new Error('Statement to be removed is not on store: ' + st); - } - this.removeStatement(sts[0]); - return this; - } - - /** - * Removes all statements in a doc, the related metadata including request/response - * @param doc - The document / graph - */ - }, { - key: "removeDocument", - value: function removeDocument(doc) { - var meta = this.sym('chrome://TheCurrentSession'); // or this.rdfFactory.namedNode('chrome://TheCurrentSession') - var linkNamespaceURI = 'http://www.w3.org/2007/ont/link#'; // alain - // remove request/response and metadata - var requests = this.statementsMatching(undefined, this.sym("".concat(linkNamespaceURI, "requestedURI")), this.rdfFactory.literal(doc.value), meta).map(function (st) { - return st.subject; - }); - for (var r = 0; r < requests.length; r++) { - var request = requests[r]; - if (request !== undefined) { - this.removeMatches(request, null, null, meta); - var response = this.any(request, this.sym("".concat(linkNamespaceURI, "response")), null, meta); - if (response !== undefined) { - // ts - this.removeMatches(response, null, null, meta); - } - } - } - this.removeMatches(this.sym(doc.value), null, null, meta); // content-type - - // remove document - var sts = this.statementsMatching(undefined, undefined, undefined, doc).slice(); // Take a copy as this is the actual index - for (var i = 0; i < sts.length; i++) { - this.removeStatement(sts[i]); - } - return this; - } - - /** - * Remove all statements matching args (within limit) * - * @param subj The subject - * @param pred The predicate - * @param obj The object - * @param why The graph that contains the statement - * @param limit The number of statements to remove - */ - }, { - key: "removeMany", - value: function removeMany(subj, pred, obj, why, limit) { - // log.debug("entering removeMany w/ subj,pred,obj,why,limit = " + subj +", "+ pred+", " + obj+", " + why+", " + limit) - var sts = this.statementsMatching(subj, pred, obj, why, false); - // This is a subtle bug that occurred in updateCenter.js too. - // The fact is, this.statementsMatching returns this.whyIndex instead of a copy of it - // but for perfromance consideration, it's better to just do that - // so make a copy here. - var statements = []; - for (var i = 0; i < sts.length; i++) statements.push(sts[i]); - if (limit) statements = statements.slice(0, limit); - for (i = 0; i < statements.length; i++) this.remove(statements[i]); - } - - /** - * Remove all matching statements - * @param subject The subject - * @param predicate The predicate - * @param object The object - * @param graph The graph that contains the statement - */ - }, { - key: "removeMatches", - value: function removeMatches(subject, predicate, object, graph) { - this.removeMany(subject, predicate, object, graph); - return this; - } - - /** - * Remove a particular statement object from the store - * - * @param st - a statement which is already in the store and indexed. - * Make sure you only use this for these. - * Otherwise, you should use remove() above. - */ - }, { - key: "removeStatement", - value: function removeStatement(st) { - // log.debug("entering remove w/ st=" + st) - var term = [st.subject, st.predicate, st.object, st.graph]; - for (var p = 0; p < 4; p++) { - var c = this.canon(term[p]); - var h = this.id(c); - if (!this.index[p][h]) { - // log.warn ("Statement removal: no index '+p+': "+st) - } else { - this.rdfArrayRemove(this.index[p][h], st); - } - } - this.rdfArrayRemove(this.statements, st); - return this; - } - - /** - * Removes statements - * @param sts The statements to remove - */ - }, { - key: "removeStatements", - value: function removeStatements(sts) { - for (var i = 0; i < sts.length; i++) { - this.remove(sts[i]); - } - return this; - } - - /** - * Replace big with small, obsoleted with obsoleting. - */ - }, { - key: "replaceWith", - value: function replaceWith(big, small) { - // log.debug("Replacing "+big+" with "+small) // this.id(@@ - var oldhash = this.id(big); - var newhash = this.id(small); - var moveIndex = function moveIndex(ix) { - var oldlist = ix[oldhash]; - if (!oldlist) { - return; // none to move - } - - var newlist = ix[newhash]; - if (!newlist) { - ix[newhash] = oldlist; - } else { - ix[newhash] = oldlist.concat(newlist); - } - delete ix[oldhash]; - }; - // the canonical one carries all the indexes - for (var i = 0; i < 4; i++) { - moveIndex(this.index[i]); - } - this.redirections[oldhash] = small; - if (big.value) { - // @@JAMBO: must update redirections,aliases from sub-items, too. - if (!this.aliases[newhash]) { - this.aliases[newhash] = []; - } - this.aliases[newhash].push(big); // Back link - if (this.aliases[oldhash]) { - for (i = 0; i < this.aliases[oldhash].length; i++) { - this.redirections[this.id(this.aliases[oldhash][i])] = small; - this.aliases[newhash].push(this.aliases[oldhash][i]); - } - } - this.add(small, this.sym('http://www.w3.org/2007/ont/link#uri'), big); - // If two things are equal, and one is requested, we should request the other. - if (this.fetcher) { - this.fetcher.nowKnownAs(big, small); - } - } - moveIndex(this.classActions); - moveIndex(this.propertyActions); - // log.debug("Equate done. "+big+" to be known as "+small) - return true; // true means the statement does not need to be put in - } - - /** - * Return all equivalent URIs by which this is known - * @param x A named node - */ - }, { - key: "allAliases", - value: function allAliases(x) { - var a = this.aliases[this.id(this.canon(x))] || []; - a.push(this.canon(x)); - return a; - } - - /** - * Compare by canonical URI as smushed - * @param x A named node - * @param y Another named node - */ - }, { - key: "sameThings", - value: function sameThings(x, y) { - if (x.equals(y)) { - return true; - } - var x1 = this.canon(x); - // alert('x1='+x1) - if (!x1) return false; - var y1 = this.canon(y); - // alert('y1='+y1); //@@ - if (!y1) return false; - return x1.value === y1.value; - } - }, { - key: "setPrefixForURI", - value: function setPrefixForURI(prefix, nsuri) { - // TODO: This is a hack for our own issues, which ought to be fixed - // post-release - // See http://dig.csail.mit.edu/cgi-bin/roundup.cgi/$rdf/issue227 - if (prefix === 'tab' && this.namespaces['tab']) { - return; - } // There are files around with long badly generated prefixes like this - if (prefix.slice(0, 2) === 'ns' || prefix.slice(0, 7) === 'default') { - return; - } - - // remove any prefix that currently targets nsuri - for (var existingPrefix in this.namespaces) { - if (this.namespaces[existingPrefix] == nsuri) delete this.namespaces[existingPrefix]; - } - this.namespaces[prefix] = nsuri; - } - - /** Search the Store - * - * ALL CONVENIENCE LOOKUP FUNCTIONS RELY ON THIS! - * @param subj - A node to search for as subject, or if null, a wildcard - * @param pred - A node to search for as predicate, or if null, a wildcard - * @param obj - A node to search for as object, or if null, a wildcard - * @param why - A node to search for as graph, or if null, a wildcard - * @param justOne - flag - stop when found one rather than get all of them? - * @returns An array of nodes which match the wildcard position - */ - }, { - key: "statementsMatching", - value: function statementsMatching(subj, pred, obj, why, justOne) { - // log.debug("Matching {"+subj+" "+pred+" "+obj+"}") - var pat = [subj, pred, obj, why]; - var pattern = []; - var hash = []; - var wild = []; // wildcards - var given = []; // Not wild - var p; - var list; - for (p = 0; p < 4; p++) { - pattern[p] = this.canon(_node__WEBPACK_IMPORTED_MODULE_13__["default"].fromValue(pat[p])); - if (!pattern[p]) { - wild.push(p); - } else { - given.push(p); - hash[p] = this.id(pattern[p]); - } - } - if (given.length === 0) { - return this.statements; - } - if (given.length === 1) { - // Easy too, we have an index for that - p = given[0]; - list = this.index[p][hash[p]]; - if (list && justOne) { - if (list.length > 1) { - list = list.slice(0, 1); - } - } - list = list || []; - return list; - } - // Now given.length is 2, 3 or 4. - // We hope that the scale-free nature of the data will mean we tend to get - // a short index in there somewhere! - var best = 1e10; // really bad - var iBest; - var i; - for (i = 0; i < given.length; i++) { - p = given[i]; // Which part we are dealing with - list = this.index[p][hash[p]]; - if (!list) { - return []; // No occurrences - } - - if (list.length < best) { - best = list.length; - iBest = i; // (not p!) - } - } - // Ok, we have picked the shortest index but now we have to filter it - var pBest = given[iBest]; - var possibles = this.index[pBest][hash[pBest]]; - var check = given.slice(0, iBest).concat(given.slice(iBest + 1)); // remove iBest - var results = []; - var parts = ['subject', 'predicate', 'object', 'why']; - for (var j = 0; j < possibles.length; j++) { - var st = possibles[j]; - for (i = 0; i < check.length; i++) { - // for each position to be checked - p = check[i]; - if (!this.canon(st[parts[p]]).equals(pattern[p])) { - st = null; - break; - } - } - if (st != null) { - results.push(st); - if (justOne) break; - } - } - return results; - } - - /** - * A list of all the URIs by which this thing is known - * @param term - */ - }, { - key: "uris", - value: function uris(term) { - var cterm = this.canon(term); - var terms = this.aliases[this.id(cterm)]; - if (!cterm.value) return []; - var res = [cterm.value]; - if (terms) { - for (var i = 0; i < terms.length; i++) { - res.push(terms[i].uri); - } - } - return res; - } - }, { - key: "serialize", - value: function serialize(base, contentType, provenance, options) { - var _options; - // override Formula.serialize to force the serializer namespace prefixes - // to those of this IndexedFormula - - // if namespaces are explicitly passed in options, let them override the existing namespaces in this formula - var namespaces = (_options = options) !== null && _options !== void 0 && _options.namespaces ? _objectSpread(_objectSpread({}, this.namespaces), options.namespaces) : _objectSpread({}, this.namespaces); - options = _objectSpread(_objectSpread({}, options || {}), {}, { - namespaces: namespaces - }); - return (0,_serialize__WEBPACK_IMPORTED_MODULE_21__["default"])(provenance, this, base, contentType, undefined, options); - } - }], [{ - key: "defaultGraphURI", - get: function get() { - return _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_7__.defaultGraphURI; - } - }]); - return IndexedFormula; -}(_formula__WEBPACK_IMPORTED_MODULE_22__["default"]); -(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(IndexedFormula, "handleRDFType", void 0); - -IndexedFormula.handleRDFType = handleRDFType; - -/***/ }), - -/***/ "../rdflib/esm/types.js": -/*!******************************!*\ - !*** ../rdflib/esm/types.js ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "BlankNodeTermType": () => (/* binding */ BlankNodeTermType), -/* harmony export */ "CollectionTermType": () => (/* binding */ CollectionTermType), -/* harmony export */ "DefaultGraphTermType": () => (/* binding */ DefaultGraphTermType), -/* harmony export */ "EmptyTermType": () => (/* binding */ EmptyTermType), -/* harmony export */ "GraphTermType": () => (/* binding */ GraphTermType), -/* harmony export */ "HTMLContentType": () => (/* binding */ HTMLContentType), -/* harmony export */ "JSONLDContentType": () => (/* binding */ JSONLDContentType), -/* harmony export */ "LiteralTermType": () => (/* binding */ LiteralTermType), -/* harmony export */ "N3ContentType": () => (/* binding */ N3ContentType), -/* harmony export */ "N3LegacyContentType": () => (/* binding */ N3LegacyContentType), -/* harmony export */ "NQuadsAltContentType": () => (/* binding */ NQuadsAltContentType), -/* harmony export */ "NQuadsContentType": () => (/* binding */ NQuadsContentType), -/* harmony export */ "NTriplesContentType": () => (/* binding */ NTriplesContentType), -/* harmony export */ "NamedNodeTermType": () => (/* binding */ NamedNodeTermType), -/* harmony export */ "RDFXMLContentType": () => (/* binding */ RDFXMLContentType), -/* harmony export */ "SPARQLUpdateContentType": () => (/* binding */ SPARQLUpdateContentType), -/* harmony export */ "SPARQLUpdateSingleMatchContentType": () => (/* binding */ SPARQLUpdateSingleMatchContentType), -/* harmony export */ "TurtleContentType": () => (/* binding */ TurtleContentType), -/* harmony export */ "TurtleLegacyContentType": () => (/* binding */ TurtleLegacyContentType), -/* harmony export */ "VariableTermType": () => (/* binding */ VariableTermType), -/* harmony export */ "XHTMLContentType": () => (/* binding */ XHTMLContentType) -/* harmony export */ }); -var NamedNodeTermType = "NamedNode"; -var BlankNodeTermType = "BlankNode"; -var LiteralTermType = "Literal"; -var VariableTermType = "Variable"; -var DefaultGraphTermType = "DefaultGraph"; -// Non-RDF/JS types: -var CollectionTermType = "Collection"; -var EmptyTermType = "Empty"; -var GraphTermType = "Graph"; -var HTMLContentType = "text/html"; -var JSONLDContentType = "application/ld+json"; -var N3ContentType = "text/n3"; -var N3LegacyContentType = "application/n3"; -var NQuadsAltContentType = "application/nquads"; -var NQuadsContentType = "application/n-quads"; -var NTriplesContentType = "application/n-triples"; -var RDFXMLContentType = "application/rdf+xml"; -var SPARQLUpdateContentType = "application/sparql-update"; -var SPARQLUpdateSingleMatchContentType = "application/sparql-update-single-match"; -var TurtleContentType = "text/turtle"; -var TurtleLegacyContentType = "application/x-turtle"; -var XHTMLContentType = "application/xhtml+xml"; - -/** - * A valid mime type header - */ - -/***/ }), - -/***/ "../rdflib/esm/update-manager.js": -/*!***************************************!*\ - !*** ../rdflib/esm/update-manager.js ***! - \***************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ UpdateManager) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../rdflib/node_modules/@babel/runtime/helpers/esm/typeof.js"); -/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "../rdflib/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js"); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/regenerator */ "../rdflib/node_modules/@babel/runtime/regenerator/index.js"); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./store */ "../rdflib/esm/store.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); -/* harmony import */ var _fetcher__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./fetcher */ "../rdflib/esm/fetcher.js"); -/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./namespace */ "../rdflib/esm/namespace.js"); -/* harmony import */ var _serializer__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./serializer */ "../rdflib/esm/serializer.js"); -/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils/terms */ "../rdflib/esm/utils/terms.js"); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); -/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./utils/termValue */ "../rdflib/esm/utils/termValue.js"); - - - - - - -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; } } }; } -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); } -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; } -/* @file Update Manager Class -** -** 2007-07-15 originall sparl update module by Joe Presbrey -** 2010-08-08 TimBL folded in Kenny's WEBDAV -** 2010-12-07 TimBL addred local file write code -*/ - - - - - - - - -/** -* The UpdateManager is a helper object for a store. -* Just as a Fetcher provides the store with the ability to read and write, -* the Update Manager provides functionality for making small patches in real time, -* and also looking out for concurrent updates from other agents -*/ -var UpdateManager = /*#__PURE__*/function () { - /** Index of objects for coordinating incoming and outgoing patches */ - - /** Object of namespaces */ - - /** - * @param store - The quadstore to store data and metadata. Created if not passed. - */ - function UpdateManager(store) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__["default"])(this, UpdateManager); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__["default"])(this, "store", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__["default"])(this, "ifps", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__["default"])(this, "fps", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__["default"])(this, "patchControl", void 0); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__["default"])(this, "ns", void 0); - store = store || new _store__WEBPACK_IMPORTED_MODULE_6__["default"](); - if (store.updater) { - throw new Error("You can't have two UpdateManagers for the same store"); - } - if (!store.fetcher) { - store.fetcher = new _fetcher__WEBPACK_IMPORTED_MODULE_7__["default"](store); - } - this.store = store; - store.updater = this; - this.ifps = {}; - this.fps = {}; - this.ns = {}; - this.ns.link = (0,_namespace__WEBPACK_IMPORTED_MODULE_8__["default"])('http://www.w3.org/2007/ont/link#'); - this.ns.http = (0,_namespace__WEBPACK_IMPORTED_MODULE_8__["default"])('http://www.w3.org/2007/ont/http#'); - this.ns.httph = (0,_namespace__WEBPACK_IMPORTED_MODULE_8__["default"])('http://www.w3.org/2007/ont/httph#'); - this.ns.ldp = (0,_namespace__WEBPACK_IMPORTED_MODULE_8__["default"])('http://www.w3.org/ns/ldp#'); - this.ns.rdf = (0,_namespace__WEBPACK_IMPORTED_MODULE_8__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#'); - this.ns.rdfs = (0,_namespace__WEBPACK_IMPORTED_MODULE_8__["default"])('http://www.w3.org/2000/01/rdf-schema#'); - this.ns.rdf = (0,_namespace__WEBPACK_IMPORTED_MODULE_8__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#'); - this.ns.owl = (0,_namespace__WEBPACK_IMPORTED_MODULE_8__["default"])('http://www.w3.org/2002/07/owl#'); - this.patchControl = []; - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__["default"])(UpdateManager, [{ - key: "patchControlFor", - value: function patchControlFor(doc) { - if (!this.patchControl[doc.value]) { - this.patchControl[doc.value] = []; - } - return this.patchControl[doc.value]; - } - }, { - key: "isHttpUri", - value: function isHttpUri(uri) { - return uri.slice(0, 4) === 'http'; - } - - /** Remove from the store HTTP authorization metadata - * The editble function below relies on copies we have in the store - * of the results of previous HTTP transactions. Howver, when - * the user logs in, then that data misrepresents what would happen - * if the user tried again. - */ - }, { - key: "flagAuthorizationMetadata", - value: function flagAuthorizationMetadata() { - var kb = this.store; - var meta = kb.fetcher.appNode; - var requests = kb.statementsMatching(undefined, this.ns.link('requestedURI'), undefined, meta).map(function (st) { - return st.subject; - }); - var _iterator = _createForOfIteratorHelper(requests), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var request = _step.value; - var _response = kb.any(request, this.ns.link('response'), null, meta); - if (_response !== undefined) { - // ts - this.store.add(_response, this.ns.link('outOfDate'), true, meta); // @@ Boolean is fine - fix types - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } - - /** - * Tests whether a file is editable. - * If the file has a specific annotation that it is machine written, - * for safety, it is editable (this doesn't actually check for write access) - * If the file has wac-allow and accept patch headers, those are respected. - * and local write access is determined by those headers. - * This async version not only looks at past HTTP requests, it also makes new ones if necessary. - * - * @returns The method string SPARQL or DAV or - * LOCALFILE or false if known, undefined if not known. - */ - }, { - key: "checkEditable", - value: function () { - var _checkEditable = (0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__["default"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_5___default().mark(function _callee(uri, kb) { - var initial, final; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_5___default().wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - initial = this.editable(uri, kb); - if (!(initial !== undefined)) { - _context.next = 3; - break; - } - return _context.abrupt("return", initial); - case 3: - _context.next = 5; - return this.store.fetcher.load(uri); - case 5: - final = this.editable(uri, kb); // console.log(`Loaded ${uri} just to check editable, result: ${final}.`) - return _context.abrupt("return", final); - case 7: - case "end": - return _context.stop(); - } - }, _callee, this); - })); - function checkEditable(_x, _x2) { - return _checkEditable.apply(this, arguments); - } - return checkEditable; - }() - /** - * Tests whether a file is editable. - * If the file has a specific annotation that it is machine written, - * for safety, it is editable (this doesn't actually check for write access) - * If the file has wac-allow and accept patch headers, those are respected. - * and local write access is determined by those headers. - * This synchronous version only looks at past HTTP requests, does not make new ones. - * - * @returns The method string SPARQL or DAV or - * LOCALFILE or false if known, undefined if not known. - */ - }, { - key: "editable", - value: function editable(uri, kb) { - if (!uri) { - return false; // Eg subject is bnode, no known doc to write to - } - - if (!kb) { - kb = this.store; - } - uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_9__.termValue)(uri); - if (!this.isHttpUri(uri)) { - if (this.store.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'))) { - return 'LOCALFILE'; - } - } - var request; - var definitive = false; - var meta = this.store.fetcher.appNode; - // const kb = s - - // @ts-ignore passes a string to kb.each, which expects a term. Should this work? - var requests = kb.each(undefined, this.ns.link('requestedURI'), (0,_uri__WEBPACK_IMPORTED_MODULE_10__.docpart)(uri), meta); - var method; - for (var r = 0; r < requests.length; r++) { - request = requests[r]; - if (request !== undefined) { - var _response2 = kb.any(request, this.ns.link('response'), null, meta); - if (_response2 !== undefined) { - // ts - - var outOfDate = kb.anyJS(_response2, this.ns.link('outOfDate'), null, meta); - if (outOfDate) continue; - var wacAllow = kb.anyValue(_response2, this.ns.httph('wac-allow')); - if (wacAllow) { - var _iterator2 = _createForOfIteratorHelper(wacAllow.split(',')), - _step2; - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var bit = _step2.value; - var lr = bit.split('='); - if (lr[0].includes('user') && !lr[1].includes('write') && !lr[1].includes('append')) { - // console.log(' editable? excluded by WAC-Allow: ', wacAllow) - return false; - } - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - var acceptPatch = kb.each(_response2, this.ns.httph('accept-patch')); - if (acceptPatch.length) { - for (var i = 0; i < acceptPatch.length; i++) { - method = acceptPatch[i].value.trim(); - if (method.indexOf('application/sparql-update') >= 0) return 'SPARQL'; - if (method.indexOf('application/sparql-update-single-match') >= 0) return 'SPARQL'; - } - } - var authorVia = kb.each(_response2, this.ns.httph('ms-author-via')); - if (authorVia.length) { - for (var _i = 0; _i < authorVia.length; _i++) { - method = authorVia[_i].value.trim(); - if (method.indexOf('SPARQL') >= 0) { - return 'SPARQL'; - } - if (method.indexOf('DAV') >= 0) { - return 'DAV'; - } - } - } - if (!this.isHttpUri(uri)) { - if (!wacAllow) return false;else return 'LOCALFILE'; - } - var status = kb.each(_response2, this.ns.http('status')); - if (status.length) { - for (var _i2 = 0; _i2 < status.length; _i2++) { - // @ts-ignore since statuses should be TFTerms, this should always be false - if (status[_i2] === 200 || status[_i2] === 404) { - definitive = true; - // return false // A definitive answer - } - } - } - } else { - // console.log('UpdateManager.editable: No response for ' + uri + '\n') - } - } - } - if (requests.length === 0) { - // console.log('UpdateManager.editable: No request for ' + uri + '\n') - } else { - if (definitive) { - return false; // We have got a request and it did NOT say editable => not editable - } - } - // console.log('UpdateManager.editable: inconclusive for ' + uri + '\n') - return undefined; // We don't know (yet) as we haven't had a response (yet) - } - }, { - key: "anonymize", - value: function anonymize(obj) { - return obj.toNT().substr(0, 2) === '_:' && this.mentioned(obj) ? '?' + obj.toNT().substr(2) : obj.toNT(); - } - }, { - key: "anonymizeNT", - value: function anonymizeNT(stmt) { - return this.anonymize(stmt.subject) + ' ' + this.anonymize(stmt.predicate) + ' ' + this.anonymize(stmt.object) + ' .'; - } - }, { - key: "nTriples", - value: function nTriples(stmt) { - return "".concat(stmt.subject.toNT(), " ").concat(stmt.predicate.toNT(), " ").concat(stmt.object.toNT(), " ."); - } - - /** - * Returns a list of all bnodes occurring in a statement - * @private - */ - }, { - key: "statementBnodes", - value: function statementBnodes(st) { - return [st.subject, st.predicate, st.object].filter(function (x) { - return (0,_utils_terms__WEBPACK_IMPORTED_MODULE_11__.isBlankNode)(x); - }); - } - - /** - * Returns a list of all bnodes occurring in a list of statements - * @private - */ - }, { - key: "statementArrayBnodes", - value: function statementArrayBnodes(sts) { - var bnodes = []; - for (var i = 0; i < sts.length; i++) { - bnodes = bnodes.concat(this.statementBnodes(sts[i])); - } - bnodes.sort(); // in place sort - result may have duplicates - var bnodes2 = []; - for (var j = 0; j < bnodes.length; j++) { - if (j === 0 || !bnodes[j].equals(bnodes[j - 1])) { - bnodes2.push(bnodes[j]); - } - } - return bnodes2; - } - - /** - * Makes a cached list of [Inverse-]Functional properties - * @private - */ - }, { - key: "cacheIfps", - value: function cacheIfps() { - this.ifps = {}; - var a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('InverseFunctionalProperty')); - for (var i = 0; i < a.length; i++) { - this.ifps[a[i].value] = true; - } - this.fps = {}; - a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('FunctionalProperty')); - for (var _i3 = 0; _i3 < a.length; _i3++) { - this.fps[a[_i3].value] = true; - } - } - - /** - * Returns a context to bind a given node, up to a given depth - * @private - */ - }, { - key: "bnodeContext2", - value: function bnodeContext2(x, source, depth) { - // Return a list of statements which indirectly identify a node - // Depth > 1 if try further indirection. - // Return array of statements (possibly empty), or null if failure - var sts = this.store.statementsMatching(undefined, undefined, x, source); // incoming links - var y; - var res; - for (var i = 0; i < sts.length; i++) { - if (this.fps[sts[i].predicate.value]) { - y = sts[i].subject; - if (!y.isBlank) { - return [sts[i]]; - } - if (depth) { - res = this.bnodeContext2(y, source, depth - 1); - if (res) { - return res.concat([sts[i]]); - } - } - } - } - // outgoing links - sts = this.store.statementsMatching(x, undefined, undefined, source); - for (var _i4 = 0; _i4 < sts.length; _i4++) { - if (this.ifps[sts[_i4].predicate.value]) { - y = sts[_i4].object; - if (!y.isBlank) { - return [sts[_i4]]; - } - if (depth) { - res = this.bnodeContext2(y, source, depth - 1); - if (res) { - return res.concat([sts[_i4]]); - } - } - } - } - return null; // Failure - } - - /** - * Returns the smallest context to bind a given single bnode - * @private - */ - }, { - key: "bnodeContext1", - value: function bnodeContext1(x, source) { - // Return a list of statements which indirectly identify a node - // Breadth-first - for (var depth = 0; depth < 3; depth++) { - // Try simple first - var con = this.bnodeContext2(x, source, depth); - if (con !== null) return con; - } - // If we can't guarantee unique with logic just send all info about node - return this.store.connectedStatements(x, source); // was: - // throw new Error('Unable to uniquely identify bnode: ' + x.toNT()) - } - - /** - * @private - */ - }, { - key: "mentioned", - value: function mentioned(x) { - return this.store.statementsMatching(x, null, null, null).length !== 0 || - // Don't pin fresh bnodes - this.store.statementsMatching(null, x).length !== 0 || this.store.statementsMatching(null, null, x).length !== 0; - } - - /** - * @private - */ - }, { - key: "bnodeContext", - value: function bnodeContext(bnodes, doc) { - var context = []; - if (bnodes.length) { - this.cacheIfps(); - for (var i = 0; i < bnodes.length; i++) { - // Does this occur in old graph? - var bnode = bnodes[i]; - if (!this.mentioned(bnode)) continue; - context = context.concat(this.bnodeContext1(bnode, doc)); - } - } - return context; - } - - /** - * Returns the best context for a single statement - * @private - */ - }, { - key: "statementContext", - value: function statementContext(st) { - var bnodes = this.statementBnodes(st); - return this.bnodeContext(bnodes, st.graph); - } - - /** - * @private - */ - }, { - key: "contextWhere", - value: function contextWhere(context) { - var updater = this; - return !context || context.length === 0 ? '' : 'WHERE { ' + context.map(function (x) { - return updater.anonymizeNT(x); - }).join('\n') + ' }\n'; - } - - /** - * @private - */ - }, { - key: "fire", - value: function fire(uri, query, callbackFunction) { - var _this = this; - var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - return Promise.resolve().then(function () { - if (!uri) { - throw new Error('No URI given for remote editing operation: ' + query); - } - // console.log('UpdateManager: sending update to <' + uri + '>') - - options.noMeta = true; - options.contentType = 'application/sparql-update'; - options.body = query; - return _this.store.fetcher.webOperation('PATCH', uri, options); - }).then(function (response) { - if (!response.ok) { - var _message = 'UpdateManager: update failed for <' + uri + '> status=' + response.status + ', ' + response.statusText + '\n for query: ' + query; - // console.log(message) - throw new Error(_message); - } - - // console.log('UpdateManager: update Ok for <' + uri + '>') - - callbackFunction(uri, response.ok, response.responseText, response); - }).catch(function (err) { - callbackFunction(uri, false, err.message, err); - }); - } - - // ARE THESE THEE FUNCTIONS USED? DEPROCATE? - - /** return a statemnet updating function - * - * This does NOT update the statement. - * It returns an object which includes - * function which can be used to change the object of the statement. - */ - }, { - key: "update_statement", - value: function update_statement(statement) { - if (statement && !statement.graph) { - return; - } - var updater = this; - var context = this.statementContext(statement); - return { - statement: statement ? [statement.subject, statement.predicate, statement.object, statement.graph] : undefined, - statementNT: statement ? this.anonymizeNT(statement) : undefined, - where: updater.contextWhere(context), - set_object: function set_object(obj, callbackFunction) { - var query = this.where; - query += 'DELETE DATA { ' + this.statementNT + ' } ;\n'; - query += 'INSERT DATA { ' + - // @ts-ignore `this` might refer to the wrong scope. Does this work? - this.anonymize(this.statement[0]) + ' ' + - // @ts-ignore - this.anonymize(this.statement[1]) + ' ' + - // @ts-ignore - this.anonymize(obj) + ' ' + ' . }\n'; - updater.fire(this.statement[3].value, query, callbackFunction); - } - }; - } - }, { - key: "insert_statement", - value: function insert_statement(st, callbackFunction) { - var st0 = st instanceof Array ? st[0] : st; - var query = this.contextWhere(this.statementContext(st0)); - if (st instanceof Array) { - var stText = ''; - for (var i = 0; i < st.length; i++) stText += st[i] + '\n'; - query += 'INSERT DATA { ' + stText + ' }\n'; - } else { - query += 'INSERT DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n'; - } - this.fire(st0.graph.value, query, callbackFunction); - } - }, { - key: "delete_statement", - value: function delete_statement(st, callbackFunction) { - var st0 = st instanceof Array ? st[0] : st; - var query = this.contextWhere(this.statementContext(st0)); - if (st instanceof Array) { - var stText = ''; - for (var i = 0; i < st.length; i++) stText += st[i] + '\n'; - query += 'DELETE DATA { ' + stText + ' }\n'; - } else { - query += 'DELETE DATA { ' + this.anonymize(st.subject) + ' ' + this.anonymize(st.predicate) + ' ' + this.anonymize(st.object) + ' ' + ' . }\n'; - } - this.fire(st0.graph.value, query, callbackFunction); - } - - /// ////////////////////// - - /** - * Requests a now or future action to refresh changes coming downstream - * This is designed to allow the system to re-request the server version, - * when a websocket has pinged to say there are changes. - * If the websocket, by contrast, has sent a patch, then this may not be necessary. - * - * @param doc - * @param action - */ - }, { - key: "requestDownstreamAction", - value: function requestDownstreamAction(doc, action) { - var control = this.patchControlFor(doc); - if (!control.pendingUpstream) { - action(doc); - } else { - if (control.downstreamAction) { - if ('' + control.downstreamAction !== '' + action) { - // Kludge compare - throw new Error("Can't wait for > 1 different downstream actions"); - } - } else { - control.downstreamAction = action; - } - } - } - - /** - * We want to start counting websocket notifications - * to distinguish the ones from others from our own. - */ - }, { - key: "clearUpstreamCount", - value: function clearUpstreamCount(doc) { - var control = this.patchControlFor(doc); - control.upstreamCount = 0; - } - }, { - key: "getUpdatesVia", - value: function getUpdatesVia(doc) { - var linkHeaders = this.store.fetcher.getHeader(doc, 'updates-via'); - if (!linkHeaders || !linkHeaders.length) return null; - return linkHeaders[0].trim(); - } - }, { - key: "addDownstreamChangeListener", - value: function addDownstreamChangeListener(doc, listener) { - var _this2 = this; - var control = this.patchControlFor(doc); - if (!control.downstreamChangeListeners) { - control.downstreamChangeListeners = []; - } - control.downstreamChangeListeners.push(listener); - this.setRefreshHandler(doc, function (doc) { - _this2.reloadAndSync(doc); - }); - } - }, { - key: "reloadAndSync", - value: function reloadAndSync(doc) { - var control = this.patchControlFor(doc); - var updater = this; - if (control.reloading) { - // console.log(' Already reloading - note this load may be out of date') - control.outOfDate = true; - return; // once only needed @@ Not true, has changed again - } - - control.reloading = true; - var retryTimeout = 1000; // ms - var tryReload = function tryReload() { - // console.log('try reload - timeout = ' + retryTimeout) - updater.reload(updater.store, doc, function (ok, message, response) { - if (ok) { - if (control.downstreamChangeListeners) { - for (var i = 0; i < control.downstreamChangeListeners.length; i++) { - // console.log(' Calling downstream listener ' + i) - control.downstreamChangeListeners[i](); - } - } - control.reloading = false; - if (control.outOfDate) { - // console.log(' Extra reload because of extra update.') - control.outOfDate = false; - tryReload(); - } - } else { - control.reloading = false; - if (response.status === 0) { - // console.log('Network error refreshing the data. Retrying in ' + - // retryTimeout / 1000) - control.reloading = true; - retryTimeout = retryTimeout * 2; - setTimeout(tryReload, retryTimeout); - } else { - // console.log('Error ' + (response as Response).status + 'refreshing the data:' + - // message + '. Stopped' + doc) - } - } - }); - }; - tryReload(); - } - - /** - * Sets up websocket to listen on - * - * There is coordination between upstream changes and downstream ones - * so that a reload is not done in the middle of an upstream patch. - * If you use this API then you get called when a change happens, and you - * have to reload the file yourself, and then refresh the UI. - * Alternative is addDownstreamChangeListener(), where you do not - * have to do the reload yourself. Do mot mix them. - * - * kb contains the HTTP metadata from previous operations - * - * @param doc - * @param handler - * - * @returns {boolean} - */ - }, { - key: "setRefreshHandler", - value: function setRefreshHandler(doc, handler) { - var wssURI = this.getUpdatesVia(doc); // relative - // var kb = this.store - var theHandler = handler; - var self = this; - var updater = this; - var retryTimeout = 1500; // *2 will be 3 Seconds, 6, 12, etc - var retries = 0; - if (!wssURI) { - // console.log('Server does not support live updates through Updates-Via :-(') - return false; - } - wssURI = (0,_uri__WEBPACK_IMPORTED_MODULE_10__.join)(wssURI, doc.value); - var validWssURI = wssURI.replace(/^http:/, 'ws:').replace(/^https:/, 'wss:'); - // console.log('Web socket URI ' + wssURI) - - var openWebsocket = function openWebsocket() { - // From https://github.com/solid/solid-spec#live-updates - var socket; - if (typeof WebSocket !== 'undefined') { - socket = new WebSocket(validWssURI); - } else if (typeof window !== 'undefined' && window.WebSocket) { - socket = window.WebSocket(validWssURI); - } else { - // console.log('Live update disabled, as WebSocket not supported by platform :-(') - return; - } - socket.onopen = function () { - // console.log(' websocket open') - retryTimeout = 1500; // reset timeout to fast on success - this.send('sub ' + doc.value); - if (retries) { - // console.log('Web socket has been down, better check for any news.') - updater.requestDownstreamAction(doc, theHandler); - } - }; - var control = self.patchControlFor(doc); - control.upstreamCount = 0; - socket.onerror = function onerror(err) { - // console.log('Error on Websocket:', err) - }; - - // https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent - // - // 1000 CLOSE_NORMAL Normal closure; the connection successfully completed whatever purpose for which it was created. - // 1001 CLOSE_GOING_AWAY The endpoint is going away, either - // because of a server failure or because the browser is navigating away from the page that opened the connection. - // 1002 CLOSE_PROTOCOL_ERROR The endpoint is terminating the connection due to a protocol error. - // 1003 CLOSE_UNSUPPORTED The connection is being terminated because the endpoint - // received data of a type it cannot accept (for example, a text-only endpoint received binary data). - // 1004 Reserved. A meaning might be defined in the future. - // 1005 CLOSE_NO_STATUS Reserved. Indicates that no status code was provided even though one was expected. - // 1006 CLOSE_ABNORMAL Reserved. Used to indicate that a connection was closed abnormally ( - // - // - socket.onclose = function (event) { - // console.log('*** Websocket closed with code ' + event.code + - // ", reason '" + event.reason + "' clean = " + event.wasClean) - retryTimeout *= 2; - retries += 1; - // console.log('Retrying in ' + retryTimeout + 'ms') // (ask user?) - setTimeout(function () { - // console.log('Trying websocket again') - openWebsocket(); - }, retryTimeout); - }; - socket.onmessage = function (msg) { - if (msg.data && msg.data.slice(0, 3) === 'pub') { - if ('upstreamCount' in control) { - control.upstreamCount -= 1; - if (control.upstreamCount >= 0) { - // console.log('just an echo: ' + control.upstreamCount) - return; // Just an echo - } - } - // console.log('Assume a real downstream change: ' + control.upstreamCount + ' -> 0') - control.upstreamCount = 0; - self.requestDownstreamAction(doc, theHandler); - } - }; - }; // openWebsocket - openWebsocket(); - return true; - } - - /** - * This high-level function updates the local store iff the web is changed successfully. - * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause). - * The `why` property of each statement must be the give the web document to be updated. - * The statements to be deleted and inserted may span more than one web document. - * @param deletions - Statement or statements to be deleted. - * @param insertions - Statement or statements to be inserted. - * @returns a promise - */ - }, { - key: "updateMany", - value: function updateMany(deletions) { - var insertions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; - var docs = deletions.concat(insertions).map(function (st) { - return st.why; - }); - var thisUpdater = this; - var uniqueDocs = []; - docs.forEach(function (doc) { - if (!uniqueDocs.find(function (uniqueDoc) { - return uniqueDoc.equals(doc); - })) uniqueDocs.push(doc); - }); - var updates = uniqueDocs.map(function (doc) { - return thisUpdater.update(deletions.filter(function (st) { - return st.why.equals(doc); - }), insertions.filter(function (st) { - return st.why.equals(doc); - })); - }); - if (updates.length > 1) { - // console.log(`@@ updateMany to ${updates.length}: ${uniqueDocs}`) - } - return Promise.all(updates); - } - - /** - * This high-level function updates the local store iff the web is changed successfully. - * Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause). - * The `why` property of each statement must be the same and give the web document to be updated. - * @param deletions - Statement or statements to be deleted. - * @param insertions - Statement or statements to be inserted. - * @param callback - called as callbackFunction(uri, success, errorbody) - * OR returns a promise - * @param options - Options for the fetch call - */ - }, { - key: "update", - value: function update(deletions, insertions, callback, secondTry) { - var _this3 = this; - var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; - if (!callback) { - var thisUpdater = this; - return new Promise(function (resolve, reject) { - // Promise version - thisUpdater.update(deletions, insertions, function (uri, ok, errorBody) { - if (!ok) { - reject(new Error(errorBody)); - } else { - resolve(); - } - }, secondTry, options); // callbackFunction - }); // promise - } // if - - try { - var kb = this.store; - var ds = !deletions ? [] : (0,_utils_terms__WEBPACK_IMPORTED_MODULE_11__.isStore)(deletions) ? deletions.statements : deletions instanceof Array ? deletions : [deletions]; - var is = !insertions ? [] : (0,_utils_terms__WEBPACK_IMPORTED_MODULE_11__.isStore)(insertions) ? insertions.statements : insertions instanceof Array ? insertions : [insertions]; - if (!(ds instanceof Array)) { - throw new Error('Type Error ' + (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(ds) + ': ' + ds); - } - if (!(is instanceof Array)) { - throw new Error('Type Error ' + (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(is) + ': ' + is); - } - if (ds.length === 0 && is.length === 0) { - return callback(null, true); // success -- nothing needed to be done. - } - - var doc = ds.length ? ds[0].graph : is[0].graph; - if (!doc) { - var _message2 = 'Error patching: statement does not specify which document to patch:' + ds[0] + ', ' + is[0]; - // console.log(message) - throw new Error(_message2); - } - if (doc.termType !== 'NamedNode') { - var _message3 = 'Error patching: document not a NamedNode:' + ds[0] + ', ' + is[0]; - // console.log(message) - throw new Error(_message3); - } - var control = this.patchControlFor(doc); - var startTime = Date.now(); - var props = ['subject', 'predicate', 'object', 'why']; - var verbs = ['insert', 'delete']; - var clauses = { - 'delete': ds, - 'insert': is - }; - verbs.map(function (verb) { - clauses[verb].map(function (st) { - if (!doc.equals(st.graph)) { - throw new Error('update: destination ' + doc + ' inconsistent with delete quad ' + st.graph); - } - props.map(function (prop) { - if (typeof st[prop] === 'undefined') { - throw new Error('update: undefined ' + prop + ' of statement.'); - } - }); - }); - }); - var protocol = this.editable(doc.value, kb); - if (protocol === false) { - throw new Error('Update: Can\'t make changes in uneditable ' + doc); - } - if (protocol === undefined) { - // Not enough metadata - if (secondTry) { - throw new Error('Update: Loaded ' + doc + "but stil can't figure out what editing protcol it supports."); - } - // console.log(`Update: have not loaded ${doc} before: loading now...`); - this.store.fetcher.load(doc).then(function (response) { - _this3.update(deletions, insertions, callback, true, options); - }, function (err) { - if (err.response.status === 404) { - // nonexistent files are fine - _this3.update(deletions, insertions, callback, true, options); - } else { - throw new Error("Update: Can't get updatability status ".concat(doc, " before patching: ").concat(err)); - } - }); - return; - } else if (protocol.indexOf('SPARQL') >= 0) { - var bnodes = []; - // change ReadOnly type to Mutable type - - if (ds.length) bnodes = this.statementArrayBnodes(ds); - if (is.length) bnodes = bnodes.concat(this.statementArrayBnodes(is)); - var context = this.bnodeContext(bnodes, doc); - var whereClause = this.contextWhere(context); - var query = ''; - if (whereClause.length) { - // Is there a WHERE clause? - if (ds.length) { - query += 'DELETE { '; - for (var i = 0; i < ds.length; i++) { - query += this.anonymizeNT(ds[i]) + '\n'; - } - query += ' }\n'; - } - if (is.length) { - query += 'INSERT { '; - for (var _i5 = 0; _i5 < is.length; _i5++) { - query += this.anonymizeNT(is[_i5]) + '\n'; - } - query += ' }\n'; - } - query += whereClause; - } else { - // no where clause - if (ds.length) { - query += 'DELETE DATA { '; - for (var _i6 = 0; _i6 < ds.length; _i6++) { - query += this.anonymizeNT(ds[_i6]) + '\n'; - } - query += ' } \n'; - } - if (is.length) { - if (ds.length) query += ' ; '; - query += 'INSERT DATA { '; - for (var _i7 = 0; _i7 < is.length; _i7++) { - query += this.nTriples(is[_i7]) + '\n'; - } - query += ' }\n'; - } - } - // Track pending upstream patches until they have finished their callbackFunction - control.pendingUpstream = control.pendingUpstream ? control.pendingUpstream + 1 : 1; - if ('upstreamCount' in control) { - control.upstreamCount += 1; // count changes we originated ourselves - // console.log('upstream count up to : ' + control.upstreamCount) - } - - this.fire(doc.value, query, function (uri, success, body, response) { - response.elapsedTimeMs = Date.now() - startTime; - /* console.log(' UpdateManager: Return ' + - (success ? 'success ' : 'FAILURE ') + (response as Response).status + - ' elapsed ' + (response as any).elapsedTimeMs + 'ms') - */ - if (success) { - try { - kb.remove(ds); - } catch (e) { - success = false; - body = 'Remote Ok BUT error deleting ' + ds.length + ' from store!!! ' + e; - } // Add in any case -- help recover from weirdness?? - for (var _i8 = 0; _i8 < is.length; _i8++) { - kb.add(is[_i8].subject, is[_i8].predicate, is[_i8].object, doc); - } - } - callback(uri, success, body, response); - control.pendingUpstream -= 1; - // When upstream patches have been sent, reload state if downstream waiting - if (control.pendingUpstream === 0 && control.downstreamAction) { - var downstreamAction = control.downstreamAction; - delete control.downstreamAction; - // console.log('delayed downstream action:') - downstreamAction(doc); - } - }, options); - } else if (protocol.indexOf('DAV') >= 0) { - this.updateDav(doc, ds, is, callback, options); - } else { - if (protocol.indexOf('LOCALFILE') >= 0) { - try { - this.updateLocalFile(doc, ds, is, callback, options); - } catch (e) { - callback(doc.value, false, 'Exception trying to write back file <' + doc.value + '>\n' - // + tabulator.Util.stackString(e)) - ); - } - } else { - throw new Error("Unhandled edit method: '" + protocol + "' for " + doc); - } - } - } catch (e) { - callback(undefined, false, 'Exception in update: ' + e + '\n' + _utils_js__WEBPACK_IMPORTED_MODULE_12__.stackString(e)); - } - } - }, { - key: "updateDav", - value: function updateDav(doc, ds, is, callbackFunction) { - var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; - var kb = this.store; - // The code below is derived from Kenny's UpdateCenter.js - var request = kb.any(doc, this.ns.link('request')); - if (!request) { - throw new Error('No record of our HTTP GET request for document: ' + doc); - } // should not happen - var response = kb.any(request, this.ns.link('response')); - if (!response) { - return null; // throw "No record HTTP GET response for document: "+doc - } - - var contentType = kb.the(response, this.ns.httph('content-type')).value; - - // prepare contents of revised document - var newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy! - for (var i = 0; i < ds.length; i++) { - _utils_js__WEBPACK_IMPORTED_MODULE_12__.RDFArrayRemove(newSts, ds[i]); - } - for (var _i9 = 0; _i9 < is.length; _i9++) { - newSts.push(is[_i9]); - } - var documentString = this.serialize(doc.value, newSts, contentType); - - // Write the new version back - var candidateTarget = kb.the(response, this.ns.httph('content-location')); - var targetURI; - if (candidateTarget) { - targetURI = (0,_uri__WEBPACK_IMPORTED_MODULE_10__.join)(candidateTarget.value, targetURI); - } - options.contentType = contentType; - options.noMeta = true; - options.body = documentString; - return kb.fetcher.webOperation('PUT', targetURI, options).then(function (response) { - if (!response.ok) { - throw new Error(response.error); - } - for (var _i10 = 0; _i10 < ds.length; _i10++) { - kb.remove(ds[_i10]); - } - for (var _i11 = 0; _i11 < is.length; _i11++) { - kb.add(is[_i11].subject, is[_i11].predicate, is[_i11].object, doc); - } - callbackFunction(doc.value, response.ok, response.responseText, response); - }).catch(function (err) { - callbackFunction(doc.value, false, err.message, err); - }); - } - - /** - * Likely deprecated, since this lib no longer deals with browser extension - * - * @param doc - * @param ds - * @param is - * @param callbackFunction - * @param options - */ - }, { - key: "updateLocalFile", - value: function updateLocalFile(doc, ds, is, callbackFunction) { - var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; - var kb = this.store; - // console.log('Writing back to local file\n') - - // prepare contents of revised document - var newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice(); // copy! - - for (var i = 0; i < ds.length; i++) { - _utils_js__WEBPACK_IMPORTED_MODULE_12__.RDFArrayRemove(newSts, ds[i]); - } - for (var _i12 = 0; _i12 < is.length; _i12++) { - newSts.push(is[_i12]); - } - // serialize to the appropriate format - var dot = doc.value.lastIndexOf('.'); - if (dot < 1) { - throw new Error('Rewriting file: No filename extension: ' + doc.value); - } - var ext = doc.value.slice(dot + 1); - var contentType = _fetcher__WEBPACK_IMPORTED_MODULE_7__["default"].CONTENT_TYPE_BY_EXT[ext]; - if (!contentType) { - throw new Error('File extension .' + ext + ' not supported for data write'); - } - options.body = this.serialize(doc.value, newSts, contentType); - options.contentType = contentType; - kb.fetcher.webOperation('PUT', doc.value, options).then(function (response) { - if (!response.ok) return callbackFunction(doc.value, false, response.error); - for (var _i13 = 0; _i13 < ds.length; _i13++) { - kb.remove(ds[_i13]); - } - for (var _i14 = 0; _i14 < is.length; _i14++) { - kb.add(is[_i14].subject, is[_i14].predicate, is[_i14].object, doc); - } - callbackFunction(doc.value, true, ''); // success! - }); - } - - /** - * @throws {Error} On unsupported content type - * - * @returns {string} - */ - }, { - key: "serialize", - value: function serialize(uri, data, contentType) { - var kb = this.store; - var documentString; - if (typeof data === 'string') { - return data; - } - - // serialize to the appropriate format - var sz = (0,_serializer__WEBPACK_IMPORTED_MODULE_13__["default"])(kb); - sz.suggestNamespaces(kb.namespaces); - sz.setBase(uri); - switch (contentType) { - case 'text/xml': - case 'application/rdf+xml': - documentString = sz.statementsToXML(data); - break; - case 'text/n3': - case 'text/turtle': - case 'application/x-turtle': // Legacy - case 'application/n3': - // Legacy - documentString = sz.statementsToN3(data); - break; - default: - throw new Error('Content-type ' + contentType + ' not supported for data serialization'); - } - return documentString; - } - - /** - * This is suitable for an initial creation of a document. - */ - }, { - key: "put", - value: function put(doc, data, contentType, callback) { - var _this4 = this; - var kb = this.store; - var documentString; - return Promise.resolve().then(function () { - documentString = _this4.serialize(doc.value, data, contentType); - return kb.fetcher.webOperation('PUT', doc.value, { - contentType: contentType, - body: documentString - }); - }).then(function (response) { - if (!response.ok) { - return callback(doc.value, response.ok, response.error, response); - } - delete kb.fetcher.nonexistent[doc.value]; - delete kb.fetcher.requested[doc.value]; // @@ could this mess with the requested state machine? if a fetch is in progress - - if (typeof data !== 'string') { - data.map(function (st) { - kb.addStatement(st); - }); - } - callback(doc.value, response.ok, '', response); - }).catch(function (err) { - callback(doc.value, false, err.message); - }); - } - - /** - * Reloads a document. - * - * Fast and cheap, no metadata. Measure times for the document. - * Load it provisionally. - * Don't delete the statements before the load, or it will leave a broken - * document in the meantime. - * - * @param kb - * @param doc {RDFlibNamedNode} - * @param callbackFunction - */ - }, { - key: "reload", - value: function reload(kb, doc, callbackFunction) { - var startTime = Date.now(); - // force sets no-cache and - var options = { - force: true, - noMeta: true, - clearPreviousData: true - }; - kb.fetcher.nowOrWhenFetched(doc.value, options, function (ok, body, response) { - if (!ok) { - // console.log(' ERROR reloading data: ' + body) - callbackFunction(false, 'Error reloading data: ' + body, response); - //@ts-ignore Where does onErrorWasCalled come from? - } else if (response.onErrorWasCalled || response.status !== 200) { - // console.log(' Non-HTTP error reloading data! onErrorWasCalled=' + - //@ts-ignore Where does onErrorWasCalled come from? - // response.onErrorWasCalled + ' status: ' + response.status) - callbackFunction(false, 'Non-HTTP error reloading data: ' + body, response); - } else { - var elapsedTimeMs = Date.now() - startTime; - if (!doc.reloadTimeTotal) doc.reloadTimeTotal = 0; - if (!doc.reloadTimeCount) doc.reloadTimeCount = 0; - doc.reloadTimeTotal += elapsedTimeMs; - doc.reloadTimeCount += 1; - - // console.log(' Fetch took ' + elapsedTimeMs + 'ms, av. of ' + - // doc.reloadTimeCount + ' = ' + - // (doc.reloadTimeTotal / doc.reloadTimeCount) + 'ms.') - - callbackFunction(true); - } - }); - } - }]); - return UpdateManager; -}(); - - -/***/ }), - -/***/ "../rdflib/esm/updates-via.js": -/*!************************************!*\ - !*** ../rdflib/esm/updates-via.js ***! - \************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "UpdatesSocket": () => (/* binding */ UpdatesSocket), -/* harmony export */ "UpdatesVia": () => (/* binding */ UpdatesVia) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./factories/rdflib-data-factory */ "../rdflib/esm/factories/rdflib-data-factory.js"); - - -/* - * Updates-Via - */ - -var UpdatesSocket = /*#__PURE__*/function () { - function UpdatesSocket(parent, via) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, UpdatesSocket); - this.parent = parent; - this.via = via; - this.connected = false; - this.pending = {}; - this.subscribed = {}; - this.socket = {}; - try { - this.socket = new WebSocket(via); - this.socket.onopen = this.onOpen; - this.socket.onclose = this.onClose; - this.socket.onmessage = this.onMessage; - this.socket.onerror = this.onError; - } catch (error) { - this.onError(error); - } - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(UpdatesSocket, [{ - key: "_decode", - value: function _decode(q) { - var elt; - var i; - var k; - var r; - var ref; - var ref1; - var v; - r = {}; - ref = function () { - var j, len, ref, results; - ref = q.split('&'); - results = []; - for (j = 0, len = ref.length; j < len; j++) { - elt = ref[j]; - results.push(elt.split('=')); - } - return results; - }(); - for (i in ref) { - elt = ref[i]; - ref1 = [decodeURIComponent(elt[0]), decodeURIComponent(elt[1])]; - k = ref1[0]; - v = ref1[1]; - if (r[k] == null) { - r[k] = []; - } - r[k].push(v); - } - return r; - } - }, { - key: "_send", - value: function _send(method, uri, data) { - var base, message; - message = [method, uri, data].join(' '); - return typeof (base = this.socket).send === 'function' ? base.send(message) : void 0; - } - }, { - key: "_subscribe", - value: function _subscribe(uri) { - this._send('sub', uri, ''); - this.subscribed[uri] = true; - return this.subscribed[uri]; - } - }, { - key: "onClose", - value: function onClose(e) { - var uri; - this.connected = false; - for (uri in this.subscribed) { - this.pending[uri] = true; - } - this.subscribed = {}; - return this.subscribed; - } - }, { - key: "onError", - value: function onError(e) { - throw new Error('onError' + e); - } - }, { - key: "onMessage", - value: function onMessage(e) { - var base, message; - message = e.data.split(' '); - if (message[0] === 'ping') { - return typeof (base = this.socket).send === 'function' ? base.send('pong ' + message.slice(1).join(' ')) : void 0; - } else if (message[0] === 'pub') { - return this.parent.onUpdate(message[1], this._decode(message[2])); - } - } - }, { - key: "onOpen", - value: function onOpen(e) { - var results, uri; - this.connected = true; - results = []; - for (uri in this.pending) { - delete this.pending[uri]; - results.push(this._subscribe(uri)); - } - return results; - } - }, { - key: "subscribe", - value: function subscribe(uri) { - if (this.connected) { - return this._subscribe(uri); - } else { - this.pending[uri] = true; - return this.pending[uri]; - } - } - }]); - return UpdatesSocket; -}(); -var UpdatesVia = /*#__PURE__*/function () { - function UpdatesVia(fetcher) { - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, UpdatesVia); - this.fetcher = fetcher; - this.graph = {}; - this.via = {}; - this.fetcher.addCallback('headers', this.onHeaders); - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(UpdatesVia, [{ - key: "onHeaders", - value: function onHeaders(d) { - var etag, uri, via; - if (d.headers == null) { - return true; - } - if (typeof WebSocket === 'undefined' || WebSocket === null) { - return true; - } - etag = d.headers['etag']; - via = d.headers['updates-via']; - uri = d.uri; - if (etag && via) { - this.graph[uri] = { - etag: etag, - via: via - }; - this.register(via, uri); - } - return true; - } - }, { - key: "onUpdate", - value: function onUpdate(uri, d) { - return this.fetcher.refresh(_factories_rdflib_data_factory__WEBPACK_IMPORTED_MODULE_2__["default"].namedNode(uri)); - } - }, { - key: "register", - value: function register(via, uri) { - if (this.via[via] == null) { - this.via[via] = new UpdatesSocket(this, via); - } - return this.via[via].subscribe(uri); - } - }]); - return UpdatesVia; -}(); - -/***/ }), - -/***/ "../rdflib/esm/uri.js": -/*!****************************!*\ - !*** ../rdflib/esm/uri.js ***! - \****************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "docpart": () => (/* binding */ docpart), -/* harmony export */ "document": () => (/* binding */ document), -/* harmony export */ "hostpart": () => (/* binding */ hostpart), -/* harmony export */ "join": () => (/* binding */ join), -/* harmony export */ "protocol": () => (/* binding */ protocol), -/* harmony export */ "refTo": () => (/* binding */ refTo) -/* harmony export */ }); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); -/* - * Implements URI-specific functions - * - * See RFC 2386 - * - * See also: - * http://www.w3.org/2005/10/ajaw/uri.js - * http://www.w3.org/2000/10/swap/uripath.py - * - */ -var alert = alert || console.log; - - -/** - * Gets the document part of an URI - * @param uri The URI - */ -function docpart(uri) { - var i; - i = uri.indexOf('#'); - if (i < 0) { - return uri; - } else { - return uri.slice(0, i); - } -} - -/** - * Gets the document part of an URI as a named node - * @param x - The URI - */ -function document(x) { - return new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"](docpart(x)); -} - -/** - * Gets the hostname in an URI - * @param u The URI - */ -function hostpart(u) { - var m = /[^\/]*\/\/([^\/]*)\//.exec(u); - if (m) { - return m[1]; - } else { - return ''; - } -} - -/** - * Joins an URI with a base - * @param given - The relative part - * @param base - The base URI - */ -function join(given, base) { - var baseColon, baseScheme, baseSingle; - var colon, lastSlash, path; - var baseHash = base.indexOf('#'); - if (baseHash > 0) { - base = base.slice(0, baseHash); - } - if (given.length === 0) { - return base; - } - if (given.indexOf('#') === 0) { - return base + given; - } - colon = given.indexOf(':'); - if (colon >= 0) { - return given; - } - baseColon = base.indexOf(':'); - if (base.length === 0) { - return given; - } - if (baseColon < 0) { - alert('Invalid base: ' + base + ' in join with given: ' + given); - return given; - } - baseScheme = base.slice(0, +baseColon + 1 || 9e9); - if (given.indexOf('//') === 0) { - return baseScheme + given; - } - if (base.indexOf('//', baseColon) === baseColon + 1) { - baseSingle = base.indexOf('/', baseColon + 3); - if (baseSingle < 0) { - if (base.length - baseColon - 3 > 0) { - return base + '/' + given; - } else { - return baseScheme + given; - } - } - } else { - baseSingle = base.indexOf('/', baseColon + 1); - if (baseSingle < 0) { - if (base.length - baseColon - 1 > 0) { - return base + '/' + given; - } else { - return baseScheme + given; - } - } - } - if (given.indexOf('/') === 0) { - return base.slice(0, baseSingle) + given; - } - path = base.slice(baseSingle); - lastSlash = path.lastIndexOf('/'); - if (lastSlash < 0) { - return baseScheme + given; - } - if (lastSlash >= 0 && lastSlash < path.length - 1) { - path = path.slice(0, +lastSlash + 1 || 9e9); - } - path += given; - while (path.match(/[^\/]*\/\.\.\//)) { - path = path.replace(/[^\/]*\/\.\.\//, ''); - } - path = path.replace(/\.\//g, ''); - path = path.replace(/\/\.$/, '/'); - return base.slice(0, baseSingle) + path; -} - -/** - * Gets the protocol part of an URI - * @param uri The URI - */ -function protocol(uri) { - var i = uri.indexOf(':'); - if (i < 0) { - return null; - } else { - return uri.slice(0, i); - } -} - -/** - * Gets a relative uri - * @param base The base URI - * @param uri The absolute URI - */ -function refTo(base, uri) { - var c, i, k, l, len, len1, n, o, p, q, ref, ref1, s; - var commonHost = new RegExp('^[-_a-zA-Z0-9.]+:(//[^/]*)?/[^/]*$'); - if (!base) { - return uri; - } - if (base === uri) { - return ''; - } - for (i = o = 0, len = uri.length; o < len; i = ++o) { - var _c = uri[i]; - if (_c !== base[i]) { - break; - } - } - if (base.slice(0, i).match(commonHost)) { - k = uri.indexOf('//'); - if (k < 0) { - k = -2; - } - l = uri.indexOf('/', k + 2); - if (uri[l + 1] !== '/' && base[l + 1] !== '/' && uri.slice(0, l) === base.slice(0, l)) { - return uri.slice(l); - } - } - if (uri[i] === '#' && base.length === i) { - return uri.slice(i); - } - while (i > 0 && uri[i - 1] !== '/') { - i--; - } - if (i < 3) { - return uri; - } - if (base.indexOf('//', i - 2) > 0 || uri.indexOf('//', i - 2) > 0) { - return uri; - } - if (base.indexOf(':', i) > 0) { - return uri; - } - n = 0; - ref = base.slice(i); - for (p = 0, len1 = ref.length; p < len1; p++) { - c = ref[p]; - if (c === '/') { - n++; - } - } - if (n === 0 && i < uri.length && uri[i] === '#') { - return './' + uri.slice(i); - } - if (n === 0 && i === uri.length) { - return './'; - } - s = ''; - if (n > 0) { - for (q = 1, ref1 = n; ref1 >= 1 ? q <= ref1 : q >= ref1; ref1 >= 1 ? ++q : --q) { - s += '../'; - } - } - return s + uri.slice(i); -} - -/***/ }), - -/***/ "../rdflib/esm/utils-js.js": -/*!*********************************!*\ - !*** ../rdflib/esm/utils-js.js ***! - \*********************************/ -/***/ ((module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "DOMParserFactory": () => (/* binding */ DOMParserFactory), -/* harmony export */ "RDFArrayRemove": () => (/* binding */ RDFArrayRemove), -/* harmony export */ "callbackify": () => (/* binding */ callbackify), -/* harmony export */ "domToString": () => (/* binding */ domToString), -/* harmony export */ "dtstamp": () => (/* binding */ dtstamp), -/* harmony export */ "dumpNode": () => (/* binding */ dumpNode), -/* harmony export */ "heavyCompare": () => (/* binding */ heavyCompare), -/* harmony export */ "heavyCompareSPO": () => (/* binding */ heavyCompareSPO), -/* harmony export */ "linkRelationProperty": () => (/* binding */ linkRelationProperty), -/* harmony export */ "log": () => (/* reexport safe */ _log__WEBPACK_IMPORTED_MODULE_0__["default"]), -/* harmony export */ "mediaTypeClass": () => (/* binding */ mediaTypeClass), -/* harmony export */ "output": () => (/* binding */ output), -/* harmony export */ "parseXML": () => (/* binding */ parseXML), -/* harmony export */ "stackString": () => (/* binding */ stackString), -/* harmony export */ "string": () => (/* binding */ string), -/* harmony export */ "string_startswith": () => (/* binding */ string_startswith), -/* harmony export */ "uri": () => (/* reexport module object */ _uri__WEBPACK_IMPORTED_MODULE_1__) -/* harmony export */ }); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); -/* harmony import */ var _xmldom_xmldom__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @xmldom/xmldom */ "../rdflib/node_modules/@xmldom/xmldom/lib/index.js"); -/* module decorator */ module = __webpack_require__.hmd(module); -/** - * Utility functions for $rdf - * @module util - */ - - - - -var string = { - template: stringTemplate -}; - -function mediaTypeClass(mediaType) { - mediaType = mediaType.split(';')[0].trim(); // remove media type parameters - return new _named_node__WEBPACK_IMPORTED_MODULE_2__["default"]('http://www.w3.org/ns/iana/media-types/' + mediaType + '#Resource'); -} -function linkRelationProperty(relation) { - return new _named_node__WEBPACK_IMPORTED_MODULE_2__["default"]('http://www.w3.org/ns/iana/link-relations/relation#' + relation.trim()); -} - -/** - * Adds callback functionality to an object. - * Callback functions are indexed by a 'hook' string. - * They return true if they want to be called again. - * @method callbackify - * @param obj {Object} - * @param callbacks {Array} - */ -function callbackify(obj, callbacks) { - obj.callbacks = {}; - for (var x = callbacks.length - 1; x >= 0; x--) { - obj.callbacks[callbacks[x]] = []; - } - obj.addHook = function (hook) { - if (!obj.callbacks[hook]) { - obj.callbacks[hook] = []; - } - }; - obj.addCallback = function (hook, func) { - obj.callbacks[hook].push(func); - }; - obj.removeCallback = function (hook, funcName) { - for (var i = 0; i < obj.callbacks[hook].length; i++) { - if (obj.callbacks[hook][i].name === funcName) { - obj.callbacks[hook].splice(i, 1); - return true; - } - } - return false; - }; - obj.insertCallback = function (hook, func) { - obj.callbacks[hook].unshift(func); - }; - obj.fireCallbacks = function fireCallbacks(hook, args) { - var newCallbacks = []; - var replaceCallbacks = []; - var len = obj.callbacks[hook].length; - var x; - var callback; - - // log.info('!@$ Firing '+hook+' call back with length'+len) - for (x = len - 1; x >= 0; x--) { - // log.info('@@ Firing '+hook+' callback '+ obj.callbacks[hook][x]) - callback = obj.callbacks[hook][x]; - if (callback && callback.apply(obj, args)) { - newCallbacks.push(callback); - } - } - for (x = newCallbacks.length - 1; x >= 0; x--) { - replaceCallbacks.push(newCallbacks[x]); - } - for (x = len; x < obj.callbacks[hook].length; x++) { - replaceCallbacks.push(obj.callbacks[hook][x]); - } - obj.callbacks[hook] = replaceCallbacks; - }; -} - -/** - * Returns a DOM parser based on current runtime environment. - */ -function DOMParserFactory() { - if (window.DOMParser) { - return new _xmldom_xmldom__WEBPACK_IMPORTED_MODULE_3__.DOMParser(); - } else if (window.ActiveXObject) { - return new ActiveXObject('Microsoft.XMLDOM'); - } else { - return false; - } -} - -// From https://github.com/linkeddata/dokieli -function domToString(node, options) { - options = options || {}; - var selfClosing = []; - if (options && options.selfClosing) { - options.selfClosing.split(' ').forEach(function (n) { - selfClosing[n] = true; - }); - } - var skipAttributes = []; - if (options && options.skipAttributes) { - options.skipAttributes.split(' ').forEach(function (n) { - skipAttributes[n] = true; - }); - } - return dumpNode(node, options, selfClosing, skipAttributes); -} -function dumpNode(node, options, selfClosing, skipAttributes) { - var i; - var out = ''; - var noEsc = [false]; - if (typeof node.nodeType === 'undefined') return out; - if (node.nodeType === 1) { - if (node.hasAttribute('class') && options && options.classWithChildText && node.matches(options.classWithChildText.class)) { - out += node.querySelector(options.classWithChildText.element).textContent; - } else if (!(options && options.skipNodeWithClass && node.matches('.' + options.skipNodeWithClass))) { - var ename = node.nodeName.toLowerCase(); - out += '<' + ename; - var attrList = []; - for (i = node.attributes.length - 1; i >= 0; i--) { - var atn = node.attributes[i]; - if (skipAttributes && skipAttributes.length > 0 && skipAttributes[atn.name]) continue; - if (/^\d+$/.test(atn.name)) continue; - if (atn.name === 'class' && options && options.replaceClassItemWith && atn.value.split(' ').indexOf(options.replaceClassItemWith.source) > -1) { - var re = new RegExp(options.replaceClassItemWith.source, 'g'); - atn.value = atn.value.replace(re, options.replaceClassItemWith.target).trim(); - } - if (!(atn.name === 'class' && options && options.skipClassWithValue && options.skipClassWithValue === atn.value)) { - attrList.push(atn.name + '=\'' + atn.value.replace(/&/g, '&').replace(//g, '>').replace(/'/g, '"') + '\''); - } - } - if (attrList.length > 0) { - if (options && options.sortAttributes) { - attrList.sort(function (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()); - }); - } - out += ' ' + attrList.join(' '); - } - if (selfClosing && selfClosing.ename) { - out += ' />'; - } else { - out += '>'; - out += ename === 'html' ? '\n ' : ''; - noEsc.push(ename === 'style' || ename === 'script'); - for (i = 0; i < node.childNodes.length; i++) out += dumpNode(node.childNodes[i]); - noEsc.pop(); - out += ename === 'body' ? '' + '\n' : ''; - } - } - } else if (node.nodeType === 8) { - // FIXME: If comments are not tabbed in source, a new line is not prepended - out += ''; - } else if (node.nodeType === 3 || node.nodeType === 4) { - // XXX: Remove new lines which were added after DOM ready - var nl = node.nodeValue.replace(/\n+$/, ''); - out += noEsc[noEsc.length - 1] ? nl : nl.replace(/&/g, '&').replace(//g, '>'); - } else { - console.log('Warning; Cannot handle serialising nodes of type: ' + node.nodeType); - console.log(node); - } - return out; -} -function dtstamp() { - var now = new Date(); - var year = now.getYear() + 1900; - var month = now.getMonth() + 1; - var day = now.getDate(); - var hour = now.getUTCHours(); - var minute = now.getUTCMinutes(); - var second = now.getSeconds(); - if (month < 10) month = '0' + month; - if (day < 10) day = '0' + day; - if (hour < 10) hour = '0' + hour; - if (minute < 10) minute = '0' + minute; - if (second < 10) second = '0' + second; - return year + '-' + month + '-' + day + 'T' + hour + ':' + minute + ':' + second + 'Z'; -} - -/** - * Compares statements (heavy comparison for repeatable canonical ordering) - */ -function heavyCompare(x, y, g, uriMap) { - var nonBlank = function nonBlank(x) { - return x.termType === 'BlankNode' ? null : x; - }; - var signature = function signature(x) { - var lis = g.statementsMatching(x).map(function (st) { - return '' + nonBlank(st.subject) + ' ' + nonBlank(st.predicate) + ' ' + nonBlank(st.object); - }).concat(g.statementsMatching(undefined, undefined, x).map(function (st) { - return '' + nonBlank(st.subject) + ' ' + nonBlank(st.predicate) + ' ' + nonBlank(st.object); - })); - lis.sort(); - return lis.join('\n'); - }; - var comparison = Object.prototype.hasOwnProperty.call(g, "compareTerms") ? g.compareTerms(x, y) : x.compareTerm(y); - if (x.termType === 'BlankNode' && y.termType === 'BlankNode') { - if (comparison === 0) return 0; // Same - if (signature(x) > signature(y)) return +1; - if (signature(x) < signature(y)) return -1; - return comparison; // Too bad -- this order not canonical. - // throw "different bnodes indistinquishable for sorting" - } else { - if (uriMap && x.uri && y.uri) { - return (uriMap[x.uri] || x.uri).localeCompare(uriMap[y.uri] || y.uri); - } - return comparison; - } -} -function heavyCompareSPO(x, y, g, uriMap) { - return heavyCompare(x.subject, y.subject, g, uriMap) || heavyCompare(x.predicate, y.predicate, g, uriMap) || heavyCompare(x.object, y.object, g, uriMap); -} - -/** - * Defines a simple debugging function - * @method output - * @param o {String} - */ -function output(o) { - var k = document.createElement('div'); - k.textContent = o; - document.body.appendChild(k); -} - - -/** - * Returns a DOM from parsed XML. - */ -function parseXML(str, options) { - var dparser; - options = options || {}; - if ( true && module && module.exports) { - // Node.js - var dom = new _xmldom_xmldom__WEBPACK_IMPORTED_MODULE_3__.DOMParser().parseFromString(str, options.contentType || 'application/xhtml+xml'); - return dom; - } else { - if (typeof window !== 'undefined' && window.DOMParser) { - dparser = new window.DOMParser(); // seems to actually work - } else { - dparser = new _xmldom_xmldom__WEBPACK_IMPORTED_MODULE_3__.DOMParser(); // Doc says this works - } - } - - return dparser.parseFromString(str, 'application/xml'); -} - -/** - * Removes all statements equal to x from a - */ -function RDFArrayRemove(a, x) { - for (var i = 0; i < a.length; i++) { - // TODO: This used to be the following, which didnt always work..why - // if(a[i] === x) - if (a[i].subject.equals(x.subject) && a[i].predicate.equals(x.predicate) && a[i].object.equals(x.object) && a[i].why.equals(x.why)) { - a.splice(i, 1); - return; - } - } - throw new Error('RDFArrayRemove: Array did not contain ' + x + ' ' + x.why); -} -function string_startswith(str, pref) { - // missing library routines - return str.slice(0, pref.length) === pref; -} - -/** - * C++, python style %s -> subs - */ -function stringTemplate(base, subs) { - var baseA = base.split('%s'); - var result = ''; - for (var i = 0; i < subs.length; i++) { - subs[i] += ''; - result += baseA[i] + subs[i]; - } - return result + baseA.slice(subs.length).join(); -} - -// Stack dump on errors - to pass errors back - -function stackString(e) { - var str = '' + e + '\n'; - if (!e.stack) { - return str + 'No stack available.\n'; - } - var lines = e.stack.toString().split('\n'); - var toprint = []; - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; - if (line.indexOf('ecmaunit.js') > -1) { - // remove useless bit of traceback - break; - } - if (line.charAt(0) == '(') { - line = 'function' + line; - } - var chunks = line.split('@'); - toprint.push(chunks); - } - // toprint.reverse(); No - I prefer the latest at the top by the error message -tbl - - for (var i = 0; i < toprint.length; i++) { - str += ' ' + toprint[i][1] + '\n ' + toprint[i][0]; - } - return str; -} - -/***/ }), - -/***/ "../rdflib/esm/utils.js": -/*!******************************!*\ - !*** ../rdflib/esm/utils.js ***! - \******************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "AJAR_handleNewTerm": () => (/* binding */ AJAR_handleNewTerm), -/* harmony export */ "ArrayIndexOf": () => (/* binding */ ArrayIndexOf), -/* harmony export */ "appliedFactoryMethods": () => (/* binding */ appliedFactoryMethods), -/* harmony export */ "arrayToStatements": () => (/* binding */ arrayToStatements) -/* harmony export */ }); -/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./log */ "../rdflib/esm/log.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); -/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils-js */ "../rdflib/esm/utils-js.js"); - - - -/** RDF/JS spec Typeguards */ - -/** - * Loads ontologies of the data we load (this is the callback from the kb to - * the fetcher). - */ -function AJAR_handleNewTerm(kb, p, requestedBy) { - var sf = null; - if (typeof kb.fetcher !== 'undefined') { - sf = kb.fetcher; - } else { - return; - } - if (p.termType !== 'NamedNode') return; - var docuri = (0,_uri__WEBPACK_IMPORTED_MODULE_0__.docpart)(p.uri); - var fixuri; - if (p.uri.indexOf('#') < 0) { - // No hash - // @@ major hack for dbpedia Categories, which spread indefinitely - if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string_startswith)(p.uri, 'http://dbpedia.org/resource/Category:')) return; - - /* - if (string_startswith(p.uri, 'http://xmlns.com/foaf/0.1/')) { - fixuri = "http://dig.csail.mit.edu/2005/ajar/ajaw/test/foaf" - // should give HTTP 303 to ontology -- now is :-) - } else - */ - if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string_startswith)(p.uri, 'http://purl.org/dc/elements/1.1/') || (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string_startswith)(p.uri, 'http://purl.org/dc/terms/')) { - fixuri = 'http://dublincore.org/2005/06/13/dcq'; - // dc fetched multiple times - } else if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string_startswith)(p.uri, 'http://xmlns.com/wot/0.1/')) { - fixuri = 'http://xmlns.com/wot/0.1/index.rdf'; - } else if ((0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.string_startswith)(p.uri, 'http://web.resource.org/cc/')) { - // log.warn("creative commons links to html instead of rdf. doesn't seem to content-negotiate.") - fixuri = 'http://web.resource.org/cc/schema.rdf'; - } - } - if (fixuri) { - docuri = fixuri; - } - if (sf && sf.getState(docuri) !== 'unrequested') return; - if (fixuri) { - // only give warning once: else happens too often - _log__WEBPACK_IMPORTED_MODULE_2__["default"].warn('Assuming server still broken, faking redirect of <' + p.uri + '> to <' + docuri + '>'); - } - return sf.fetch(docuri, { - referringTerm: requestedBy - }); -} -var appliedFactoryMethods = ['blankNode', 'defaultGraph', 'literal', 'namedNode', 'quad', 'variable', 'supports']; -var rdf = { - first: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first', - rest: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest', - nil: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil' -}; - -/** - * Expands an array of Terms to a set of statements representing the rdf:list. - * @param rdfFactory - The factory to use - * @param subject - The iri of the first list item. - * @param data - The terms to expand into the list. - * @return The {data} as a set of statements. - */ -function arrayToStatements(rdfFactory, subject, data) { - var statements = []; - data.reduce(function (id, _listObj, i, listData) { - statements.push(rdfFactory.quad(id, rdfFactory.namedNode(rdf.first), listData[i])); - var nextNode; - if (i < listData.length - 1) { - nextNode = rdfFactory.blankNode(); - statements.push(rdfFactory.quad(id, rdfFactory.namedNode(rdf.rest), nextNode)); - } else { - statements.push(rdfFactory.quad(id, rdfFactory.namedNode(rdf.rest), rdfFactory.namedNode(rdf.nil))); - } - return nextNode; - }, subject); - return statements; -} -function ArrayIndexOf(arr, item) { - var i = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - var length = arr.length; - if (i < 0) i = length + i; - for (; i < length; i++) { - if (arr[i] === item) { - return i; - } - } - return -1; -} - -/***/ }), - -/***/ "../rdflib/esm/utils/default-graph-uri.js": -/*!************************************************!*\ - !*** ../rdflib/esm/utils/default-graph-uri.js ***! - \************************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "defaultGraphNode": () => (/* binding */ defaultGraphNode), -/* harmony export */ "defaultGraphURI": () => (/* binding */ defaultGraphURI) -/* harmony export */ }); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../named-node */ "../rdflib/esm/named-node.js"); -// Prevents circular dependencies between data-factory-internal and statement - - -var defaultGraphURI = 'chrome:theSession'; -var defaultGraphNode = new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"](defaultGraphURI); - -/***/ }), - -/***/ "../rdflib/esm/utils/termValue.js": -/*!****************************************!*\ - !*** ../rdflib/esm/utils/termValue.js ***! - \****************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "termValue": () => (/* binding */ termValue) -/* harmony export */ }); -/** Retrieve the value of a term, or self if already a string. */ -function termValue(node) { - if (typeof node === 'string') { - return node; - } - return node.value; -} - -/***/ }), - -/***/ "../rdflib/esm/utils/terms.js": -/*!************************************!*\ - !*** ../rdflib/esm/utils/terms.js ***! - \************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "isBlankNode": () => (/* binding */ isBlankNode), -/* harmony export */ "isCollection": () => (/* binding */ isCollection), -/* harmony export */ "isGraph": () => (/* binding */ isGraph), -/* harmony export */ "isLiteral": () => (/* binding */ isLiteral), -/* harmony export */ "isNamedNode": () => (/* binding */ isNamedNode), -/* harmony export */ "isPredicate": () => (/* binding */ isPredicate), -/* harmony export */ "isQuad": () => (/* binding */ isQuad), -/* harmony export */ "isRDFObject": () => (/* binding */ isRDFObject), -/* harmony export */ "isRDFlibObject": () => (/* binding */ isRDFlibObject), -/* harmony export */ "isRDFlibPredicate": () => (/* binding */ isRDFlibPredicate), -/* harmony export */ "isRDFlibSubject": () => (/* binding */ isRDFlibSubject), -/* harmony export */ "isStatement": () => (/* binding */ isStatement), -/* harmony export */ "isStore": () => (/* binding */ isStore), -/* harmony export */ "isSubject": () => (/* binding */ isSubject), -/* harmony export */ "isTerm": () => (/* binding */ isTerm), -/* harmony export */ "isVariable": () => (/* binding */ isVariable) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "../rdflib/node_modules/@babel/runtime/helpers/esm/typeof.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../types */ "../rdflib/esm/types.js"); - - -/** TypeGuard for RDFLib Statements */ -function isStatement(obj) { - return (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(obj) === 'object' && obj !== null && 'subject' in obj; -} - -/** TypeGuard for RDFlib Stores */ -function isStore(obj) { - return (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(obj) === 'object' && obj !== null && 'statements' in obj; -} - -/** TypeGuard for RDFLib Collections */ -function isCollection(obj) { - return isTerm(obj) && obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.CollectionTermType; -} - -/** TypeGuard for valid RDFlib Object types, also allows Collections, Graphs */ -function isRDFlibObject(obj) { - return obj && Object.prototype.hasOwnProperty.call(obj, 'termType') && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.NamedNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.VariableTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.BlankNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.CollectionTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.LiteralTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.GraphTermType); -} - -/** TypeGuard for valid RDFlib Subject types, same as Object as RDFLib symmetrical. -*/ -function isRDFlibSubject(obj) { - return obj && Object.prototype.hasOwnProperty.call(obj, 'termType') && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.NamedNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.VariableTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.BlankNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.CollectionTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.LiteralTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.GraphTermType); -} - -/** TypeGuard for valid RDF/JS spec Predicate types */ -function isRDFlibPredicate(obj) { - return isTerm(obj) && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.NamedNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.BlankNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.VariableTermType); -} - -/** TypeGuard for RDFLib Variables */ -function isVariable(obj) { - return isTerm(obj) && obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.VariableTermType; -} - -/** TypeGuard for RDF/JS spec Terms */ -function isTerm(obj) { - return (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(obj) === 'object' && obj !== null && 'termType' in obj; -} - -/** TypeGuard for RDF/JS spec Literals */ -function isLiteral(value) { - return value.termType === _types__WEBPACK_IMPORTED_MODULE_1__.LiteralTermType; -} - -/** TypeGuard for RDF/JS spec Quads */ -function isQuad(obj) { - return (0,_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__["default"])(obj) === "object" && obj !== null && 'subject' in obj && 'predicate' in obj && 'object' in obj; -} - -/** TypeGuard for RDF/JS spec NamedNodes */ -function isNamedNode(obj) { - return isTerm(obj) && obj.termType === 'NamedNode'; -} - -/** TypeGuard for RDF/JS spec BlankNodes */ -function isBlankNode(obj) { - return isTerm(obj) && 'termType' in obj && obj.termType === 'BlankNode'; -} - -/** TypeGuard for valid RDF/JS spec Subject types */ -function isSubject(obj) { - return isTerm(obj) && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.NamedNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.VariableTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.BlankNodeTermType); -} - -/** TypeGuard for valid RDF/JS spec Predicate types */ -function isPredicate(obj) { - return isTerm(obj) && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.NamedNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.VariableTermType); -} - -/** TypeGuard for valid RDF/JS spec Object types */ -function isRDFObject(obj) { - return isTerm(obj) && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.NamedNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.VariableTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.BlankNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.LiteralTermType); -} - -/** TypeGuard for valid RDF/JS Graph types */ -function isGraph(obj) { - return isTerm(obj) && (obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.NamedNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.VariableTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.BlankNodeTermType || obj.termType === _types__WEBPACK_IMPORTED_MODULE_1__.DefaultGraphTermType); -} - -/***/ }), - -/***/ "../rdflib/esm/variable.js": -/*!*********************************!*\ - !*** ../rdflib/esm/variable.js ***! - \*********************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (/* binding */ Variable) -/* harmony export */ }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "../rdflib/node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "../rdflib/node_modules/@babel/runtime/helpers/esm/createClass.js"); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "../rdflib/node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "../rdflib/node_modules/@babel/runtime/helpers/esm/inherits.js"); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "../rdflib/node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "../rdflib/node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "../rdflib/node_modules/@babel/runtime/helpers/esm/defineProperty.js"); -/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./class-order */ "../rdflib/esm/class-order.js"); -/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./node-internal */ "../rdflib/esm/node-internal.js"); -/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "../rdflib/esm/types.js"); -/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./uri */ "../rdflib/esm/uri.js"); - - - - - - - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - - - - -/** -* Variables are placeholders used in patterns to be matched. -* In cwm they are symbols which are the formula's list of quantified variables. -* In sparql they are not visibly URIs. Here we compromise, by having -* a common special base URI for variables. Their names are uris, -* but the ? notation has an implicit base uri of 'varid:' -*/ -var Variable = /*#__PURE__*/function (_Node) { - (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Variable, _Node); - var _super = _createSuper(Variable); - /** The base string for a variable's name */ - - /** The unique identifier of this variable */ - - /** - * Initializes this variable - * @param name The variable's name - */ - function Variable() { - var _this; - var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; - (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Variable); - _this = _super.call(this, name); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.VariableTermType); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "base", 'varid:'); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_8__["default"].Variable); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 1); - (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "uri", void 0); - _this.base = 'varid:'; - _this.uri = _uri__WEBPACK_IMPORTED_MODULE_9__.join(name, _this.base); - return _this; - } - (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Variable, [{ - key: "equals", - value: function equals(other) { - if (!other) { - return false; - } - return this.termType === other.termType && this.value === other.value; - } - }, { - key: "hashString", - value: function hashString() { - return this.toString(); - } - }, { - key: "substitute", - value: function substitute(bindings) { - var ref; - return (ref = bindings[this.toNT()]) != null ? ref : this; - } - }, { - key: "toString", - value: function toString() { - return Variable.toString(this); - } - }], [{ - key: "toString", - value: function toString(variable) { - if (variable.uri.slice(0, variable.base.length) === variable.base) { - return "?".concat(variable.uri.slice(variable.base.length)); - } - return "?".concat(variable.uri); - } - }]); - return Variable; -}(_node_internal__WEBPACK_IMPORTED_MODULE_10__["default"]); - - -/***/ }), - -/***/ "../rdflib/esm/xsd-internal.js": -/*!*************************************!*\ - !*** ../rdflib/esm/xsd-internal.js ***! - \*************************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./named-node */ "../rdflib/esm/named-node.js"); - -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ - boolean: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#boolean'), - dateTime: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#dateTime'), - decimal: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#decimal'), - double: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#double'), - integer: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#integer'), - langString: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString'), - string: new _named_node__WEBPACK_IMPORTED_MODULE_0__["default"]('http://www.w3.org/2001/XMLSchema#string') -}); - -/***/ }), - -/***/ "../rdflib/esm/xsd.js": -/*!****************************!*\ - !*** ../rdflib/esm/xsd.js ***! - \****************************/ -/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -/* harmony export */ __webpack_require__.d(__webpack_exports__, { -/* harmony export */ "createXSD": () => (/* binding */ createXSD), -/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) -/* harmony export */ }); -/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "../rdflib/esm/factories/canonical-data-factory.js"); - -function createXSD() { - var localFactory = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_0__["default"]; - return { - boolean: localFactory.namedNode("http://www.w3.org/2001/XMLSchema#boolean"), - dateTime: localFactory.namedNode("http://www.w3.org/2001/XMLSchema#dateTime"), - decimal: localFactory.namedNode("http://www.w3.org/2001/XMLSchema#decimal"), - double: localFactory.namedNode("http://www.w3.org/2001/XMLSchema#double"), - integer: localFactory.namedNode("http://www.w3.org/2001/XMLSchema#integer"), - langString: localFactory.namedNode("http://www.w3.org/1999/02/22-rdf-syntax-ns#langString"), - string: localFactory.namedNode("http://www.w3.org/2001/XMLSchema#string") - }; -} -var defaultXSD = createXSD(_factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_0__["default"]); -/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (defaultXSD); - -/***/ }), - -/***/ "../rdflib/node_modules/@frogcat/ttl2jsonld/ttl2jsonld.js": -/*!****************************************************************!*\ - !*** ../rdflib/node_modules/@frogcat/ttl2jsonld/ttl2jsonld.js ***! - \****************************************************************/ -/***/ (function(module, exports, __webpack_require__) { - -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* - * Generated by PEG.js 0.10.0. - * - * http://pegjs.org/ - */ -(function(root, factory) { - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else {} -})(this, function() { - "use strict"; - - function peg$subclass(child, parent) { - function ctor() { this.constructor = child; } - ctor.prototype = parent.prototype; - child.prototype = new ctor(); - } - - function peg$SyntaxError(message, expected, found, location) { - this.message = message; - this.expected = expected; - this.found = found; - this.location = location; - this.name = "SyntaxError"; - - if (typeof Error.captureStackTrace === "function") { - Error.captureStackTrace(this, peg$SyntaxError); - } - } - - peg$subclass(peg$SyntaxError, Error); - - peg$SyntaxError.buildMessage = function(expected, found) { - var DESCRIBE_EXPECTATION_FNS = { - literal: function(expectation) { - return "\"" + literalEscape(expectation.text) + "\""; - }, - - "class": function(expectation) { - var escapedParts = "", - i; - - for (i = 0; i < expectation.parts.length; i++) { - escapedParts += expectation.parts[i] instanceof Array - ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1]) - : classEscape(expectation.parts[i]); - } - - return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]"; - }, - - any: function(expectation) { - return "any character"; - }, - - end: function(expectation) { - return "end of input"; - }, - - other: function(expectation) { - return expectation.description; - } - }; - - function hex(ch) { - return ch.charCodeAt(0).toString(16).toUpperCase(); - } - - function literalEscape(s) { - return s - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\0/g, '\\0') - .replace(/\t/g, '\\t') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); - } - - function classEscape(s) { - return s - .replace(/\\/g, '\\\\') - .replace(/\]/g, '\\]') - .replace(/\^/g, '\\^') - .replace(/-/g, '\\-') - .replace(/\0/g, '\\0') - .replace(/\t/g, '\\t') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/[\x00-\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) - .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x' + hex(ch); }); - } - - function describeExpectation(expectation) { - return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation); - } - - function describeExpected(expected) { - var descriptions = new Array(expected.length), - i, j; - - for (i = 0; i < expected.length; i++) { - descriptions[i] = describeExpectation(expected[i]); - } - - descriptions.sort(); - - if (descriptions.length > 0) { - for (i = 1, j = 1; i < descriptions.length; i++) { - if (descriptions[i - 1] !== descriptions[i]) { - descriptions[j] = descriptions[i]; - j++; - } - } - descriptions.length = j; - } - - switch (descriptions.length) { - case 1: - return descriptions[0]; - - case 2: - return descriptions[0] + " or " + descriptions[1]; - - default: - return descriptions.slice(0, -1).join(", ") - + ", or " - + descriptions[descriptions.length - 1]; - } - } - - function describeFound(found) { - return found ? "\"" + literalEscape(found) + "\"" : "end of input"; - } - - return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found."; - }; - - function peg$parse(input, options) { - options = options !== void 0 ? options : {}; - - var peg$FAILED = {}, - - peg$startRuleFunctions = { turtleDoc: peg$parseturtleDoc }, - peg$startRuleFunction = peg$parseturtleDoc, - - peg$c0 = function(statements) { - var jsonld = context.toJSON(); - jsonld["@graph"] = []; - statements.filter(a=>Array.isArray(a)).forEach(a=>{ - a.forEach(b=>{ - jsonld["@graph"].push(b); - }); - }); - - if(jsonld["@graph"].length===1){ - Object.assign(jsonld,jsonld["@graph"][0]); - delete jsonld["@graph"]; - } - - return jsonld; - }, - peg$c1 = ".", - peg$c2 = peg$literalExpectation(".", false), - peg$c3 = function(a) {return a;}, - peg$c4 = "#", - peg$c5 = peg$literalExpectation("#", false), - peg$c6 = /^[^\n]/, - peg$c7 = peg$classExpectation(["\n"], true, false), - peg$c8 = "\n", - peg$c9 = peg$literalExpectation("\n", false), - peg$c10 = function(a) {return a.join("");}, - peg$c11 = "@prefix", - peg$c12 = peg$literalExpectation("@prefix", false), - peg$c13 = function(a, b) { - context.addPrefix(a==="" ? "0" : a,b); - return {}; - }, - peg$c14 = "@base", - peg$c15 = peg$literalExpectation("@base", false), - peg$c16 = function(a) { - context.addBase(a); - return {}; - }, - peg$c17 = /^[Bb]/, - peg$c18 = peg$classExpectation(["B", "b"], false, false), - peg$c19 = /^[Aa]/, - peg$c20 = peg$classExpectation(["A", "a"], false, false), - peg$c21 = /^[Ss]/, - peg$c22 = peg$classExpectation(["S", "s"], false, false), - peg$c23 = /^[Ee]/, - peg$c24 = peg$classExpectation(["E", "e"], false, false), - peg$c25 = /^[Pp]/, - peg$c26 = peg$classExpectation(["P", "p"], false, false), - peg$c27 = /^[Rr]/, - peg$c28 = peg$classExpectation(["R", "r"], false, false), - peg$c29 = /^[Ff]/, - peg$c30 = peg$classExpectation(["F", "f"], false, false), - peg$c31 = /^[Ii]/, - peg$c32 = peg$classExpectation(["I", "i"], false, false), - peg$c33 = /^[Xx]/, - peg$c34 = peg$classExpectation(["X", "x"], false, false), - peg$c35 = function(s, p) { - var x = {}; - if(typeof s==='string' && s!=='[]') x["@id"] = s; - else if(typeof s==='object') Object.assign(x,s); - if(p) Object.assign(x,p); - return [x]; - }, - peg$c36 = function(s, p) { - var x = {}; - if(s) Object.assign(x,s); - if(p) Object.assign(x,p); - return [x]; - }, - peg$c37 = ";", - peg$c38 = peg$literalExpectation(";", false), - peg$c39 = function(a, b, e, f) {var x={};x[e]=f;return x;}, - peg$c40 = function(a, b, d) {return d;}, - peg$c41 = function(a, b, c) { - var x = {}; - c.unshift(createObject(a,b)); - c.forEach(t=>{ - if(!t) return; - Object.keys(t).forEach(key=>{ - t[key].forEach(val=>{ - if(key==="@type" && val["@id"]!==undefined) val = val["@id"]; - if(x[key]===undefined) x[key] = val; - else if(Array.isArray(x[key])) x[key].push(val); - else x[key] = [x[key],val]; - }); - }); - }); - return x; - }, - peg$c42 = ",", - peg$c43 = peg$literalExpectation(",", false), - peg$c44 = function(a, c) {return c;}, - peg$c45 = function(a, b) { - b.unshift(a); - return b; - }, - peg$c46 = "a", - peg$c47 = peg$literalExpectation("a", false), - peg$c48 = function() {return '@type';}, - peg$c49 = function(a) {return expandList(a,true);}, - peg$c50 = function(a) {return expandList(a,false);}, - peg$c51 = function(a) {return a==="[]" ? {} : {"@id":a};}, - peg$c52 = function(a) {return {"@id":a};}, - peg$c53 = "[", - peg$c54 = peg$literalExpectation("[", false), - peg$c55 = "]", - peg$c56 = peg$literalExpectation("]", false), - peg$c57 = "(", - peg$c58 = peg$literalExpectation("(", false), - peg$c59 = ")", - peg$c60 = peg$literalExpectation(")", false), - peg$c61 = function(a) {return {"@list":a};}, - peg$c62 = function(a, b) {return {"@value":a,"@language":b};}, - peg$c63 = "^^", - peg$c64 = peg$literalExpectation("^^", false), - peg$c65 = function(a, b) { - if(b==="http://www.w3.org/2001/XMLSchema#boolean" && a==="true") return true; - if(b==="http://www.w3.org/2001/XMLSchema#boolean" && a==="false") return false; - if(b==="http://www.w3.org/2001/XMLSchema#integer") return parseInt(a); - if(b==="http://www.w3.org/2001/XMLSchema#double") return parseFloat(a); - - const uri = context.resolve(b,true); - if(uri){ - const prefix = b.split(":")[0]; - if(uri==="http://www.w3.org/2001/XMLSchema#boolean" && a==="true"){ - context.decrement(prefix); - return true; - } - if(uri==="http://www.w3.org/2001/XMLSchema#boolean" && a==="false"){ - context.decrement(prefix); - return false; - } - if(uri==="http://www.w3.org/2001/XMLSchema#integer"){ - context.decrement(prefix); - return parseInt(a); - } - if(uri==="http://www.w3.org/2001/XMLSchema#double"){ - context.decrement(prefix); - return parseFloat(a); - } - } - return {"@value":a,"@type":b}; - }, - peg$c66 = "true", - peg$c67 = peg$literalExpectation("true", false), - peg$c68 = function() {return true;}, - peg$c69 = "false", - peg$c70 = peg$literalExpectation("false", false), - peg$c71 = function() {return false;}, - peg$c72 = function(a) {return a+":";}, - peg$c73 = "<", - peg$c74 = peg$literalExpectation("<", false), - peg$c75 = /^[^\0- <>"{}|\^`\\]/, - peg$c76 = peg$classExpectation([["\0", " "], "<", ">", "\"", "{", "}", "|", "^", "`", "\\"], true, false), - peg$c77 = ">", - peg$c78 = peg$literalExpectation(">", false), - peg$c79 = function(a) { - const decoded = a.map(s=> { - if(0x10000 <= s.codePointAt(0) && s.codePointAt(0) <= 0xeffff) return 'a'; - if(s.length===1) return s; - if(s.length===6) return String.fromCharCode("0x"+s.substring(2)); - if(s.length===10) return String.fromCodePoint("0x"+s.substring(2)); - return s; - }).join(""); - if(decoded.match(/^[^\u0000-\u0020<>"{}|^`\\]*$/)){ - var join = a.join(""); - try{ - return context.resolve(join); - }catch(e){ - error("Invalid IRIREF "+join); - } - } - else error("Invalid IRIREF "+a.join("")+" / "+decoded); - }, - peg$c80 = ":", - peg$c81 = peg$literalExpectation(":", false), - peg$c82 = function(a) { - a = a || "0"; - if(context.hasPrefix(a)===false) - error("undefined prefix "+a); - return a; - }, - peg$c83 = function(a) {return (a||"");}, - peg$c84 = function(a, b) { - context.increment(a); - return context.resolve(a+":"+b); - }, - peg$c85 = "_:", - peg$c86 = peg$literalExpectation("_:", false), - peg$c87 = /^[0-9]/, - peg$c88 = peg$classExpectation([["0", "9"]], false, false), - peg$c89 = "@", - peg$c90 = peg$literalExpectation("@", false), - peg$c91 = /^[a-zA-Z]/, - peg$c92 = peg$classExpectation([["a", "z"], ["A", "Z"]], false, false), - peg$c93 = "-", - peg$c94 = peg$literalExpectation("-", false), - peg$c95 = /^[a-zA-Z0-9]/, - peg$c96 = peg$classExpectation([["a", "z"], ["A", "Z"], ["0", "9"]], false, false), - peg$c97 = function(a, s) {return '-'+s.join("");}, - peg$c98 = function(a, b) {return a.join("")+b.join("");}, - peg$c99 = /^[+\-]/, - peg$c100 = peg$classExpectation(["+", "-"], false, false), - peg$c101 = function(a) { - if(a.match(/^[0+][0-9]+$/)) - return { - "@value" : a, - "@type" : "http://www.w3.org/2001/XMLSchema#integer" - }; - return parseInt(a); - }, - peg$c102 = function(a) { - return { - "@value" : a, - "@type" : "http://www.w3.org/2001/XMLSchema#decimal" - } - }, - peg$c103 = function(a) { - return { - "@value" : a, - "@type" : "http://www.w3.org/2001/XMLSchema#double" - }; - }, - peg$c104 = /^[eE]/, - peg$c105 = peg$classExpectation(["e", "E"], false, false), - peg$c106 = "\"", - peg$c107 = peg$literalExpectation("\"", false), - peg$c108 = /^[^"\\\n\r]/, - peg$c109 = peg$classExpectation(["\"", "\\", "\n", "\r"], true, false), - peg$c110 = "'", - peg$c111 = peg$literalExpectation("'", false), - peg$c112 = /^[^'\\\n\r]/, - peg$c113 = peg$classExpectation(["'", "\\", "\n", "\r"], true, false), - peg$c114 = "'''", - peg$c115 = peg$literalExpectation("'''", false), - peg$c116 = /^[^'\\]/, - peg$c117 = peg$classExpectation(["'", "\\"], true, false), - peg$c118 = "''", - peg$c119 = peg$literalExpectation("''", false), - peg$c120 = function(head, a) {return "''"+a.join("");}, - peg$c121 = function(head, a) {return "'" +a.join("");}, - peg$c122 = function(head, body) {return head.join("")+body.join("");}, - peg$c123 = "\"\"\"", - peg$c124 = peg$literalExpectation("\"\"\"", false), - peg$c125 = /^[^"\\]/, - peg$c126 = peg$classExpectation(["\"", "\\"], true, false), - peg$c127 = "\"\"", - peg$c128 = peg$literalExpectation("\"\"", false), - peg$c129 = function(head, a) {return '""'+a.join("");}, - peg$c130 = function(head, a) {return '"' +a.join("");}, - peg$c131 = "\\U", - peg$c132 = peg$literalExpectation("\\U", false), - peg$c133 = function(hex) { - return String.fromCodePoint(parseInt(hex.join(""),16)); - }, - peg$c134 = "\\u", - peg$c135 = peg$literalExpectation("\\u", false), - peg$c136 = function(hex) { - return String.fromCharCode(parseInt(hex.join(""),16)); - }, - peg$c137 = "\\t", - peg$c138 = peg$literalExpectation("\\t", false), - peg$c139 = function() {return '\t';}, - peg$c140 = "\\b", - peg$c141 = peg$literalExpectation("\\b", false), - peg$c142 = function() {return '\b';}, - peg$c143 = "\\n", - peg$c144 = peg$literalExpectation("\\n", false), - peg$c145 = function() {return '\n';}, - peg$c146 = "\\r", - peg$c147 = peg$literalExpectation("\\r", false), - peg$c148 = function() {return '\r';}, - peg$c149 = "\\f", - peg$c150 = peg$literalExpectation("\\f", false), - peg$c151 = function() {return '\f';}, - peg$c152 = "\\\"", - peg$c153 = peg$literalExpectation("\\\"", false), - peg$c154 = function() {return '"';}, - peg$c155 = "\\'", - peg$c156 = peg$literalExpectation("\\'", false), - peg$c157 = function() {return "'";}, - peg$c158 = "\\\\", - peg$c159 = peg$literalExpectation("\\\\", false), - peg$c160 = function() {return '\\';}, - peg$c161 = /^[ \t\r\n]/, - peg$c162 = peg$classExpectation([" ", "\t", "\r", "\n"], false, false), - peg$c163 = function() {return "[]";}, - peg$c164 = /^[\uD800-\uDBFF]/, - peg$c165 = peg$classExpectation([["\uD800", "\uDBFF"]], false, false), - peg$c166 = /^[\uDC00-\uDFFF]/, - peg$c167 = peg$classExpectation([["\uDC00", "\uDFFF"]], false, false), - peg$c168 = function(a, b) {return a+b;}, - peg$c169 = /^[A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/, - peg$c170 = peg$classExpectation([["A", "Z"], ["a", "z"], ["\xC0", "\xD6"], ["\xD8", "\xF6"], ["\xF8", "\u02FF"], ["\u0370", "\u037D"], ["\u037F", "\u1FFF"], ["\u200C", "\u200D"], ["\u2070", "\u218F"], ["\u2C00", "\u2FEF"], ["\u3001", "\uD7FF"], ["\uF900", "\uFDCF"], ["\uFDF0", "\uFFFD"]], false, false), - peg$c171 = "_", - peg$c172 = peg$literalExpectation("_", false), - peg$c173 = "\xB7", - peg$c174 = peg$literalExpectation("\xB7", false), - peg$c175 = /^[\u0300-\u036F]/, - peg$c176 = peg$classExpectation([["\u0300", "\u036F"]], false, false), - peg$c177 = /^[\u203F-\u2040]/, - peg$c178 = peg$classExpectation([["\u203F", "\u2040"]], false, false), - peg$c179 = function(head, body, a, b) {return a.join("")+b.join("");}, - peg$c180 = function(head, body, tail) {return head+body.join("")+tail.join("");}, - peg$c181 = "%", - peg$c182 = peg$literalExpectation("%", false), - peg$c183 = /^[0-9A-Fa-f]/, - peg$c184 = peg$classExpectation([["0", "9"], ["A", "F"], ["a", "f"]], false, false), - peg$c185 = "\\", - peg$c186 = peg$literalExpectation("\\", false), - peg$c187 = /^[_~.!$&'()*+,;=\/?#@%\-]/, - peg$c188 = peg$classExpectation(["_", "~", ".", "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=", "/", "?", "#", "@", "%", "-"], false, false), - - peg$currPos = 0, - peg$savedPos = 0, - peg$posDetailsCache = [{ line: 1, column: 1 }], - peg$maxFailPos = 0, - peg$maxFailExpected = [], - peg$silentFails = 0, - - peg$result; - - if ("startRule" in options) { - if (!(options.startRule in peg$startRuleFunctions)) { - throw new Error("Can't start parsing from rule \"" + options.startRule + "\"."); - } - - peg$startRuleFunction = peg$startRuleFunctions[options.startRule]; - } - - function text() { - return input.substring(peg$savedPos, peg$currPos); - } - - function location() { - return peg$computeLocation(peg$savedPos, peg$currPos); - } - - function expected(description, location) { - location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) - - throw peg$buildStructuredError( - [peg$otherExpectation(description)], - input.substring(peg$savedPos, peg$currPos), - location - ); - } - - function error(message, location) { - location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos) - - throw peg$buildSimpleError(message, location); - } - - function peg$literalExpectation(text, ignoreCase) { - return { type: "literal", text: text, ignoreCase: ignoreCase }; - } - - function peg$classExpectation(parts, inverted, ignoreCase) { - return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase }; - } - - function peg$anyExpectation() { - return { type: "any" }; - } - - function peg$endExpectation() { - return { type: "end" }; - } - - function peg$otherExpectation(description) { - return { type: "other", description: description }; - } - - function peg$computePosDetails(pos) { - var details = peg$posDetailsCache[pos], p; - - if (details) { - return details; - } else { - p = pos - 1; - while (!peg$posDetailsCache[p]) { - p--; - } - - details = peg$posDetailsCache[p]; - details = { - line: details.line, - column: details.column - }; - - while (p < pos) { - if (input.charCodeAt(p) === 10) { - details.line++; - details.column = 1; - } else { - details.column++; - } - - p++; - } - - peg$posDetailsCache[pos] = details; - return details; - } - } - - function peg$computeLocation(startPos, endPos) { - var startPosDetails = peg$computePosDetails(startPos), - endPosDetails = peg$computePosDetails(endPos); - - return { - start: { - offset: startPos, - line: startPosDetails.line, - column: startPosDetails.column - }, - end: { - offset: endPos, - line: endPosDetails.line, - column: endPosDetails.column - } - }; - } - - function peg$fail(expected) { - if (peg$currPos < peg$maxFailPos) { return; } - - if (peg$currPos > peg$maxFailPos) { - peg$maxFailPos = peg$currPos; - peg$maxFailExpected = []; - } - - peg$maxFailExpected.push(expected); - } - - function peg$buildSimpleError(message, location) { - return new peg$SyntaxError(message, null, null, location); - } - - function peg$buildStructuredError(expected, found, location) { - return new peg$SyntaxError( - peg$SyntaxError.buildMessage(expected, found), - expected, - found, - location - ); - } - - function peg$parseturtleDoc() { - var s0, s1, s2, s3; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parsestatement(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parsestatement(); - } - if (s1 !== peg$FAILED) { - s2 = []; - s3 = peg$parseIGNORE(); - while (s3 !== peg$FAILED) { - s2.push(s3); - s3 = peg$parseIGNORE(); - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c0(s1); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsestatement() { - var s0, s1, s2, s3; - - s0 = peg$parsedirective(); - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = peg$parsetriples(); - if (s1 !== peg$FAILED) { - s2 = []; - s3 = peg$parseIGNORE(); - while (s3 !== peg$FAILED) { - s2.push(s3); - s3 = peg$parseIGNORE(); - } - if (s2 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 46) { - s3 = peg$c1; - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s3 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s1); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } - - return s0; - } - - function peg$parseCOMMENT() { - var s0, s1, s2, s3; - - s0 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 35) { - s1 = peg$c4; - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c5); } - } - if (s1 !== peg$FAILED) { - s2 = []; - if (peg$c6.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c7); } - } - while (s3 !== peg$FAILED) { - s2.push(s3); - if (peg$c6.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c7); } - } - } - if (s2 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 10) { - s3 = peg$c8; - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c9); } - } - if (s3 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c10(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseIGNORE() { - var s0; - - s0 = peg$parseWS(); - if (s0 === peg$FAILED) { - s0 = peg$parseCOMMENT(); - } - - return s0; - } - - function peg$parsedirective() { - var s0; - - s0 = peg$parseprefixID(); - if (s0 === peg$FAILED) { - s0 = peg$parsebase(); - if (s0 === peg$FAILED) { - s0 = peg$parsesparqlPrefix(); - if (s0 === peg$FAILED) { - s0 = peg$parsesparqlBase(); - } - } - } - - return s0; - } - - function peg$parseprefixID() { - var s0, s1, s2, s3, s4, s5, s6, s7, s8; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - if (input.substr(peg$currPos, 7) === peg$c11) { - s2 = peg$c11; - peg$currPos += 7; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c12); } - } - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$parseIGNORE(); - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$parseIGNORE(); - } - if (s3 !== peg$FAILED) { - s4 = peg$parsePNAME_NS_NO_CHECK(); - if (s4 !== peg$FAILED) { - s5 = []; - s6 = peg$parseIGNORE(); - while (s6 !== peg$FAILED) { - s5.push(s6); - s6 = peg$parseIGNORE(); - } - if (s5 !== peg$FAILED) { - s6 = peg$parseIRIREF(); - if (s6 !== peg$FAILED) { - s7 = []; - s8 = peg$parseIGNORE(); - while (s8 !== peg$FAILED) { - s7.push(s8); - s8 = peg$parseIGNORE(); - } - if (s7 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 46) { - s8 = peg$c1; - peg$currPos++; - } else { - s8 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s8 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c13(s4, s6); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsebase() { - var s0, s1, s2, s3, s4, s5, s6; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - if (input.substr(peg$currPos, 5) === peg$c14) { - s2 = peg$c14; - peg$currPos += 5; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c15); } - } - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$parseIGNORE(); - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$parseIGNORE(); - } - if (s3 !== peg$FAILED) { - s4 = peg$parseIRIREF(); - if (s4 !== peg$FAILED) { - s5 = []; - s6 = peg$parseIGNORE(); - while (s6 !== peg$FAILED) { - s5.push(s6); - s6 = peg$parseIGNORE(); - } - if (s5 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 46) { - s6 = peg$c1; - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s6 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c16(s4); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsesparqlBase() { - var s0, s1, s2, s3, s4, s5, s6, s7; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - if (peg$c17.test(input.charAt(peg$currPos))) { - s2 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c18); } - } - if (s2 !== peg$FAILED) { - if (peg$c19.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c20); } - } - if (s3 !== peg$FAILED) { - if (peg$c21.test(input.charAt(peg$currPos))) { - s4 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s4 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c22); } - } - if (s4 !== peg$FAILED) { - if (peg$c23.test(input.charAt(peg$currPos))) { - s5 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c24); } - } - if (s5 !== peg$FAILED) { - s6 = []; - s7 = peg$parseIGNORE(); - while (s7 !== peg$FAILED) { - s6.push(s7); - s7 = peg$parseIGNORE(); - } - if (s6 !== peg$FAILED) { - s7 = peg$parseIRIREF(); - if (s7 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c16(s7); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsesparqlPrefix() { - var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - if (peg$c25.test(input.charAt(peg$currPos))) { - s2 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c26); } - } - if (s2 !== peg$FAILED) { - if (peg$c27.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c28); } - } - if (s3 !== peg$FAILED) { - if (peg$c23.test(input.charAt(peg$currPos))) { - s4 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s4 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c24); } - } - if (s4 !== peg$FAILED) { - if (peg$c29.test(input.charAt(peg$currPos))) { - s5 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c30); } - } - if (s5 !== peg$FAILED) { - if (peg$c31.test(input.charAt(peg$currPos))) { - s6 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c32); } - } - if (s6 !== peg$FAILED) { - if (peg$c33.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c34); } - } - if (s7 !== peg$FAILED) { - s8 = []; - s9 = peg$parseIGNORE(); - while (s9 !== peg$FAILED) { - s8.push(s9); - s9 = peg$parseIGNORE(); - } - if (s8 !== peg$FAILED) { - s9 = peg$parsePNAME_NS_NO_CHECK(); - if (s9 !== peg$FAILED) { - s10 = []; - s11 = peg$parseIGNORE(); - while (s11 !== peg$FAILED) { - s10.push(s11); - s11 = peg$parseIGNORE(); - } - if (s10 !== peg$FAILED) { - s11 = peg$parseIRIREF(); - if (s11 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c13(s9, s11); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsetriples() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = peg$parsesubject(); - if (s1 !== peg$FAILED) { - s2 = peg$parsepredicateObjectList(); - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c35(s1, s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = peg$parseblankNodePropertyList(); - if (s1 !== peg$FAILED) { - s2 = peg$parsepredicateObjectList(); - if (s2 === peg$FAILED) { - s2 = null; - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c36(s1, s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } - - return s0; - } - - function peg$parsepredicateObjectList() { - var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; - - s0 = peg$currPos; - s1 = peg$parseverb(); - if (s1 !== peg$FAILED) { - s2 = peg$parseobjectList(); - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$currPos; - s5 = []; - s6 = peg$parseIGNORE(); - while (s6 !== peg$FAILED) { - s5.push(s6); - s6 = peg$parseIGNORE(); - } - if (s5 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 59) { - s6 = peg$c37; - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c38); } - } - if (s6 !== peg$FAILED) { - s7 = peg$currPos; - s8 = peg$parseverb(); - if (s8 !== peg$FAILED) { - s9 = peg$parseobjectList(); - if (s9 !== peg$FAILED) { - peg$savedPos = s7; - s8 = peg$c39(s1, s2, s8, s9); - s7 = s8; - } else { - peg$currPos = s7; - s7 = peg$FAILED; - } - } else { - peg$currPos = s7; - s7 = peg$FAILED; - } - if (s7 === peg$FAILED) { - s7 = null; - } - if (s7 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c40(s1, s2, s7); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$currPos; - s5 = []; - s6 = peg$parseIGNORE(); - while (s6 !== peg$FAILED) { - s5.push(s6); - s6 = peg$parseIGNORE(); - } - if (s5 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 59) { - s6 = peg$c37; - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c38); } - } - if (s6 !== peg$FAILED) { - s7 = peg$currPos; - s8 = peg$parseverb(); - if (s8 !== peg$FAILED) { - s9 = peg$parseobjectList(); - if (s9 !== peg$FAILED) { - peg$savedPos = s7; - s8 = peg$c39(s1, s2, s8, s9); - s7 = s8; - } else { - peg$currPos = s7; - s7 = peg$FAILED; - } - } else { - peg$currPos = s7; - s7 = peg$FAILED; - } - if (s7 === peg$FAILED) { - s7 = null; - } - if (s7 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c40(s1, s2, s7); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } - if (s3 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c41(s1, s2, s3); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseobjectList() { - var s0, s1, s2, s3, s4, s5, s6; - - s0 = peg$currPos; - s1 = peg$parseobject(); - if (s1 !== peg$FAILED) { - s2 = []; - s3 = peg$currPos; - s4 = []; - s5 = peg$parseIGNORE(); - while (s5 !== peg$FAILED) { - s4.push(s5); - s5 = peg$parseIGNORE(); - } - if (s4 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 44) { - s5 = peg$c42; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c43); } - } - if (s5 !== peg$FAILED) { - s6 = peg$parseobject(); - if (s6 !== peg$FAILED) { - peg$savedPos = s3; - s4 = peg$c44(s1, s6); - s3 = s4; - } else { - peg$currPos = s3; - s3 = peg$FAILED; - } - } else { - peg$currPos = s3; - s3 = peg$FAILED; - } - } else { - peg$currPos = s3; - s3 = peg$FAILED; - } - while (s3 !== peg$FAILED) { - s2.push(s3); - s3 = peg$currPos; - s4 = []; - s5 = peg$parseIGNORE(); - while (s5 !== peg$FAILED) { - s4.push(s5); - s5 = peg$parseIGNORE(); - } - if (s4 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 44) { - s5 = peg$c42; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c43); } - } - if (s5 !== peg$FAILED) { - s6 = peg$parseobject(); - if (s6 !== peg$FAILED) { - peg$savedPos = s3; - s4 = peg$c44(s1, s6); - s3 = s4; - } else { - peg$currPos = s3; - s3 = peg$FAILED; - } - } else { - peg$currPos = s3; - s3 = peg$FAILED; - } - } else { - peg$currPos = s3; - s3 = peg$FAILED; - } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c45(s1, s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseverb() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = peg$parsepredicate(); - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s1); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 97) { - s2 = peg$c46; - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c47); } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c48(); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } - - return s0; - } - - function peg$parsesubject() { - var s0, s1; - - s0 = peg$currPos; - s1 = peg$parsecollection(); - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c49(s1); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$parseBlankNode(); - if (s0 === peg$FAILED) { - s0 = peg$parseiri(); - } - } - - return s0; - } - - function peg$parsepredicate() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parseiri(); - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseobject() { - var s0, s1; - - s0 = peg$parseliteral(); - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = peg$parsecollection(); - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c50(s1); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = peg$parseBlankNode(); - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c51(s1); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = peg$parseblankNodePropertyList(); - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s1); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = peg$parseiri(); - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c52(s1); - } - s0 = s1; - } - } - } - } - - return s0; - } - - function peg$parseliteral() { - var s0; - - s0 = peg$parseRDFLiteral(); - if (s0 === peg$FAILED) { - s0 = peg$parseNumericLiteral(); - if (s0 === peg$FAILED) { - s0 = peg$parseBooleanLiteral(); - } - } - - return s0; - } - - function peg$parseblankNodePropertyList() { - var s0, s1, s2, s3, s4, s5; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 91) { - s2 = peg$c53; - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c54); } - } - if (s2 !== peg$FAILED) { - s3 = peg$parsepredicateObjectList(); - if (s3 !== peg$FAILED) { - s4 = []; - s5 = peg$parseIGNORE(); - while (s5 !== peg$FAILED) { - s4.push(s5); - s5 = peg$parseIGNORE(); - } - if (s4 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 93) { - s5 = peg$c55; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c56); } - } - if (s5 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s3); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsecollection() { - var s0, s1, s2, s3, s4, s5; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 40) { - s2 = peg$c57; - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c58); } - } - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$parseobject(); - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$parseobject(); - } - if (s3 !== peg$FAILED) { - s4 = []; - s5 = peg$parseIGNORE(); - while (s5 !== peg$FAILED) { - s4.push(s5); - s5 = peg$parseIGNORE(); - } - if (s4 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 41) { - s5 = peg$c59; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c60); } - } - if (s5 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c61(s3); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseNumericLiteral() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parseDOUBLE(); - if (s2 === peg$FAILED) { - s2 = peg$parseDECIMAL(); - if (s2 === peg$FAILED) { - s2 = peg$parseINTEGER(); - } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseRDFLiteral() { - var s0, s1, s2, s3, s4, s5, s6; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parseString(); - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$parseIGNORE(); - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$parseIGNORE(); - } - if (s3 !== peg$FAILED) { - s4 = peg$parseLANGTAG(); - if (s4 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c62(s2, s4); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parseString(); - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$parseIGNORE(); - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$parseIGNORE(); - } - if (s3 !== peg$FAILED) { - if (input.substr(peg$currPos, 2) === peg$c63) { - s4 = peg$c63; - peg$currPos += 2; - } else { - s4 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c64); } - } - if (s4 !== peg$FAILED) { - s5 = []; - s6 = peg$parseIGNORE(); - while (s6 !== peg$FAILED) { - s5.push(s6); - s6 = peg$parseIGNORE(); - } - if (s5 !== peg$FAILED) { - s6 = peg$parseiri(); - if (s6 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c65(s2, s6); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parseString(); - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } - } - - return s0; - } - - function peg$parseBooleanLiteral() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - if (input.substr(peg$currPos, 4) === peg$c66) { - s2 = peg$c66; - peg$currPos += 4; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c67); } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c68(); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - if (input.substr(peg$currPos, 5) === peg$c69) { - s2 = peg$c69; - peg$currPos += 5; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c70); } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c71(); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } - - return s0; - } - - function peg$parseString() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parseSTRING_LITERAL_LONG_SINGLE_QUOTE(); - if (s2 === peg$FAILED) { - s2 = peg$parseSTRING_LITERAL_LONG_QUOTE(); - if (s2 === peg$FAILED) { - s2 = peg$parseSTRING_LITERAL_SINGLE_QUOTE(); - if (s2 === peg$FAILED) { - s2 = peg$parseSTRING_LITERAL_QUOTE(); - } - } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseiri() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parseIRIREF(); - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parsePrefixedName(); - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } - - return s0; - } - - function peg$parsePrefixedName() { - var s0, s1; - - s0 = peg$parsePNAME_LN(); - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = peg$parsePNAME_NS(); - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c72(s1); - } - s0 = s1; - } - - return s0; - } - - function peg$parseBlankNode() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parseBLANK_NODE_LABEL(); - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - if (s0 === peg$FAILED) { - s0 = peg$currPos; - s1 = []; - s2 = peg$parseIGNORE(); - while (s2 !== peg$FAILED) { - s1.push(s2); - s2 = peg$parseIGNORE(); - } - if (s1 !== peg$FAILED) { - s2 = peg$parseANON(); - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } - - return s0; - } - - function peg$parseIRIREF() { - var s0, s1, s2, s3; - - s0 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 60) { - s1 = peg$c73; - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c74); } - } - if (s1 !== peg$FAILED) { - s2 = []; - if (peg$c75.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c76); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - while (s3 !== peg$FAILED) { - s2.push(s3); - if (peg$c75.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c76); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - } - if (s2 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 62) { - s3 = peg$c77; - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c78); } - } - if (s3 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c79(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsePNAME_NS() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = peg$parsePN_PREFIX(); - if (s1 === peg$FAILED) { - s1 = null; - } - if (s1 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 58) { - s2 = peg$c80; - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c81); } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c82(s1); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsePNAME_NS_NO_CHECK() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = peg$parsePN_PREFIX(); - if (s1 === peg$FAILED) { - s1 = null; - } - if (s1 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 58) { - s2 = peg$c80; - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c81); } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c83(s1); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsePNAME_LN() { - var s0, s1, s2; - - s0 = peg$currPos; - s1 = peg$parsePNAME_NS(); - if (s1 !== peg$FAILED) { - s2 = peg$parsePN_LOCAL(); - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c84(s1, s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseBLANK_NODE_LABEL() { - var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9; - - s0 = peg$currPos; - s1 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c85) { - s2 = peg$c85; - peg$currPos += 2; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c86); } - } - if (s2 !== peg$FAILED) { - s3 = peg$parsePN_CHARS_U(); - if (s3 === peg$FAILED) { - if (peg$c87.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - } - if (s3 !== peg$FAILED) { - s4 = []; - s5 = peg$parsePN_CHARS(); - while (s5 !== peg$FAILED) { - s4.push(s5); - s5 = peg$parsePN_CHARS(); - } - if (s4 !== peg$FAILED) { - s5 = []; - s6 = peg$currPos; - s7 = []; - if (input.charCodeAt(peg$currPos) === 46) { - s8 = peg$c1; - peg$currPos++; - } else { - s8 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s8 !== peg$FAILED) { - while (s8 !== peg$FAILED) { - s7.push(s8); - if (input.charCodeAt(peg$currPos) === 46) { - s8 = peg$c1; - peg$currPos++; - } else { - s8 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - } - } else { - s7 = peg$FAILED; - } - if (s7 !== peg$FAILED) { - s8 = []; - s9 = peg$parsePN_CHARS(); - if (s9 !== peg$FAILED) { - while (s9 !== peg$FAILED) { - s8.push(s9); - s9 = peg$parsePN_CHARS(); - } - } else { - s8 = peg$FAILED; - } - if (s8 !== peg$FAILED) { - s7 = [s7, s8]; - s6 = s7; - } else { - peg$currPos = s6; - s6 = peg$FAILED; - } - } else { - peg$currPos = s6; - s6 = peg$FAILED; - } - while (s6 !== peg$FAILED) { - s5.push(s6); - s6 = peg$currPos; - s7 = []; - if (input.charCodeAt(peg$currPos) === 46) { - s8 = peg$c1; - peg$currPos++; - } else { - s8 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s8 !== peg$FAILED) { - while (s8 !== peg$FAILED) { - s7.push(s8); - if (input.charCodeAt(peg$currPos) === 46) { - s8 = peg$c1; - peg$currPos++; - } else { - s8 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - } - } else { - s7 = peg$FAILED; - } - if (s7 !== peg$FAILED) { - s8 = []; - s9 = peg$parsePN_CHARS(); - if (s9 !== peg$FAILED) { - while (s9 !== peg$FAILED) { - s8.push(s9); - s9 = peg$parsePN_CHARS(); - } - } else { - s8 = peg$FAILED; - } - if (s8 !== peg$FAILED) { - s7 = [s7, s8]; - s6 = s7; - } else { - peg$currPos = s6; - s6 = peg$FAILED; - } - } else { - peg$currPos = s6; - s6 = peg$FAILED; - } - } - if (s5 !== peg$FAILED) { - s2 = [s2, s3, s4, s5]; - s1 = s2; - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - if (s1 !== peg$FAILED) { - s0 = input.substring(s0, peg$currPos); - } else { - s0 = s1; - } - - return s0; - } - - function peg$parseLANGTAG() { - var s0, s1, s2, s3, s4, s5, s6, s7; - - s0 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 64) { - s1 = peg$c89; - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c90); } - } - if (s1 !== peg$FAILED) { - s2 = []; - if (peg$c91.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c92); } - } - if (s3 !== peg$FAILED) { - while (s3 !== peg$FAILED) { - s2.push(s3); - if (peg$c91.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c92); } - } - } - } else { - s2 = peg$FAILED; - } - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 45) { - s5 = peg$c93; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c94); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c95.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c96); } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c95.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c96); } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c97(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 45) { - s5 = peg$c93; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c94); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c95.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c96); } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c95.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c96); } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c97(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } - if (s3 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c98(s2, s3); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseINTEGER() { - var s0, s1, s2, s3, s4, s5; - - s0 = peg$currPos; - s1 = peg$currPos; - s2 = peg$currPos; - if (peg$c99.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c100); } - } - if (s3 === peg$FAILED) { - s3 = null; - } - if (s3 !== peg$FAILED) { - s4 = []; - if (peg$c87.test(input.charAt(peg$currPos))) { - s5 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - if (s5 !== peg$FAILED) { - while (s5 !== peg$FAILED) { - s4.push(s5); - if (peg$c87.test(input.charAt(peg$currPos))) { - s5 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - } - } else { - s4 = peg$FAILED; - } - if (s4 !== peg$FAILED) { - s3 = [s3, s4]; - s2 = s3; - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - if (s2 !== peg$FAILED) { - s1 = input.substring(s1, peg$currPos); - } else { - s1 = s2; - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c101(s1); - } - s0 = s1; - - return s0; - } - - function peg$parseDECIMAL() { - var s0, s1, s2, s3, s4, s5, s6, s7; - - s0 = peg$currPos; - s1 = peg$currPos; - s2 = peg$currPos; - if (peg$c99.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c100); } - } - if (s3 === peg$FAILED) { - s3 = null; - } - if (s3 !== peg$FAILED) { - s4 = []; - if (peg$c87.test(input.charAt(peg$currPos))) { - s5 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - while (s5 !== peg$FAILED) { - s4.push(s5); - if (peg$c87.test(input.charAt(peg$currPos))) { - s5 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - } - if (s4 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 46) { - s5 = peg$c1; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c87.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c87.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - s3 = [s3, s4, s5, s6]; - s2 = s3; - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - if (s2 !== peg$FAILED) { - s1 = input.substring(s1, peg$currPos); - } else { - s1 = s2; - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c102(s1); - } - s0 = s1; - - return s0; - } - - function peg$parseDOUBLE() { - var s0, s1, s2, s3, s4, s5, s6, s7, s8; - - s0 = peg$currPos; - s1 = peg$currPos; - s2 = peg$currPos; - if (peg$c99.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c100); } - } - if (s3 === peg$FAILED) { - s3 = null; - } - if (s3 !== peg$FAILED) { - s4 = peg$currPos; - s5 = []; - if (peg$c87.test(input.charAt(peg$currPos))) { - s6 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - if (s6 !== peg$FAILED) { - while (s6 !== peg$FAILED) { - s5.push(s6); - if (peg$c87.test(input.charAt(peg$currPos))) { - s6 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - } - } else { - s5 = peg$FAILED; - } - if (s5 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 46) { - s6 = peg$c1; - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s6 !== peg$FAILED) { - s7 = []; - if (peg$c87.test(input.charAt(peg$currPos))) { - s8 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s8 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - while (s8 !== peg$FAILED) { - s7.push(s8); - if (peg$c87.test(input.charAt(peg$currPos))) { - s8 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s8 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - } - if (s7 !== peg$FAILED) { - s8 = peg$parseEXPONENT(); - if (s8 !== peg$FAILED) { - s5 = [s5, s6, s7, s8]; - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - if (s4 === peg$FAILED) { - s4 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 46) { - s5 = peg$c1; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c87.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c87.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - s7 = peg$parseEXPONENT(); - if (s7 !== peg$FAILED) { - s5 = [s5, s6, s7]; - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - if (s4 === peg$FAILED) { - s4 = peg$currPos; - s5 = []; - if (peg$c87.test(input.charAt(peg$currPos))) { - s6 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - if (s6 !== peg$FAILED) { - while (s6 !== peg$FAILED) { - s5.push(s6); - if (peg$c87.test(input.charAt(peg$currPos))) { - s6 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - } - } else { - s5 = peg$FAILED; - } - if (s5 !== peg$FAILED) { - s6 = peg$parseEXPONENT(); - if (s6 !== peg$FAILED) { - s5 = [s5, s6]; - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } - } - if (s4 !== peg$FAILED) { - s3 = [s3, s4]; - s2 = s3; - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - if (s2 !== peg$FAILED) { - s1 = input.substring(s1, peg$currPos); - } else { - s1 = s2; - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c103(s1); - } - s0 = s1; - - return s0; - } - - function peg$parseEXPONENT() { - var s0, s1, s2, s3, s4, s5; - - s0 = peg$currPos; - s1 = peg$currPos; - if (peg$c104.test(input.charAt(peg$currPos))) { - s2 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c105); } - } - if (s2 !== peg$FAILED) { - if (peg$c99.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c100); } - } - if (s3 === peg$FAILED) { - s3 = null; - } - if (s3 !== peg$FAILED) { - s4 = []; - if (peg$c87.test(input.charAt(peg$currPos))) { - s5 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - if (s5 !== peg$FAILED) { - while (s5 !== peg$FAILED) { - s4.push(s5); - if (peg$c87.test(input.charAt(peg$currPos))) { - s5 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - } - } else { - s4 = peg$FAILED; - } - if (s4 !== peg$FAILED) { - s2 = [s2, s3, s4]; - s1 = s2; - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - if (s1 !== peg$FAILED) { - s0 = input.substring(s0, peg$currPos); - } else { - s0 = s1; - } - - return s0; - } - - function peg$parseSTRING_LITERAL_QUOTE() { - var s0, s1, s2, s3; - - s0 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 34) { - s1 = peg$c106; - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c107); } - } - if (s1 !== peg$FAILED) { - s2 = []; - if (peg$c108.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c109); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseECHAR(); - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - } - while (s3 !== peg$FAILED) { - s2.push(s3); - if (peg$c108.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c109); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseECHAR(); - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - } - } - if (s2 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 34) { - s3 = peg$c106; - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c107); } - } - if (s3 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c10(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseSTRING_LITERAL_SINGLE_QUOTE() { - var s0, s1, s2, s3; - - s0 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 39) { - s1 = peg$c110; - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c111); } - } - if (s1 !== peg$FAILED) { - s2 = []; - if (peg$c112.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c113); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseECHAR(); - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - } - while (s3 !== peg$FAILED) { - s2.push(s3); - if (peg$c112.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c113); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseECHAR(); - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - } - } - if (s2 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 39) { - s3 = peg$c110; - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c111); } - } - if (s3 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c10(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseSTRING_LITERAL_LONG_SINGLE_QUOTE() { - var s0, s1, s2, s3, s4, s5, s6, s7; - - s0 = peg$currPos; - if (input.substr(peg$currPos, 3) === peg$c114) { - s1 = peg$c114; - peg$currPos += 3; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c115); } - } - if (s1 !== peg$FAILED) { - s2 = []; - if (peg$c116.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseECHAR(); - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - } - while (s3 !== peg$FAILED) { - s2.push(s3); - if (peg$c116.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseECHAR(); - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - } - } - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c118) { - s5 = peg$c118; - peg$currPos += 2; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c119); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c116.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c116.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c120(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - if (s4 === peg$FAILED) { - s4 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 39) { - s5 = peg$c110; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c111); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c116.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c116.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c121(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c118) { - s5 = peg$c118; - peg$currPos += 2; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c119); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c116.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c116.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c120(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - if (s4 === peg$FAILED) { - s4 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 39) { - s5 = peg$c110; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c111); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c116.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c116.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c117); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c121(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } - } - if (s3 !== peg$FAILED) { - if (input.substr(peg$currPos, 3) === peg$c114) { - s4 = peg$c114; - peg$currPos += 3; - } else { - s4 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c115); } - } - if (s4 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c122(s2, s3); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseSTRING_LITERAL_LONG_QUOTE() { - var s0, s1, s2, s3, s4, s5, s6, s7; - - s0 = peg$currPos; - if (input.substr(peg$currPos, 3) === peg$c123) { - s1 = peg$c123; - peg$currPos += 3; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c124); } - } - if (s1 !== peg$FAILED) { - s2 = []; - if (peg$c125.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseECHAR(); - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - } - while (s3 !== peg$FAILED) { - s2.push(s3); - if (peg$c125.test(input.charAt(peg$currPos))) { - s3 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s3 === peg$FAILED) { - s3 = peg$parseECHAR(); - if (s3 === peg$FAILED) { - s3 = peg$parseUCHAR(); - } - } - } - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c127) { - s5 = peg$c127; - peg$currPos += 2; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c128); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c125.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c125.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c129(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - if (s4 === peg$FAILED) { - s4 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 34) { - s5 = peg$c106; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c107); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c125.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c125.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c130(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c127) { - s5 = peg$c127; - peg$currPos += 2; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c128); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c125.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c125.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c129(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - if (s4 === peg$FAILED) { - s4 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 34) { - s5 = peg$c106; - peg$currPos++; - } else { - s5 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c107); } - } - if (s5 !== peg$FAILED) { - s6 = []; - if (peg$c125.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (peg$c125.test(input.charAt(peg$currPos))) { - s7 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c126); } - } - if (s7 === peg$FAILED) { - s7 = peg$parseECHAR(); - if (s7 === peg$FAILED) { - s7 = peg$parseUCHAR(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c130(s2, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } - } - if (s3 !== peg$FAILED) { - if (input.substr(peg$currPos, 3) === peg$c123) { - s4 = peg$c123; - peg$currPos += 3; - } else { - s4 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c124); } - } - if (s4 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c122(s2, s3); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parseUCHAR() { - var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; - - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c131) { - s1 = peg$c131; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c132); } - } - if (s1 !== peg$FAILED) { - s2 = peg$currPos; - s3 = peg$parseHEX(); - if (s3 !== peg$FAILED) { - s4 = peg$parseHEX(); - if (s4 !== peg$FAILED) { - s5 = peg$parseHEX(); - if (s5 !== peg$FAILED) { - s6 = peg$parseHEX(); - if (s6 !== peg$FAILED) { - s7 = peg$parseHEX(); - if (s7 !== peg$FAILED) { - s8 = peg$parseHEX(); - if (s8 !== peg$FAILED) { - s9 = peg$parseHEX(); - if (s9 !== peg$FAILED) { - s10 = peg$parseHEX(); - if (s10 !== peg$FAILED) { - s3 = [s3, s4, s5, s6, s7, s8, s9, s10]; - s2 = s3; - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c133(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - if (s0 === peg$FAILED) { - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c134) { - s1 = peg$c134; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c135); } - } - if (s1 !== peg$FAILED) { - s2 = peg$currPos; - s3 = peg$parseHEX(); - if (s3 !== peg$FAILED) { - s4 = peg$parseHEX(); - if (s4 !== peg$FAILED) { - s5 = peg$parseHEX(); - if (s5 !== peg$FAILED) { - s6 = peg$parseHEX(); - if (s6 !== peg$FAILED) { - s3 = [s3, s4, s5, s6]; - s2 = s3; - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - } else { - peg$currPos = s2; - s2 = peg$FAILED; - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c136(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } - - return s0; - } - - function peg$parseECHAR() { - var s0, s1; - - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c137) { - s1 = peg$c137; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c138); } - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c139(); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c140) { - s1 = peg$c140; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c141); } - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c142(); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c143) { - s1 = peg$c143; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c144); } - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c145(); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c146) { - s1 = peg$c146; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c147); } - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c148(); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c149) { - s1 = peg$c149; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c150); } - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c151(); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c152) { - s1 = peg$c152; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c153); } - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c154(); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c155) { - s1 = peg$c155; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c156); } - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c157(); - } - s0 = s1; - if (s0 === peg$FAILED) { - s0 = peg$currPos; - if (input.substr(peg$currPos, 2) === peg$c158) { - s1 = peg$c158; - peg$currPos += 2; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c159); } - } - if (s1 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c160(); - } - s0 = s1; - } - } - } - } - } - } - } - - return s0; - } - - function peg$parseWS() { - var s0; - - if (peg$c161.test(input.charAt(peg$currPos))) { - s0 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s0 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c162); } - } - - return s0; - } - - function peg$parseANON() { - var s0, s1, s2, s3; - - s0 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 91) { - s1 = peg$c53; - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c54); } - } - if (s1 !== peg$FAILED) { - s2 = []; - s3 = peg$parseIGNORE(); - while (s3 !== peg$FAILED) { - s2.push(s3); - s3 = peg$parseIGNORE(); - } - if (s2 !== peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 93) { - s3 = peg$c55; - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c56); } - } - if (s3 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c163(); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsePN_CHARS_BASE() { - var s0, s1, s2; - - s0 = peg$currPos; - if (peg$c164.test(input.charAt(peg$currPos))) { - s1 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c165); } - } - if (s1 !== peg$FAILED) { - if (peg$c166.test(input.charAt(peg$currPos))) { - s2 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c167); } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c168(s1, s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - if (s0 === peg$FAILED) { - if (peg$c169.test(input.charAt(peg$currPos))) { - s0 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s0 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c170); } - } - } - - return s0; - } - - function peg$parsePN_CHARS_U() { - var s0; - - s0 = peg$parsePN_CHARS_BASE(); - if (s0 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 95) { - s0 = peg$c171; - peg$currPos++; - } else { - s0 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c172); } - } - } - - return s0; - } - - function peg$parsePN_CHARS() { - var s0; - - s0 = peg$parsePN_CHARS_U(); - if (s0 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 45) { - s0 = peg$c93; - peg$currPos++; - } else { - s0 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c94); } - } - if (s0 === peg$FAILED) { - if (peg$c87.test(input.charAt(peg$currPos))) { - s0 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s0 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - if (s0 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 183) { - s0 = peg$c173; - peg$currPos++; - } else { - s0 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c174); } - } - if (s0 === peg$FAILED) { - if (peg$c175.test(input.charAt(peg$currPos))) { - s0 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s0 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c176); } - } - if (s0 === peg$FAILED) { - if (peg$c177.test(input.charAt(peg$currPos))) { - s0 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s0 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c178); } - } - } - } - } - } - } - - return s0; - } - - function peg$parsePN_PREFIX() { - var s0, s1, s2, s3, s4, s5, s6, s7, s8; - - s0 = peg$currPos; - s1 = peg$currPos; - s2 = peg$parsePN_CHARS_BASE(); - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$parsePN_CHARS(); - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$parsePN_CHARS(); - } - if (s3 !== peg$FAILED) { - s4 = []; - s5 = peg$currPos; - s6 = []; - if (input.charCodeAt(peg$currPos) === 46) { - s7 = peg$c1; - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (input.charCodeAt(peg$currPos) === 46) { - s7 = peg$c1; - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - s7 = []; - s8 = peg$parsePN_CHARS(); - if (s8 !== peg$FAILED) { - while (s8 !== peg$FAILED) { - s7.push(s8); - s8 = peg$parsePN_CHARS(); - } - } else { - s7 = peg$FAILED; - } - if (s7 !== peg$FAILED) { - s6 = [s6, s7]; - s5 = s6; - } else { - peg$currPos = s5; - s5 = peg$FAILED; - } - } else { - peg$currPos = s5; - s5 = peg$FAILED; - } - while (s5 !== peg$FAILED) { - s4.push(s5); - s5 = peg$currPos; - s6 = []; - if (input.charCodeAt(peg$currPos) === 46) { - s7 = peg$c1; - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - if (input.charCodeAt(peg$currPos) === 46) { - s7 = peg$c1; - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - s7 = []; - s8 = peg$parsePN_CHARS(); - if (s8 !== peg$FAILED) { - while (s8 !== peg$FAILED) { - s7.push(s8); - s8 = peg$parsePN_CHARS(); - } - } else { - s7 = peg$FAILED; - } - if (s7 !== peg$FAILED) { - s6 = [s6, s7]; - s5 = s6; - } else { - peg$currPos = s5; - s5 = peg$FAILED; - } - } else { - peg$currPos = s5; - s5 = peg$FAILED; - } - } - if (s4 !== peg$FAILED) { - s2 = [s2, s3, s4]; - s1 = s2; - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - if (s1 !== peg$FAILED) { - s0 = input.substring(s0, peg$currPos); - } else { - s0 = s1; - } - - return s0; - } - - function peg$parsePN_LOCAL() { - var s0, s1, s2, s3, s4, s5, s6, s7; - - s0 = peg$currPos; - s1 = peg$parsePN_CHARS_U(); - if (s1 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 58) { - s1 = peg$c80; - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c81); } - } - if (s1 === peg$FAILED) { - if (peg$c87.test(input.charAt(peg$currPos))) { - s1 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c88); } - } - if (s1 === peg$FAILED) { - s1 = peg$parsePLX(); - } - } - } - if (s1 !== peg$FAILED) { - s2 = []; - s3 = peg$parsePN_CHARS(); - if (s3 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 58) { - s3 = peg$c80; - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c81); } - } - if (s3 === peg$FAILED) { - s3 = peg$parsePLX(); - } - } - while (s3 !== peg$FAILED) { - s2.push(s3); - s3 = peg$parsePN_CHARS(); - if (s3 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 58) { - s3 = peg$c80; - peg$currPos++; - } else { - s3 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c81); } - } - if (s3 === peg$FAILED) { - s3 = peg$parsePLX(); - } - } - } - if (s2 !== peg$FAILED) { - s3 = []; - s4 = peg$currPos; - s5 = []; - if (input.charCodeAt(peg$currPos) === 46) { - s6 = peg$c1; - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s6 !== peg$FAILED) { - while (s6 !== peg$FAILED) { - s5.push(s6); - if (input.charCodeAt(peg$currPos) === 46) { - s6 = peg$c1; - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - } - } else { - s5 = peg$FAILED; - } - if (s5 !== peg$FAILED) { - s6 = []; - s7 = peg$parsePN_CHARS(); - if (s7 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 58) { - s7 = peg$c80; - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c81); } - } - if (s7 === peg$FAILED) { - s7 = peg$parsePLX(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - s7 = peg$parsePN_CHARS(); - if (s7 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 58) { - s7 = peg$c80; - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c81); } - } - if (s7 === peg$FAILED) { - s7 = peg$parsePLX(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c179(s1, s2, s5, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - while (s4 !== peg$FAILED) { - s3.push(s4); - s4 = peg$currPos; - s5 = []; - if (input.charCodeAt(peg$currPos) === 46) { - s6 = peg$c1; - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - if (s6 !== peg$FAILED) { - while (s6 !== peg$FAILED) { - s5.push(s6); - if (input.charCodeAt(peg$currPos) === 46) { - s6 = peg$c1; - peg$currPos++; - } else { - s6 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c2); } - } - } - } else { - s5 = peg$FAILED; - } - if (s5 !== peg$FAILED) { - s6 = []; - s7 = peg$parsePN_CHARS(); - if (s7 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 58) { - s7 = peg$c80; - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c81); } - } - if (s7 === peg$FAILED) { - s7 = peg$parsePLX(); - } - } - if (s7 !== peg$FAILED) { - while (s7 !== peg$FAILED) { - s6.push(s7); - s7 = peg$parsePN_CHARS(); - if (s7 === peg$FAILED) { - if (input.charCodeAt(peg$currPos) === 58) { - s7 = peg$c80; - peg$currPos++; - } else { - s7 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c81); } - } - if (s7 === peg$FAILED) { - s7 = peg$parsePLX(); - } - } - } - } else { - s6 = peg$FAILED; - } - if (s6 !== peg$FAILED) { - peg$savedPos = s4; - s5 = peg$c179(s1, s2, s5, s6); - s4 = s5; - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } else { - peg$currPos = s4; - s4 = peg$FAILED; - } - } - if (s3 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c180(s1, s2, s3); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - function peg$parsePLX() { - var s0; - - s0 = peg$parsePERCENT(); - if (s0 === peg$FAILED) { - s0 = peg$parsePN_LOCAL_ESC(); - } - - return s0; - } - - function peg$parsePERCENT() { - var s0, s1, s2, s3, s4; - - s0 = peg$currPos; - s1 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 37) { - s2 = peg$c181; - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c182); } - } - if (s2 !== peg$FAILED) { - s3 = peg$parseHEX(); - if (s3 !== peg$FAILED) { - s4 = peg$parseHEX(); - if (s4 !== peg$FAILED) { - s2 = [s2, s3, s4]; - s1 = s2; - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - } else { - peg$currPos = s1; - s1 = peg$FAILED; - } - if (s1 !== peg$FAILED) { - s0 = input.substring(s0, peg$currPos); - } else { - s0 = s1; - } - - return s0; - } - - function peg$parseHEX() { - var s0; - - if (peg$c183.test(input.charAt(peg$currPos))) { - s0 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s0 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c184); } - } - - return s0; - } - - function peg$parsePN_LOCAL_ESC() { - var s0, s1, s2; - - s0 = peg$currPos; - if (input.charCodeAt(peg$currPos) === 92) { - s1 = peg$c185; - peg$currPos++; - } else { - s1 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c186); } - } - if (s1 !== peg$FAILED) { - if (peg$c187.test(input.charAt(peg$currPos))) { - s2 = input.charAt(peg$currPos); - peg$currPos++; - } else { - s2 = peg$FAILED; - if (peg$silentFails === 0) { peg$fail(peg$c188); } - } - if (s2 !== peg$FAILED) { - peg$savedPos = s0; - s1 = peg$c3(s2); - s0 = s1; - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - } else { - peg$currPos = s0; - s0 = peg$FAILED; - } - - return s0; - } - - - var isBrowser=new Function("try {return this===window;}catch(e){ return false;}"); - var URL = isBrowser() ? window.URL : (__webpack_require__(/*! url */ "../rdflib/node_modules/url/url.js").URL); - var isIRI = function(a){return a.match(/^[a-z](.*?):(.+?)/g);}; - function createObject(property,value){var a={};a[property]=value;return a;} - var context = { - base : [], - data : {}, - addBase : function(uri){ - if(context.base.length===0){ - context.base.push(uri); - return; - } - const last = context.base[context.base.length-1]; - if(last!==uri) context.base.push(new URL(uri,last).toString()); - }, - addPrefix : function(prefix,uri){ - const list = context.data[prefix]; - if(list===undefined){ - context.data[prefix] = [{uri:uri,count:0}]; - }else if(list[list.length-1].uri!==uri){ - list.push({uri:uri,count:0}); - } - }, - hasPrefix : function(prefix){ - return this.data[prefix]!==undefined; - }, - resolve : function(pname,force){ - const prefix = Object.keys(context.data).find(key=>pname.indexOf(key+":")===0); - if(prefix!==undefined) { - const list = context.data[prefix]; - if(list.length===1 && force!==true && isIRI(list[0].uri)) return pname; - const uri = list[list.length-1].uri; - return pname.replace(prefix+":",uri); - }else{ - var base = context.base.length === 0 ? options.baseIRI : context.base[context.base.length-1]; - if(!base || pname.match(/^(http:|https:|urn:|file:)/)) return pname; - if(pname.indexOf("//")===0 && base) return base.split("//")[0]+pname; - return new URL(pname,base).toString(); - } - }, - increment : function(prefix){ - const list = context.data[prefix]; - if(list!==undefined)list[list.length-1].count++; - }, - decrement : function(prefix){ - const list = context.data[prefix]; - if(list!==undefined)list[list.length-1].count--; - }, - toJSON : function(){ - const root = {}; - if(context.base.length>0){ - if(root["@context"]===undefined)root["@context"] = {}; - root["@context"]["@base"] = context.base[0]; - } - Object.keys(context.data).forEach(key=>{ - const head = context.data[key][0]; - if(head.uri==="http://www.w3.org/2001/XMLSchema#" && head.count < 1) return; - if(!isIRI(head.uri)) return; - if(root["@context"]===undefined) root["@context"] = {}; - root["@context"][key] = head.uri; - }); - return root; - } - }; - - function expandList(container,force){ - if(container["@list"]===undefined) return container; - if(!force && !container["@list"].find(x=>x["@list"]!==undefined)) return container; - - if(container["@list"].length===0) - return {"@id" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"}; - - var root = {}; - var focus = null; - container["@list"].forEach(b=>{ - if(focus===null) focus = root; - else { - focus["http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"] = {}; - focus = focus["http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"]; - } - focus["http://www.w3.org/1999/02/22-rdf-syntax-ns#first"] = expandList(b,true); - focus["http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"] = { - "@id" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil" - }; - }); - return root; - } - - - peg$result = peg$startRuleFunction(); - - if (peg$result !== peg$FAILED && peg$currPos === input.length) { - return peg$result; - } else { - if (peg$result !== peg$FAILED && peg$currPos < input.length) { - peg$fail(peg$endExpectation()); - } - - throw peg$buildStructuredError( - peg$maxFailExpected, - peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null, - peg$maxFailPos < input.length - ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1) - : peg$computeLocation(peg$maxFailPos, peg$maxFailPos) - ); - } - } - - return { - SyntaxError: peg$SyntaxError, - parse: peg$parse - }; -}); - - -/***/ }), - -/***/ "../rdflib/node_modules/@xmldom/xmldom/lib/conventions.js": -/*!****************************************************************!*\ - !*** ../rdflib/node_modules/@xmldom/xmldom/lib/conventions.js ***! - \****************************************************************/ -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -/** - * Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes. - * - * Works with anything that has a `length` property and index access properties, including NodeList. - * - * @template {unknown} T - * @param {Array | ({length:number, [number]: T})} list - * @param {function (item: T, index: number, list:Array | ({length:number, [number]: T})):boolean} predicate - * @param {Partial>?} ac `Array.prototype` by default, - * allows injecting a custom implementation in tests - * @returns {T | undefined} - * - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find - * @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find - */ -function find(list, predicate, ac) { - if (ac === undefined) { - ac = Array.prototype; - } - if (list && typeof ac.find === 'function') { - return ac.find.call(list, predicate); - } - for (var i = 0; i < list.length; i++) { - if (Object.prototype.hasOwnProperty.call(list, i)) { - var item = list[i]; - if (predicate.call(undefined, item, i, list)) { - return item; - } - } - } -} - -/** - * "Shallow freezes" an object to render it immutable. - * Uses `Object.freeze` if available, - * otherwise the immutability is only in the type. - * - * Is used to create "enum like" objects. - * - * @template T - * @param {T} object the object to freeze - * @param {Pick = Object} oc `Object` by default, - * allows to inject custom object constructor for tests - * @returns {Readonly} - * - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze - */ -function freeze(object, oc) { - if (oc === undefined) { - oc = Object - } - return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object -} - -/** - * Since we can not rely on `Object.assign` we provide a simplified version - * that is sufficient for our needs. - * - * @param {Object} target - * @param {Object | null | undefined} source - * - * @returns {Object} target - * @throws TypeError if target is not an object - * - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign - */ -function assign(target, source) { - if (target === null || typeof target !== 'object') { - throw new TypeError('target is not an object') - } - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - return target -} - -/** - * All mime types that are allowed as input to `DOMParser.parseFromString` - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN - * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec - * @see DOMParser.prototype.parseFromString - */ -var MIME_TYPE = freeze({ - /** - * `text/html`, the only mime type that triggers treating an XML document as HTML. - * - * @see DOMParser.SupportedType.isHTML - * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration - * @see https://en.wikipedia.org/wiki/HTML Wikipedia - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN - * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec - */ - HTML: 'text/html', - - /** - * Helper method to check a mime type if it indicates an HTML document - * - * @param {string} [value] - * @returns {boolean} - * - * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration - * @see https://en.wikipedia.org/wiki/HTML Wikipedia - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN - * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */ - isHTML: function (value) { - return value === MIME_TYPE.HTML - }, - - /** - * `application/xml`, the standard mime type for XML documents. - * - * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration - * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303 - * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia - */ - XML_APPLICATION: 'application/xml', - - /** - * `text/html`, an alias for `application/xml`. - * - * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303 - * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration - * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia - */ - XML_TEXT: 'text/xml', - - /** - * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace, - * but is parsed as an XML document. - * - * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration - * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec - * @see https://en.wikipedia.org/wiki/XHTML Wikipedia - */ - XML_XHTML_APPLICATION: 'application/xhtml+xml', - - /** - * `image/svg+xml`, - * - * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration - * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1 - * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia - */ - XML_SVG_IMAGE: 'image/svg+xml', -}) - -/** - * Namespaces that are used in this code base. - * - * @see http://www.w3.org/TR/REC-xml-names - */ -var NAMESPACE = freeze({ - /** - * The XHTML namespace. - * - * @see http://www.w3.org/1999/xhtml - */ - HTML: 'http://www.w3.org/1999/xhtml', - - /** - * Checks if `uri` equals `NAMESPACE.HTML`. - * - * @param {string} [uri] - * - * @see NAMESPACE.HTML - */ - isHTML: function (uri) { - return uri === NAMESPACE.HTML - }, - - /** - * The SVG namespace. - * - * @see http://www.w3.org/2000/svg - */ - SVG: 'http://www.w3.org/2000/svg', - - /** - * The `xml:` namespace. - * - * @see http://www.w3.org/XML/1998/namespace - */ - XML: 'http://www.w3.org/XML/1998/namespace', - - /** - * The `xmlns:` namespace - * - * @see https://www.w3.org/2000/xmlns/ - */ - XMLNS: 'http://www.w3.org/2000/xmlns/', -}) - -exports.assign = assign; -exports.find = find; -exports.freeze = freeze; -exports.MIME_TYPE = MIME_TYPE; -exports.NAMESPACE = NAMESPACE; - - -/***/ }), - -/***/ "../rdflib/node_modules/@xmldom/xmldom/lib/dom-parser.js": -/*!***************************************************************!*\ - !*** ../rdflib/node_modules/@xmldom/xmldom/lib/dom-parser.js ***! - \***************************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var conventions = __webpack_require__(/*! ./conventions */ "../rdflib/node_modules/@xmldom/xmldom/lib/conventions.js"); -var dom = __webpack_require__(/*! ./dom */ "../rdflib/node_modules/@xmldom/xmldom/lib/dom.js") -var entities = __webpack_require__(/*! ./entities */ "../rdflib/node_modules/@xmldom/xmldom/lib/entities.js"); -var sax = __webpack_require__(/*! ./sax */ "../rdflib/node_modules/@xmldom/xmldom/lib/sax.js"); - -var DOMImplementation = dom.DOMImplementation; - -var NAMESPACE = conventions.NAMESPACE; - -var ParseError = sax.ParseError; -var XMLReader = sax.XMLReader; - -/** - * Normalizes line ending according to https://www.w3.org/TR/xml11/#sec-line-ends: - * - * > XML parsed entities are often stored in computer files which, - * > for editing convenience, are organized into lines. - * > These lines are typically separated by some combination - * > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA). - * > - * > To simplify the tasks of applications, the XML processor must behave - * > as if it normalized all line breaks in external parsed entities (including the document entity) - * > on input, before parsing, by translating all of the following to a single #xA character: - * > - * > 1. the two-character sequence #xD #xA - * > 2. the two-character sequence #xD #x85 - * > 3. the single character #x85 - * > 4. the single character #x2028 - * > 5. any #xD character that is not immediately followed by #xA or #x85. - * - * @param {string} input - * @returns {string} - */ -function normalizeLineEndings(input) { - return input - .replace(/\r[\n\u0085]/g, '\n') - .replace(/[\r\u0085\u2028]/g, '\n') -} - -/** - * @typedef Locator - * @property {number} [columnNumber] - * @property {number} [lineNumber] - */ - -/** - * @typedef DOMParserOptions - * @property {DOMHandler} [domBuilder] - * @property {Function} [errorHandler] - * @property {(string) => string} [normalizeLineEndings] used to replace line endings before parsing - * defaults to `normalizeLineEndings` - * @property {Locator} [locator] - * @property {Record} [xmlns] - * - * @see normalizeLineEndings - */ - -/** - * The DOMParser interface provides the ability to parse XML or HTML source code - * from a string into a DOM `Document`. - * - * _xmldom is different from the spec in that it allows an `options` parameter, - * to override the default behavior._ - * - * @param {DOMParserOptions} [options] - * @constructor - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser - * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization - */ -function DOMParser(options){ - this.options = options ||{locator:{}}; -} - -DOMParser.prototype.parseFromString = function(source,mimeType){ - var options = this.options; - var sax = new XMLReader(); - var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler - var errorHandler = options.errorHandler; - var locator = options.locator; - var defaultNSMap = options.xmlns||{}; - var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1; - var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES; - if(locator){ - domBuilder.setDocumentLocator(locator) - } - - sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); - sax.domBuilder = options.domBuilder || domBuilder; - if(isHTML){ - defaultNSMap[''] = NAMESPACE.HTML; - } - defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML; - var normalize = options.normalizeLineEndings || normalizeLineEndings; - if (source && typeof source === 'string') { - sax.parse( - normalize(source), - defaultNSMap, - entityMap - ) - } else { - sax.errorHandler.error('invalid doc source') - } - return domBuilder.doc; -} -function buildErrorHandler(errorImpl,domBuilder,locator){ - if(!errorImpl){ - if(domBuilder instanceof DOMHandler){ - return domBuilder; - } - errorImpl = domBuilder ; - } - var errorHandler = {} - var isCallback = errorImpl instanceof Function; - locator = locator||{} - function build(key){ - var fn = errorImpl[key]; - if(!fn && isCallback){ - fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl; - } - errorHandler[key] = fn && function(msg){ - fn('[xmldom '+key+']\t'+msg+_locator(locator)); - }||function(){}; - } - build('warning'); - build('error'); - build('fatalError'); - return errorHandler; -} - -//console.log('#\n\n\n\n\n\n\n####') -/** - * +ContentHandler+ErrorHandler - * +LexicalHandler+EntityResolver2 - * -DeclHandler-DTDHandler - * - * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler - * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2 - * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html - */ -function DOMHandler() { - this.cdata = false; -} -function position(locator,node){ - node.lineNumber = locator.lineNumber; - node.columnNumber = locator.columnNumber; -} -/** - * @see org.xml.sax.ContentHandler#startDocument - * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html - */ -DOMHandler.prototype = { - startDocument : function() { - this.doc = new DOMImplementation().createDocument(null, null, null); - if (this.locator) { - this.doc.documentURI = this.locator.systemId; - } - }, - startElement:function(namespaceURI, localName, qName, attrs) { - var doc = this.doc; - var el = doc.createElementNS(namespaceURI, qName||localName); - var len = attrs.length; - appendElement(this, el); - this.currentElement = el; - - this.locator && position(this.locator,el) - for (var i = 0 ; i < len; i++) { - var namespaceURI = attrs.getURI(i); - var value = attrs.getValue(i); - var qName = attrs.getQName(i); - var attr = doc.createAttributeNS(namespaceURI, qName); - this.locator &&position(attrs.getLocator(i),attr); - attr.value = attr.nodeValue = value; - el.setAttributeNode(attr) - } - }, - endElement:function(namespaceURI, localName, qName) { - var current = this.currentElement - var tagName = current.tagName; - this.currentElement = current.parentNode; - }, - startPrefixMapping:function(prefix, uri) { - }, - endPrefixMapping:function(prefix) { - }, - processingInstruction:function(target, data) { - var ins = this.doc.createProcessingInstruction(target, data); - this.locator && position(this.locator,ins) - appendElement(this, ins); - }, - ignorableWhitespace:function(ch, start, length) { - }, - characters:function(chars, start, length) { - chars = _toString.apply(this,arguments) - //console.log(chars) - if(chars){ - if (this.cdata) { - var charNode = this.doc.createCDATASection(chars); - } else { - var charNode = this.doc.createTextNode(chars); - } - if(this.currentElement){ - this.currentElement.appendChild(charNode); - }else if(/^\s*$/.test(chars)){ - this.doc.appendChild(charNode); - //process xml - } - this.locator && position(this.locator,charNode) - } - }, - skippedEntity:function(name) { - }, - endDocument:function() { - this.doc.normalize(); - }, - setDocumentLocator:function (locator) { - if(this.locator = locator){// && !('lineNumber' in locator)){ - locator.lineNumber = 0; - } - }, - //LexicalHandler - comment:function(chars, start, length) { - chars = _toString.apply(this,arguments) - var comm = this.doc.createComment(chars); - this.locator && position(this.locator,comm) - appendElement(this, comm); - }, - - startCDATA:function() { - //used in characters() methods - this.cdata = true; - }, - endCDATA:function() { - this.cdata = false; - }, - - startDTD:function(name, publicId, systemId) { - var impl = this.doc.implementation; - if (impl && impl.createDocumentType) { - var dt = impl.createDocumentType(name, publicId, systemId); - this.locator && position(this.locator,dt) - appendElement(this, dt); - this.doc.doctype = dt; - } - }, - /** - * @see org.xml.sax.ErrorHandler - * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html - */ - warning:function(error) { - console.warn('[xmldom warning]\t'+error,_locator(this.locator)); - }, - error:function(error) { - console.error('[xmldom error]\t'+error,_locator(this.locator)); - }, - fatalError:function(error) { - throw new ParseError(error, this.locator); - } -} -function _locator(l){ - if(l){ - return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']' - } -} -function _toString(chars,start,length){ - if(typeof chars == 'string'){ - return chars.substr(start,length) - }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") - if(chars.length >= start+length || start){ - return new java.lang.String(chars,start,length)+''; - } - return chars; - } -} - -/* - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html - * used method of org.xml.sax.ext.LexicalHandler: - * #comment(chars, start, length) - * #startCDATA() - * #endCDATA() - * #startDTD(name, publicId, systemId) - * - * - * IGNORED method of org.xml.sax.ext.LexicalHandler: - * #endDTD() - * #startEntity(name) - * #endEntity(name) - * - * - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html - * IGNORED method of org.xml.sax.ext.DeclHandler - * #attributeDecl(eName, aName, type, mode, value) - * #elementDecl(name, model) - * #externalEntityDecl(name, publicId, systemId) - * #internalEntityDecl(name, value) - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html - * IGNORED method of org.xml.sax.EntityResolver2 - * #resolveEntity(String name,String publicId,String baseURI,String systemId) - * #resolveEntity(publicId, systemId) - * #getExternalSubset(name, baseURI) - * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html - * IGNORED method of org.xml.sax.DTDHandler - * #notationDecl(name, publicId, systemId) {}; - * #unparsedEntityDecl(name, publicId, systemId, notationName) {}; - */ -"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){ - DOMHandler.prototype[key] = function(){return null} -}) - -/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */ -function appendElement (hander,node) { - if (!hander.currentElement) { - hander.doc.appendChild(node); - } else { - hander.currentElement.appendChild(node); - } -}//appendChild and setAttributeNS are preformance key - -exports.__DOMHandler = DOMHandler; -exports.normalizeLineEndings = normalizeLineEndings; -exports.DOMParser = DOMParser; - - -/***/ }), - -/***/ "../rdflib/node_modules/@xmldom/xmldom/lib/dom.js": -/*!********************************************************!*\ - !*** ../rdflib/node_modules/@xmldom/xmldom/lib/dom.js ***! - \********************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var conventions = __webpack_require__(/*! ./conventions */ "../rdflib/node_modules/@xmldom/xmldom/lib/conventions.js"); - -var find = conventions.find; -var NAMESPACE = conventions.NAMESPACE; - -/** - * A prerequisite for `[].filter`, to drop elements that are empty - * @param {string} input - * @returns {boolean} - */ -function notEmptyString (input) { - return input !== '' -} -/** - * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace - * @see https://infra.spec.whatwg.org/#ascii-whitespace - * - * @param {string} input - * @returns {string[]} (can be empty) - */ -function splitOnASCIIWhitespace(input) { - // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE - return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [] -} - -/** - * Adds element as a key to current if it is not already present. - * - * @param {Record} current - * @param {string} element - * @returns {Record} - */ -function orderedSetReducer (current, element) { - if (!current.hasOwnProperty(element)) { - current[element] = true; - } - return current; -} - -/** - * @see https://infra.spec.whatwg.org/#ordered-set - * @param {string} input - * @returns {string[]} - */ -function toOrderedSet(input) { - if (!input) return []; - var list = splitOnASCIIWhitespace(input); - return Object.keys(list.reduce(orderedSetReducer, {})) -} - -/** - * Uses `list.indexOf` to implement something like `Array.prototype.includes`, - * which we can not rely on being available. - * - * @param {any[]} list - * @returns {function(any): boolean} - */ -function arrayIncludes (list) { - return function(element) { - return list && list.indexOf(element) !== -1; - } -} - -function copy(src,dest){ - for(var p in src){ - if (Object.prototype.hasOwnProperty.call(src, p)) { - dest[p] = src[p]; - } - } -} - -/** -^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));? -^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));? - */ -function _extends(Class,Super){ - var pt = Class.prototype; - if(!(pt instanceof Super)){ - function t(){}; - t.prototype = Super.prototype; - t = new t(); - copy(pt,t); - Class.prototype = pt = t; - } - if(pt.constructor != Class){ - if(typeof Class != 'function'){ - console.error("unknown Class:"+Class) - } - pt.constructor = Class - } -} - -// Node Types -var NodeType = {} -var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; -var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; -var TEXT_NODE = NodeType.TEXT_NODE = 3; -var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; -var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; -var ENTITY_NODE = NodeType.ENTITY_NODE = 6; -var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; -var COMMENT_NODE = NodeType.COMMENT_NODE = 8; -var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; -var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; -var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; -var NOTATION_NODE = NodeType.NOTATION_NODE = 12; - -// ExceptionCode -var ExceptionCode = {} -var ExceptionMessage = {}; -var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1); -var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2); -var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3); -var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4); -var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5); -var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6); -var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7); -var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8); -var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9); -var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10); -//level2 -var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11); -var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12); -var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13); -var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); -var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); - -/** - * DOM Level 2 - * Object DOMException - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html - */ -function DOMException(code, message) { - if(message instanceof Error){ - var error = message; - }else{ - error = this; - Error.call(this, ExceptionMessage[code]); - this.message = ExceptionMessage[code]; - if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException); - } - error.code = code; - if(message) this.message = this.message + ": " + message; - return error; -}; -DOMException.prototype = Error.prototype; -copy(ExceptionCode,DOMException) - -/** - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177 - * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live. - * The items in the NodeList are accessible via an integral index, starting from 0. - */ -function NodeList() { -}; -NodeList.prototype = { - /** - * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive. - * @standard level1 - */ - length:0, - /** - * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null. - * @standard level1 - * @param index unsigned long - * Index into the collection. - * @return Node - * The node at the indexth position in the NodeList, or null if that is not a valid index. - */ - item: function(index) { - return this[index] || null; - }, - toString:function(isHTML,nodeFilter){ - for(var buf = [], i = 0;i=0){ - var lastIndex = list.length-1 - while(i0 || key == 'xmlns'){ -// return null; -// } - //console.log() - var i = this.length; - while(i--){ - var attr = this[i]; - //console.log(attr.nodeName,key) - if(attr.nodeName == key){ - return attr; - } - } - }, - setNamedItem: function(attr) { - var el = attr.ownerElement; - if(el && el!=this._ownerElement){ - throw new DOMException(INUSE_ATTRIBUTE_ERR); - } - var oldAttr = this.getNamedItem(attr.nodeName); - _addNamedNode(this._ownerElement,this,attr,oldAttr); - return oldAttr; - }, - /* returns Node */ - setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR - var el = attr.ownerElement, oldAttr; - if(el && el!=this._ownerElement){ - throw new DOMException(INUSE_ATTRIBUTE_ERR); - } - oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName); - _addNamedNode(this._ownerElement,this,attr,oldAttr); - return oldAttr; - }, - - /* returns Node */ - removeNamedItem: function(key) { - var attr = this.getNamedItem(key); - _removeNamedNode(this._ownerElement,this,attr); - return attr; - - - },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR - - //for level2 - removeNamedItemNS:function(namespaceURI,localName){ - var attr = this.getNamedItemNS(namespaceURI,localName); - _removeNamedNode(this._ownerElement,this,attr); - return attr; - }, - getNamedItemNS: function(namespaceURI, localName) { - var i = this.length; - while(i--){ - var node = this[i]; - if(node.localName == localName && node.namespaceURI == namespaceURI){ - return node; - } - } - return null; - } -}; - -/** - * The DOMImplementation interface represents an object providing methods - * which are not dependent on any particular document. - * Such an object is returned by the `Document.implementation` property. - * - * __The individual methods describe the differences compared to the specs.__ - * - * @constructor - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN - * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial) - * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core - * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core - * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard - */ -function DOMImplementation() { -} - -DOMImplementation.prototype = { - /** - * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported. - * The different implementations fairly diverged in what kind of features were reported. - * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use. - * - * @deprecated It is deprecated and modern browsers return true in all cases. - * - * @param {string} feature - * @param {string} [version] - * @returns {boolean} always true - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN - * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core - * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard - */ - hasFeature: function(feature, version) { - return true; - }, - /** - * Creates an XML Document object of the specified type with its document element. - * - * __It behaves slightly different from the description in the living standard__: - * - There is no interface/class `XMLDocument`, it returns a `Document` instance. - * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared. - * - this implementation is not validating names or qualified names - * (when parsing XML strings, the SAX parser takes care of that) - * - * @param {string|null} namespaceURI - * @param {string} qualifiedName - * @param {DocumentType=null} doctype - * @returns {Document} - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN - * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial) - * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core - * - * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract - * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names - * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names - */ - createDocument: function(namespaceURI, qualifiedName, doctype){ - var doc = new Document(); - doc.implementation = this; - doc.childNodes = new NodeList(); - doc.doctype = doctype || null; - if (doctype){ - doc.appendChild(doctype); - } - if (qualifiedName){ - var root = doc.createElementNS(namespaceURI, qualifiedName); - doc.appendChild(root); - } - return doc; - }, - /** - * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`. - * - * __This behavior is slightly different from the in the specs__: - * - this implementation is not validating names or qualified names - * (when parsing XML strings, the SAX parser takes care of that) - * - * @param {string} qualifiedName - * @param {string} [publicId] - * @param {string} [systemId] - * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation - * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()` - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN - * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core - * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard - * - * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract - * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names - * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names - */ - createDocumentType: function(qualifiedName, publicId, systemId){ - var node = new DocumentType(); - node.name = qualifiedName; - node.nodeName = qualifiedName; - node.publicId = publicId || ''; - node.systemId = systemId || ''; - - return node; - } -}; - - -/** - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 - */ - -function Node() { -}; - -Node.prototype = { - firstChild : null, - lastChild : null, - previousSibling : null, - nextSibling : null, - attributes : null, - parentNode : null, - childNodes : null, - ownerDocument : null, - nodeValue : null, - namespaceURI : null, - prefix : null, - localName : null, - // Modified in DOM Level 2: - insertBefore:function(newChild, refChild){//raises - return _insertBefore(this,newChild,refChild); - }, - replaceChild:function(newChild, oldChild){//raises - _insertBefore(this, newChild,oldChild, assertPreReplacementValidityInDocument); - if(oldChild){ - this.removeChild(oldChild); - } - }, - removeChild:function(oldChild){ - return _removeChild(this,oldChild); - }, - appendChild:function(newChild){ - return this.insertBefore(newChild,null); - }, - hasChildNodes:function(){ - return this.firstChild != null; - }, - cloneNode:function(deep){ - return cloneNode(this.ownerDocument||this,this,deep); - }, - // Modified in DOM Level 2: - normalize:function(){ - var child = this.firstChild; - while(child){ - var next = child.nextSibling; - if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){ - this.removeChild(next); - child.appendData(next.data); - }else{ - child.normalize(); - child = next; - } - } - }, - // Introduced in DOM Level 2: - isSupported:function(feature, version){ - return this.ownerDocument.implementation.hasFeature(feature,version); - }, - // Introduced in DOM Level 2: - hasAttributes:function(){ - return this.attributes.length>0; - }, - /** - * Look up the prefix associated to the given namespace URI, starting from this node. - * **The default namespace declarations are ignored by this method.** - * See Namespace Prefix Lookup for details on the algorithm used by this method. - * - * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._ - * - * @param {string | null} namespaceURI - * @returns {string | null} - * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix - * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo - * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix - * @see https://github.com/xmldom/xmldom/issues/322 - */ - lookupPrefix:function(namespaceURI){ - var el = this; - while(el){ - var map = el._nsMap; - //console.dir(map) - if(map){ - for(var n in map){ - if (Object.prototype.hasOwnProperty.call(map, n) && map[n] === namespaceURI) { - return n; - } - } - } - el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; - } - return null; - }, - // Introduced in DOM Level 3: - lookupNamespaceURI:function(prefix){ - var el = this; - while(el){ - var map = el._nsMap; - //console.dir(map) - if(map){ - if(Object.prototype.hasOwnProperty.call(map, prefix)){ - return map[prefix] ; - } - } - el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; - } - return null; - }, - // Introduced in DOM Level 3: - isDefaultNamespace:function(namespaceURI){ - var prefix = this.lookupPrefix(namespaceURI); - return prefix == null; - } -}; - - -function _xmlEncoder(c){ - return c == '<' && '<' || - c == '>' && '>' || - c == '&' && '&' || - c == '"' && '"' || - '&#'+c.charCodeAt()+';' -} - - -copy(NodeType,Node); -copy(NodeType,Node.prototype); - -/** - * @param callback return true for continue,false for break - * @return boolean true: break visit; - */ -function _visitNode(node,callback){ - if(callback(node)){ - return true; - } - if(node = node.firstChild){ - do{ - if(_visitNode(node,callback)){return true} - }while(node=node.nextSibling) - } -} - - - -function Document(){ - this.ownerDocument = this; -} - -function _onAddAttribute(doc,el,newAttr){ - doc && doc._inc++; - var ns = newAttr.namespaceURI ; - if(ns === NAMESPACE.XMLNS){ - //update namespace - el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value - } -} - -function _onRemoveAttribute(doc,el,newAttr,remove){ - doc && doc._inc++; - var ns = newAttr.namespaceURI ; - if(ns === NAMESPACE.XMLNS){ - //update namespace - delete el._nsMap[newAttr.prefix?newAttr.localName:''] - } -} - -/** - * Updates `el.childNodes`, updating the indexed items and it's `length`. - * Passing `newChild` means it will be appended. - * Otherwise it's assumed that an item has been removed, - * and `el.firstNode` and it's `.nextSibling` are used - * to walk the current list of child nodes. - * - * @param {Document} doc - * @param {Node} el - * @param {Node} [newChild] - * @private - */ -function _onUpdateChild (doc, el, newChild) { - if(doc && doc._inc){ - doc._inc++; - //update childNodes - var cs = el.childNodes; - if (newChild) { - cs[cs.length++] = newChild; - } else { - var child = el.firstChild; - var i = 0; - while (child) { - cs[i++] = child; - child = child.nextSibling; - } - cs.length = i; - delete cs[cs.length]; - } - } -} - -/** - * Removes the connections between `parentNode` and `child` - * and any existing `child.previousSibling` or `child.nextSibling`. - * - * @see https://github.com/xmldom/xmldom/issues/135 - * @see https://github.com/xmldom/xmldom/issues/145 - * - * @param {Node} parentNode - * @param {Node} child - * @returns {Node} the child that was removed. - * @private - */ -function _removeChild (parentNode, child) { - var previous = child.previousSibling; - var next = child.nextSibling; - if (previous) { - previous.nextSibling = next; - } else { - parentNode.firstChild = next; - } - if (next) { - next.previousSibling = previous; - } else { - parentNode.lastChild = previous; - } - child.parentNode = null; - child.previousSibling = null; - child.nextSibling = null; - _onUpdateChild(parentNode.ownerDocument, parentNode); - return child; -} - -/** - * Returns `true` if `node` can be a parent for insertion. - * @param {Node} node - * @returns {boolean} - */ -function hasValidParentNodeType(node) { - return ( - node && - (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE) - ); -} - -/** - * Returns `true` if `node` can be inserted according to it's `nodeType`. - * @param {Node} node - * @returns {boolean} - */ -function hasInsertableNodeType(node) { - return ( - node && - (isElementNode(node) || - isTextNode(node) || - isDocTypeNode(node) || - node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || - node.nodeType === Node.COMMENT_NODE || - node.nodeType === Node.PROCESSING_INSTRUCTION_NODE) - ); -} - -/** - * Returns true if `node` is a DOCTYPE node - * @param {Node} node - * @returns {boolean} - */ -function isDocTypeNode(node) { - return node && node.nodeType === Node.DOCUMENT_TYPE_NODE; -} - -/** - * Returns true if the node is an element - * @param {Node} node - * @returns {boolean} - */ -function isElementNode(node) { - return node && node.nodeType === Node.ELEMENT_NODE; -} -/** - * Returns true if `node` is a text node - * @param {Node} node - * @returns {boolean} - */ -function isTextNode(node) { - return node && node.nodeType === Node.TEXT_NODE; -} - -/** - * Check if en element node can be inserted before `child`, or at the end if child is falsy, - * according to the presence and position of a doctype node on the same level. - * - * @param {Document} doc The document node - * @param {Node} child the node that would become the nextSibling if the element would be inserted - * @returns {boolean} `true` if an element can be inserted before child - * @private - * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - */ -function isElementInsertionPossible(doc, child) { - var parentChildNodes = doc.childNodes || []; - if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) { - return false; - } - var docTypeNode = find(parentChildNodes, isDocTypeNode); - return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); -} - -/** - * Check if en element node can be inserted before `child`, or at the end if child is falsy, - * according to the presence and position of a doctype node on the same level. - * - * @param {Node} doc The document node - * @param {Node} child the node that would become the nextSibling if the element would be inserted - * @returns {boolean} `true` if an element can be inserted before child - * @private - * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - */ -function isElementReplacementPossible(doc, child) { - var parentChildNodes = doc.childNodes || []; - - function hasElementChildThatIsNotChild(node) { - return isElementNode(node) && node !== child; - } - - if (find(parentChildNodes, hasElementChildThatIsNotChild)) { - return false; - } - var docTypeNode = find(parentChildNodes, isDocTypeNode); - return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); -} - -/** - * @private - * Steps 1-5 of the checks before inserting and before replacing a child are the same. - * - * @param {Node} parent the parent node to insert `node` into - * @param {Node} node the node to insert - * @param {Node=} child the node that should become the `nextSibling` of `node` - * @returns {Node} - * @throws DOMException for several node combinations that would create a DOM that is not well-formed. - * @throws DOMException if `child` is provided but is not a child of `parent`. - * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - * @see https://dom.spec.whatwg.org/#concept-node-replace - */ -function assertPreInsertionValidity1to5(parent, node, child) { - // 1. If `parent` is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException. - if (!hasValidParentNodeType(parent)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected parent node type ' + parent.nodeType); - } - // 2. If `node` is a host-including inclusive ancestor of `parent`, then throw a "HierarchyRequestError" DOMException. - // not implemented! - // 3. If `child` is non-null and its parent is not `parent`, then throw a "NotFoundError" DOMException. - if (child && child.parentNode !== parent) { - throw new DOMException(NOT_FOUND_ERR, 'child not in parent'); - } - if ( - // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException. - !hasInsertableNodeType(node) || - // 5. If either `node` is a Text node and `parent` is a document, - // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0 - // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE) - // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException. - (isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE) - ) { - throw new DOMException( - HIERARCHY_REQUEST_ERR, - 'Unexpected node type ' + node.nodeType + ' for parent node type ' + parent.nodeType - ); - } -} - -/** - * @private - * Step 6 of the checks before inserting and before replacing a child are different. - * - * @param {Document} parent the parent node to insert `node` into - * @param {Node} node the node to insert - * @param {Node | undefined} child the node that should become the `nextSibling` of `node` - * @returns {Node} - * @throws DOMException for several node combinations that would create a DOM that is not well-formed. - * @throws DOMException if `child` is provided but is not a child of `parent`. - * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - * @see https://dom.spec.whatwg.org/#concept-node-replace - */ -function assertPreInsertionValidityInDocument(parent, node, child) { - var parentChildNodes = parent.childNodes || []; - var nodeChildNodes = node.childNodes || []; - - // DocumentFragment - if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { - var nodeChildElements = nodeChildNodes.filter(isElementNode); - // If node has more than one element child or has a Text node child. - if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); - } - // Otherwise, if `node` has one element child and either `parent` has an element child, - // `child` is a doctype, or `child` is non-null and a doctype is following `child`. - if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); - } - } - // Element - if (isElementNode(node)) { - // `parent` has an element child, `child` is a doctype, - // or `child` is non-null and a doctype is following `child`. - if (!isElementInsertionPossible(parent, child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); - } - } - // DocumentType - if (isDocTypeNode(node)) { - // `parent` has a doctype child, - if (find(parentChildNodes, isDocTypeNode)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); - } - var parentElementChild = find(parentChildNodes, isElementNode); - // `child` is non-null and an element is preceding `child`, - if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); - } - // or `child` is null and `parent` has an element child. - if (!child && parentElementChild) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can not be appended since element is present'); - } - } -} - -/** - * @private - * Step 6 of the checks before inserting and before replacing a child are different. - * - * @param {Document} parent the parent node to insert `node` into - * @param {Node} node the node to insert - * @param {Node | undefined} child the node that should become the `nextSibling` of `node` - * @returns {Node} - * @throws DOMException for several node combinations that would create a DOM that is not well-formed. - * @throws DOMException if `child` is provided but is not a child of `parent`. - * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - * @see https://dom.spec.whatwg.org/#concept-node-replace - */ -function assertPreReplacementValidityInDocument(parent, node, child) { - var parentChildNodes = parent.childNodes || []; - var nodeChildNodes = node.childNodes || []; - - // DocumentFragment - if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { - var nodeChildElements = nodeChildNodes.filter(isElementNode); - // If `node` has more than one element child or has a Text node child. - if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); - } - // Otherwise, if `node` has one element child and either `parent` has an element child that is not `child` or a doctype is following `child`. - if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); - } - } - // Element - if (isElementNode(node)) { - // `parent` has an element child that is not `child` or a doctype is following `child`. - if (!isElementReplacementPossible(parent, child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); - } - } - // DocumentType - if (isDocTypeNode(node)) { - function hasDoctypeChildThatIsNotChild(node) { - return isDocTypeNode(node) && node !== child; - } - - // `parent` has a doctype child that is not `child`, - if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); - } - var parentElementChild = find(parentChildNodes, isElementNode); - // or an element is preceding `child`. - if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); - } - } -} - -/** - * @private - * @param {Node} parent the parent node to insert `node` into - * @param {Node} node the node to insert - * @param {Node=} child the node that should become the `nextSibling` of `node` - * @returns {Node} - * @throws DOMException for several node combinations that would create a DOM that is not well-formed. - * @throws DOMException if `child` is provided but is not a child of `parent`. - * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - */ -function _insertBefore(parent, node, child, _inDocumentAssertion) { - // To ensure pre-insertion validity of a node into a parent before a child, run these steps: - assertPreInsertionValidity1to5(parent, node, child); - - // If parent is a document, and any of the statements below, switched on the interface node implements, - // are true, then throw a "HierarchyRequestError" DOMException. - if (parent.nodeType === Node.DOCUMENT_NODE) { - (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child); - } - - var cp = node.parentNode; - if(cp){ - cp.removeChild(node);//remove and update - } - if(node.nodeType === DOCUMENT_FRAGMENT_NODE){ - var newFirst = node.firstChild; - if (newFirst == null) { - return node; - } - var newLast = node.lastChild; - }else{ - newFirst = newLast = node; - } - var pre = child ? child.previousSibling : parent.lastChild; - - newFirst.previousSibling = pre; - newLast.nextSibling = child; - - - if(pre){ - pre.nextSibling = newFirst; - }else{ - parent.firstChild = newFirst; - } - if(child == null){ - parent.lastChild = newLast; - }else{ - child.previousSibling = newLast; - } - do{ - newFirst.parentNode = parent; - }while(newFirst !== newLast && (newFirst= newFirst.nextSibling)) - _onUpdateChild(parent.ownerDocument||parent, parent); - //console.log(parent.lastChild.nextSibling == null) - if (node.nodeType == DOCUMENT_FRAGMENT_NODE) { - node.firstChild = node.lastChild = null; - } - return node; -} - -/** - * Appends `newChild` to `parentNode`. - * If `newChild` is already connected to a `parentNode` it is first removed from it. - * - * @see https://github.com/xmldom/xmldom/issues/135 - * @see https://github.com/xmldom/xmldom/issues/145 - * @param {Node} parentNode - * @param {Node} newChild - * @returns {Node} - * @private - */ -function _appendSingleChild (parentNode, newChild) { - if (newChild.parentNode) { - newChild.parentNode.removeChild(newChild); - } - newChild.parentNode = parentNode; - newChild.previousSibling = parentNode.lastChild; - newChild.nextSibling = null; - if (newChild.previousSibling) { - newChild.previousSibling.nextSibling = newChild; - } else { - parentNode.firstChild = newChild; - } - parentNode.lastChild = newChild; - _onUpdateChild(parentNode.ownerDocument, parentNode, newChild); - return newChild; -} - -Document.prototype = { - //implementation : null, - nodeName : '#document', - nodeType : DOCUMENT_NODE, - /** - * The DocumentType node of the document. - * - * @readonly - * @type DocumentType - */ - doctype : null, - documentElement : null, - _inc : 1, - - insertBefore : function(newChild, refChild){//raises - if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){ - var child = newChild.firstChild; - while(child){ - var next = child.nextSibling; - this.insertBefore(child,refChild); - child = next; - } - return newChild; - } - _insertBefore(this, newChild, refChild); - newChild.ownerDocument = this; - if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) { - this.documentElement = newChild; - } - - return newChild; - }, - removeChild : function(oldChild){ - if(this.documentElement == oldChild){ - this.documentElement = null; - } - return _removeChild(this,oldChild); - }, - replaceChild: function (newChild, oldChild) { - //raises - _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument); - newChild.ownerDocument = this; - if (oldChild) { - this.removeChild(oldChild); - } - if (isElementNode(newChild)) { - this.documentElement = newChild; - } - }, - // Introduced in DOM Level 2: - importNode : function(importedNode,deep){ - return importNode(this,importedNode,deep); - }, - // Introduced in DOM Level 2: - getElementById : function(id){ - var rtv = null; - _visitNode(this.documentElement,function(node){ - if(node.nodeType == ELEMENT_NODE){ - if(node.getAttribute('id') == id){ - rtv = node; - return true; - } - } - }) - return rtv; - }, - - /** - * The `getElementsByClassName` method of `Document` interface returns an array-like object - * of all child elements which have **all** of the given class name(s). - * - * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters. - * - * - * Warning: This is a live LiveNodeList. - * Changes in the DOM will reflect in the array as the changes occur. - * If an element selected by this array no longer qualifies for the selector, - * it will automatically be removed. Be aware of this for iteration purposes. - * - * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName - * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname - */ - getElementsByClassName: function(classNames) { - var classNamesSet = toOrderedSet(classNames) - return new LiveNodeList(this, function(base) { - var ls = []; - if (classNamesSet.length > 0) { - _visitNode(base.documentElement, function(node) { - if(node !== base && node.nodeType === ELEMENT_NODE) { - var nodeClassNames = node.getAttribute('class') - // can be null if the attribute does not exist - if (nodeClassNames) { - // before splitting and iterating just compare them for the most common case - var matches = classNames === nodeClassNames; - if (!matches) { - var nodeClassNamesSet = toOrderedSet(nodeClassNames) - matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet)) - } - if(matches) { - ls.push(node); - } - } - } - }); - } - return ls; - }); - }, - - //document factory method: - createElement : function(tagName){ - var node = new Element(); - node.ownerDocument = this; - node.nodeName = tagName; - node.tagName = tagName; - node.localName = tagName; - node.childNodes = new NodeList(); - var attrs = node.attributes = new NamedNodeMap(); - attrs._ownerElement = node; - return node; - }, - createDocumentFragment : function(){ - var node = new DocumentFragment(); - node.ownerDocument = this; - node.childNodes = new NodeList(); - return node; - }, - createTextNode : function(data){ - var node = new Text(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createComment : function(data){ - var node = new Comment(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createCDATASection : function(data){ - var node = new CDATASection(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createProcessingInstruction : function(target,data){ - var node = new ProcessingInstruction(); - node.ownerDocument = this; - node.tagName = node.target = target; - node.nodeValue= node.data = data; - return node; - }, - createAttribute : function(name){ - var node = new Attr(); - node.ownerDocument = this; - node.name = name; - node.nodeName = name; - node.localName = name; - node.specified = true; - return node; - }, - createEntityReference : function(name){ - var node = new EntityReference(); - node.ownerDocument = this; - node.nodeName = name; - return node; - }, - // Introduced in DOM Level 2: - createElementNS : function(namespaceURI,qualifiedName){ - var node = new Element(); - var pl = qualifiedName.split(':'); - var attrs = node.attributes = new NamedNodeMap(); - node.childNodes = new NodeList(); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.tagName = qualifiedName; - node.namespaceURI = namespaceURI; - if(pl.length == 2){ - node.prefix = pl[0]; - node.localName = pl[1]; - }else{ - //el.prefix = null; - node.localName = qualifiedName; - } - attrs._ownerElement = node; - return node; - }, - // Introduced in DOM Level 2: - createAttributeNS : function(namespaceURI,qualifiedName){ - var node = new Attr(); - var pl = qualifiedName.split(':'); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.name = qualifiedName; - node.namespaceURI = namespaceURI; - node.specified = true; - if(pl.length == 2){ - node.prefix = pl[0]; - node.localName = pl[1]; - }else{ - //el.prefix = null; - node.localName = qualifiedName; - } - return node; - } -}; -_extends(Document,Node); - - -function Element() { - this._nsMap = {}; -}; -Element.prototype = { - nodeType : ELEMENT_NODE, - hasAttribute : function(name){ - return this.getAttributeNode(name)!=null; - }, - getAttribute : function(name){ - var attr = this.getAttributeNode(name); - return attr && attr.value || ''; - }, - getAttributeNode : function(name){ - return this.attributes.getNamedItem(name); - }, - setAttribute : function(name, value){ - var attr = this.ownerDocument.createAttribute(name); - attr.value = attr.nodeValue = "" + value; - this.setAttributeNode(attr) - }, - removeAttribute : function(name){ - var attr = this.getAttributeNode(name) - attr && this.removeAttributeNode(attr); - }, - - //four real opeartion method - appendChild:function(newChild){ - if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ - return this.insertBefore(newChild,null); - }else{ - return _appendSingleChild(this,newChild); - } - }, - setAttributeNode : function(newAttr){ - return this.attributes.setNamedItem(newAttr); - }, - setAttributeNodeNS : function(newAttr){ - return this.attributes.setNamedItemNS(newAttr); - }, - removeAttributeNode : function(oldAttr){ - //console.log(this == oldAttr.ownerElement) - return this.attributes.removeNamedItem(oldAttr.nodeName); - }, - //get real attribute name,and remove it by removeAttributeNode - removeAttributeNS : function(namespaceURI, localName){ - var old = this.getAttributeNodeNS(namespaceURI, localName); - old && this.removeAttributeNode(old); - }, - - hasAttributeNS : function(namespaceURI, localName){ - return this.getAttributeNodeNS(namespaceURI, localName)!=null; - }, - getAttributeNS : function(namespaceURI, localName){ - var attr = this.getAttributeNodeNS(namespaceURI, localName); - return attr && attr.value || ''; - }, - setAttributeNS : function(namespaceURI, qualifiedName, value){ - var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); - attr.value = attr.nodeValue = "" + value; - this.setAttributeNode(attr) - }, - getAttributeNodeNS : function(namespaceURI, localName){ - return this.attributes.getNamedItemNS(namespaceURI, localName); - }, - - getElementsByTagName : function(tagName){ - return new LiveNodeList(this,function(base){ - var ls = []; - _visitNode(base,function(node){ - if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){ - ls.push(node); - } - }); - return ls; - }); - }, - getElementsByTagNameNS : function(namespaceURI, localName){ - return new LiveNodeList(this,function(base){ - var ls = []; - _visitNode(base,function(node){ - if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){ - ls.push(node); - } - }); - return ls; - - }); - } -}; -Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; -Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; - - -_extends(Element,Node); -function Attr() { -}; -Attr.prototype.nodeType = ATTRIBUTE_NODE; -_extends(Attr,Node); - - -function CharacterData() { -}; -CharacterData.prototype = { - data : '', - substringData : function(offset, count) { - return this.data.substring(offset, offset+count); - }, - appendData: function(text) { - text = this.data+text; - this.nodeValue = this.data = text; - this.length = text.length; - }, - insertData: function(offset,text) { - this.replaceData(offset,0,text); - - }, - appendChild:function(newChild){ - throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]) - }, - deleteData: function(offset, count) { - this.replaceData(offset,count,""); - }, - replaceData: function(offset, count, text) { - var start = this.data.substring(0,offset); - var end = this.data.substring(offset+count); - text = start + text + end; - this.nodeValue = this.data = text; - this.length = text.length; - } -} -_extends(CharacterData,Node); -function Text() { -}; -Text.prototype = { - nodeName : "#text", - nodeType : TEXT_NODE, - splitText : function(offset) { - var text = this.data; - var newText = text.substring(offset); - text = text.substring(0, offset); - this.data = this.nodeValue = text; - this.length = text.length; - var newNode = this.ownerDocument.createTextNode(newText); - if(this.parentNode){ - this.parentNode.insertBefore(newNode, this.nextSibling); - } - return newNode; - } -} -_extends(Text,CharacterData); -function Comment() { -}; -Comment.prototype = { - nodeName : "#comment", - nodeType : COMMENT_NODE -} -_extends(Comment,CharacterData); - -function CDATASection() { -}; -CDATASection.prototype = { - nodeName : "#cdata-section", - nodeType : CDATA_SECTION_NODE -} -_extends(CDATASection,CharacterData); - - -function DocumentType() { -}; -DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; -_extends(DocumentType,Node); - -function Notation() { -}; -Notation.prototype.nodeType = NOTATION_NODE; -_extends(Notation,Node); - -function Entity() { -}; -Entity.prototype.nodeType = ENTITY_NODE; -_extends(Entity,Node); - -function EntityReference() { -}; -EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; -_extends(EntityReference,Node); - -function DocumentFragment() { -}; -DocumentFragment.prototype.nodeName = "#document-fragment"; -DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; -_extends(DocumentFragment,Node); - - -function ProcessingInstruction() { -} -ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; -_extends(ProcessingInstruction,Node); -function XMLSerializer(){} -XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){ - return nodeSerializeToString.call(node,isHtml,nodeFilter); -} -Node.prototype.toString = nodeSerializeToString; -function nodeSerializeToString(isHtml,nodeFilter){ - var buf = []; - var refNode = this.nodeType == 9 && this.documentElement || this; - var prefix = refNode.prefix; - var uri = refNode.namespaceURI; - - if(uri && prefix == null){ - //console.log(prefix) - var prefix = refNode.lookupPrefix(uri); - if(prefix == null){ - //isHTML = true; - var visibleNamespaces=[ - {namespace:uri,prefix:null} - //{namespace:uri,prefix:''} - ] - } - } - serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces); - //console.log('###',this.nodeType,uri,prefix,buf.join('')) - return buf.join(''); -} - -function needNamespaceDefine(node, isHTML, visibleNamespaces) { - var prefix = node.prefix || ''; - var uri = node.namespaceURI; - // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) , - // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl : - // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty. - // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using) - // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared : - // > [...] Furthermore, the attribute value [...] must not be an empty string. - // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document. - if (!uri) { - return false; - } - if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) { - return false; - } - - var i = visibleNamespaces.length - while (i--) { - var ns = visibleNamespaces[i]; - // get namespace prefix - if (ns.prefix === prefix) { - return ns.namespace !== uri; - } - } - return true; -} -/** - * Well-formed constraint: No < in Attribute Values - * > The replacement text of any entity referred to directly or indirectly - * > in an attribute value must not contain a <. - * @see https://www.w3.org/TR/xml11/#CleanAttrVals - * @see https://www.w3.org/TR/xml11/#NT-AttValue - * - * Literal whitespace other than space that appear in attribute values - * are serialized as their entity references, so they will be preserved. - * (In contrast to whitespace literals in the input which are normalized to spaces) - * @see https://www.w3.org/TR/xml11/#AVNormalize - * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes - */ -function addSerializedAttribute(buf, qualifiedName, value) { - buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"') -} - -function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ - if (!visibleNamespaces) { - visibleNamespaces = []; - } - - if(nodeFilter){ - node = nodeFilter(node); - if(node){ - if(typeof node == 'string'){ - buf.push(node); - return; - } - }else{ - return; - } - //buf.sort.apply(attrs, attributeSorter); - } - - switch(node.nodeType){ - case ELEMENT_NODE: - var attrs = node.attributes; - var len = attrs.length; - var child = node.firstChild; - var nodeName = node.tagName; - - isHTML = NAMESPACE.isHTML(node.namespaceURI) || isHTML - - var prefixedNodeName = nodeName - if (!isHTML && !node.prefix && node.namespaceURI) { - var defaultNS - // lookup current default ns from `xmlns` attribute - for (var ai = 0; ai < attrs.length; ai++) { - if (attrs.item(ai).name === 'xmlns') { - defaultNS = attrs.item(ai).value - break - } - } - if (!defaultNS) { - // lookup current default ns in visibleNamespaces - for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) { - var namespace = visibleNamespaces[nsi] - if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) { - defaultNS = namespace.namespace - break - } - } - } - if (defaultNS !== node.namespaceURI) { - for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) { - var namespace = visibleNamespaces[nsi] - if (namespace.namespace === node.namespaceURI) { - if (namespace.prefix) { - prefixedNodeName = namespace.prefix + ':' + nodeName - } - break - } - } - } - } - - buf.push('<', prefixedNodeName); - - for(var i=0;i'); - //if is cdata child node - if(isHTML && /^script$/i.test(nodeName)){ - while(child){ - if(child.data){ - buf.push(child.data); - }else{ - serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice()); - } - child = child.nextSibling; - } - }else - { - while(child){ - serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice()); - child = child.nextSibling; - } - } - buf.push(''); - }else{ - buf.push('/>'); - } - // remove added visible namespaces - //visibleNamespaces.length = startVisibleNamespaces; - return; - case DOCUMENT_NODE: - case DOCUMENT_FRAGMENT_NODE: - var child = node.firstChild; - while(child){ - serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice()); - child = child.nextSibling; - } - return; - case ATTRIBUTE_NODE: - return addSerializedAttribute(buf, node.name, node.value); - case TEXT_NODE: - /** - * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, - * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. - * If they are needed elsewhere, they must be escaped using either numeric character references or the strings - * `&` and `<` respectively. - * The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, - * be escaped using either `>` or a character reference when it appears in the string `]]>` in content, - * when that string is not marking the end of a CDATA section. - * - * In the content of elements, character data is any string of characters - * which does not contain the start-delimiter of any markup - * and does not include the CDATA-section-close delimiter, `]]>`. - * - * @see https://www.w3.org/TR/xml/#NT-CharData - * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node - */ - return buf.push(node.data - .replace(/[<&>]/g,_xmlEncoder) - ); - case CDATA_SECTION_NODE: - return buf.push( ''); - case COMMENT_NODE: - return buf.push( ""); - case DOCUMENT_TYPE_NODE: - var pubid = node.publicId; - var sysid = node.systemId; - buf.push(''); - }else if(sysid && sysid!='.'){ - buf.push(' SYSTEM ', sysid, '>'); - }else{ - var sub = node.internalSubset; - if(sub){ - buf.push(" [",sub,"]"); - } - buf.push(">"); - } - return; - case PROCESSING_INSTRUCTION_NODE: - return buf.push( ""); - case ENTITY_REFERENCE_NODE: - return buf.push( '&',node.nodeName,';'); - //case ENTITY_NODE: - //case NOTATION_NODE: - default: - buf.push('??',node.nodeName); - } -} -function importNode(doc,node,deep){ - var node2; - switch (node.nodeType) { - case ELEMENT_NODE: - node2 = node.cloneNode(false); - node2.ownerDocument = doc; - //var attrs = node2.attributes; - //var len = attrs.length; - //for(var i=0;i { - -var freeze = (__webpack_require__(/*! ./conventions */ "../rdflib/node_modules/@xmldom/xmldom/lib/conventions.js").freeze); - -/** - * The entities that are predefined in every XML document. - * - * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-predefined-ent W3C XML 1.1 - * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent W3C XML 1.0 - * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML Wikipedia - */ -exports.XML_ENTITIES = freeze({amp:'&', apos:"'", gt:'>', lt:'<', quot:'"'}) - -/** - * A map of currently 241 entities that are detected in an HTML document. - * They contain all entries from `XML_ENTITIES`. - * - * @see XML_ENTITIES - * @see DOMParser.parseFromString - * @see DOMImplementation.prototype.createHTMLDocument - * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec - * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names - * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML - * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML) - * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML) - */ -exports.HTML_ENTITIES = freeze({ - lt: '<', - gt: '>', - amp: '&', - quot: '"', - apos: "'", - Agrave: "À", - Aacute: "Á", - Acirc: "Â", - Atilde: "Ã", - Auml: "Ä", - Aring: "Å", - AElig: "Æ", - Ccedil: "Ç", - Egrave: "È", - Eacute: "É", - Ecirc: "Ê", - Euml: "Ë", - Igrave: "Ì", - Iacute: "Í", - Icirc: "Î", - Iuml: "Ï", - ETH: "Ð", - Ntilde: "Ñ", - Ograve: "Ò", - Oacute: "Ó", - Ocirc: "Ô", - Otilde: "Õ", - Ouml: "Ö", - Oslash: "Ø", - Ugrave: "Ù", - Uacute: "Ú", - Ucirc: "Û", - Uuml: "Ü", - Yacute: "Ý", - THORN: "Þ", - szlig: "ß", - agrave: "à", - aacute: "á", - acirc: "â", - atilde: "ã", - auml: "ä", - aring: "å", - aelig: "æ", - ccedil: "ç", - egrave: "è", - eacute: "é", - ecirc: "ê", - euml: "ë", - igrave: "ì", - iacute: "í", - icirc: "î", - iuml: "ï", - eth: "ð", - ntilde: "ñ", - ograve: "ò", - oacute: "ó", - ocirc: "ô", - otilde: "õ", - ouml: "ö", - oslash: "ø", - ugrave: "ù", - uacute: "ú", - ucirc: "û", - uuml: "ü", - yacute: "ý", - thorn: "þ", - yuml: "ÿ", - nbsp: "\u00a0", - iexcl: "¡", - cent: "¢", - pound: "£", - curren: "¤", - yen: "¥", - brvbar: "¦", - sect: "§", - uml: "¨", - copy: "©", - ordf: "ª", - laquo: "«", - not: "¬", - shy: "­­", - reg: "®", - macr: "¯", - deg: "°", - plusmn: "±", - sup2: "²", - sup3: "³", - acute: "´", - micro: "µ", - para: "¶", - middot: "·", - cedil: "¸", - sup1: "¹", - ordm: "º", - raquo: "»", - frac14: "¼", - frac12: "½", - frac34: "¾", - iquest: "¿", - times: "×", - divide: "÷", - forall: "∀", - part: "∂", - exist: "∃", - empty: "∅", - nabla: "∇", - isin: "∈", - notin: "∉", - ni: "∋", - prod: "∏", - sum: "∑", - minus: "−", - lowast: "∗", - radic: "√", - prop: "∝", - infin: "∞", - ang: "∠", - and: "∧", - or: "∨", - cap: "∩", - cup: "∪", - 'int': "∫", - there4: "∴", - sim: "∼", - cong: "≅", - asymp: "≈", - ne: "≠", - equiv: "≡", - le: "≤", - ge: "≥", - sub: "⊂", - sup: "⊃", - nsub: "⊄", - sube: "⊆", - supe: "⊇", - oplus: "⊕", - otimes: "⊗", - perp: "⊥", - sdot: "⋅", - Alpha: "Α", - Beta: "Β", - Gamma: "Γ", - Delta: "Δ", - Epsilon: "Ε", - Zeta: "Ζ", - Eta: "Η", - Theta: "Θ", - Iota: "Ι", - Kappa: "Κ", - Lambda: "Λ", - Mu: "Μ", - Nu: "Ν", - Xi: "Ξ", - Omicron: "Ο", - Pi: "Π", - Rho: "Ρ", - Sigma: "Σ", - Tau: "Τ", - Upsilon: "Υ", - Phi: "Φ", - Chi: "Χ", - Psi: "Ψ", - Omega: "Ω", - alpha: "α", - beta: "β", - gamma: "γ", - delta: "δ", - epsilon: "ε", - zeta: "ζ", - eta: "η", - theta: "θ", - iota: "ι", - kappa: "κ", - lambda: "λ", - mu: "μ", - nu: "ν", - xi: "ξ", - omicron: "ο", - pi: "π", - rho: "ρ", - sigmaf: "ς", - sigma: "σ", - tau: "τ", - upsilon: "υ", - phi: "φ", - chi: "χ", - psi: "ψ", - omega: "ω", - thetasym: "ϑ", - upsih: "ϒ", - piv: "ϖ", - OElig: "Œ", - oelig: "œ", - Scaron: "Š", - scaron: "š", - Yuml: "Ÿ", - fnof: "ƒ", - circ: "ˆ", - tilde: "˜", - ensp: " ", - emsp: " ", - thinsp: " ", - zwnj: "‌", - zwj: "‍", - lrm: "‎", - rlm: "‏", - ndash: "–", - mdash: "—", - lsquo: "‘", - rsquo: "’", - sbquo: "‚", - ldquo: "“", - rdquo: "”", - bdquo: "„", - dagger: "†", - Dagger: "‡", - bull: "•", - hellip: "…", - permil: "‰", - prime: "′", - Prime: "″", - lsaquo: "‹", - rsaquo: "›", - oline: "‾", - euro: "€", - trade: "™", - larr: "←", - uarr: "↑", - rarr: "→", - darr: "↓", - harr: "↔", - crarr: "↵", - lceil: "⌈", - rceil: "⌉", - lfloor: "⌊", - rfloor: "⌋", - loz: "◊", - spades: "♠", - clubs: "♣", - hearts: "♥", - diams: "♦" -}); - -/** - * @deprecated use `HTML_ENTITIES` instead - * @see HTML_ENTITIES - */ -exports.entityMap = exports.HTML_ENTITIES - - -/***/ }), - -/***/ "../rdflib/node_modules/@xmldom/xmldom/lib/index.js": -/*!**********************************************************!*\ - !*** ../rdflib/node_modules/@xmldom/xmldom/lib/index.js ***! - \**********************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var dom = __webpack_require__(/*! ./dom */ "../rdflib/node_modules/@xmldom/xmldom/lib/dom.js") -exports.DOMImplementation = dom.DOMImplementation -exports.XMLSerializer = dom.XMLSerializer -exports.DOMParser = __webpack_require__(/*! ./dom-parser */ "../rdflib/node_modules/@xmldom/xmldom/lib/dom-parser.js").DOMParser - - -/***/ }), - -/***/ "../rdflib/node_modules/@xmldom/xmldom/lib/sax.js": -/*!********************************************************!*\ - !*** ../rdflib/node_modules/@xmldom/xmldom/lib/sax.js ***! - \********************************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -var NAMESPACE = (__webpack_require__(/*! ./conventions */ "../rdflib/node_modules/@xmldom/xmldom/lib/conventions.js").NAMESPACE); - -//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] -//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] -//[5] Name ::= NameStartChar (NameChar)* -var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF -var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); -var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); -//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ -//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') - -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE -var S_TAG = 0;//tag name offerring -var S_ATTR = 1;//attr name offerring -var S_ATTR_SPACE=2;//attr name end and space offer -var S_EQ = 3;//=space? -var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) -var S_ATTR_END = 5;//attr value end and no space(quot end) -var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) -var S_TAG_CLOSE = 7;//closed el - -/** - * Creates an error that will not be caught by XMLReader aka the SAX parser. - * - * @param {string} message - * @param {any?} locator Optional, can provide details about the location in the source - * @constructor - */ -function ParseError(message, locator) { - this.message = message - this.locator = locator - if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError); -} -ParseError.prototype = new Error(); -ParseError.prototype.name = ParseError.name - -function XMLReader(){ - -} - -XMLReader.prototype = { - parse:function(source,defaultNSMap,entityMap){ - var domBuilder = this.domBuilder; - domBuilder.startDocument(); - _copy(defaultNSMap ,defaultNSMap = {}) - parse(source,defaultNSMap,entityMap, - domBuilder,this.errorHandler); - domBuilder.endDocument(); - } -} -function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ - function fixedFromCharCode(code) { - // String.prototype.fromCharCode does not supports - // > 2 bytes unicode chars directly - if (code > 0xffff) { - code -= 0x10000; - var surrogate1 = 0xd800 + (code >> 10) - , surrogate2 = 0xdc00 + (code & 0x3ff); - - return String.fromCharCode(surrogate1, surrogate2); - } else { - return String.fromCharCode(code); - } - } - function entityReplacer(a){ - var k = a.slice(1,-1); - if (Object.hasOwnProperty.call(entityMap, k)) { - return entityMap[k]; - }else if(k.charAt(0) === '#'){ - return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) - }else{ - errorHandler.error('entity not found:'+a); - return a; - } - } - function appendText(end){//has some bugs - if(end>start){ - var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); - locator&&position(start); - domBuilder.characters(xt,0,end-start); - start = end - } - } - function position(p,m){ - while(p>=lineEnd && (m = linePattern.exec(source))){ - lineStart = m.index; - lineEnd = lineStart + m[0].length; - locator.lineNumber++; - //console.log('line++:',locator,startPos,endPos) - } - locator.columnNumber = p-lineStart+1; - } - var lineStart = 0; - var lineEnd = 0; - var linePattern = /.*(?:\r\n?|\n)|.*$/g - var locator = domBuilder.locator; - - var parseStack = [{currentNSMap:defaultNSMapCopy}] - var closeMap = {}; - var start = 0; - while(true){ - try{ - var tagStart = source.indexOf('<',start); - if(tagStart<0){ - if(!source.substr(start).match(/^\s*$/)){ - var doc = domBuilder.doc; - var text = doc.createTextNode(source.substr(start)); - doc.appendChild(text); - domBuilder.currentElement = text; - } - return; - } - if(tagStart>start){ - appendText(tagStart); - } - switch(source.charAt(tagStart+1)){ - case '/': - var end = source.indexOf('>',tagStart+3); - var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, ''); - var config = parseStack.pop(); - if(end<0){ - - tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); - errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); - end = tagStart+1+tagName.length; - }else if(tagName.match(/\s - locator&&position(tagStart); - end = parseInstruction(source,tagStart,domBuilder); - break; - case '!':// start){ - start = end; - }else{ - //TODO: 这里有可能sax回退,有位置错误风险 - appendText(Math.max(tagStart,start)+1); - } - } -} -function copyLocator(f,t){ - t.lineNumber = f.lineNumber; - t.columnNumber = f.columnNumber; - return t; -} - -/** - * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); - * @return end of the elementStartPart(end of elementEndPart for selfClosed el) - */ -function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ - - /** - * @param {string} qname - * @param {string} value - * @param {number} startIndex - */ - function addAttribute(qname, value, startIndex) { - if (el.attributeNames.hasOwnProperty(qname)) { - errorHandler.fatalError('Attribute ' + qname + ' redefined') - } - el.addValue( - qname, - // @see https://www.w3.org/TR/xml/#AVNormalize - // since the xmldom sax parser does not "interpret" DTD the following is not implemented: - // - recursive replacement of (DTD) entity references - // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA - value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer), - startIndex - ) - } - var attrName; - var value; - var p = ++start; - var s = S_TAG;//status - while(true){ - var c = source.charAt(p); - switch(c){ - case '=': - if(s === S_ATTR){//attrName - attrName = source.slice(start,p); - s = S_EQ; - }else if(s === S_ATTR_SPACE){ - s = S_EQ; - }else{ - //fatalError: equal must after attrName or space after attrName - throw new Error('attribute equal must after attrName'); // No known test case - } - break; - case '\'': - case '"': - if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE - ){//equal - if(s === S_ATTR){ - errorHandler.warning('attribute value must after "="') - attrName = source.slice(start,p) - } - start = p+1; - p = source.indexOf(c,start) - if(p>0){ - value = source.slice(start, p); - addAttribute(attrName, value, start-1); - s = S_ATTR_END; - }else{ - //fatalError: no end quot match - throw new Error('attribute value no end \''+c+'\' match'); - } - }else if(s == S_ATTR_NOQUOT_VALUE){ - value = source.slice(start, p); - addAttribute(attrName, value, start); - errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); - start = p+1; - s = S_ATTR_END - }else{ - //fatalError: no equal before - throw new Error('attribute value must after "="'); // No known test case - } - break; - case '/': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - s =S_TAG_CLOSE; - el.closed = true; - case S_ATTR_NOQUOT_VALUE: - case S_ATTR: - case S_ATTR_SPACE: - break; - //case S_EQ: - default: - throw new Error("attribute invalid close char('/')") // No known test case - } - break; - case ''://end document - errorHandler.error('unexpected end of input'); - if(s == S_TAG){ - el.setTagName(source.slice(start,p)); - } - return p; - case '>': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - break;//normal - case S_ATTR_NOQUOT_VALUE://Compatible state - case S_ATTR: - value = source.slice(start,p); - if(value.slice(-1) === '/'){ - el.closed = true; - value = value.slice(0,-1) - } - case S_ATTR_SPACE: - if(s === S_ATTR_SPACE){ - value = attrName; - } - if(s == S_ATTR_NOQUOT_VALUE){ - errorHandler.warning('attribute "'+value+'" missed quot(")!'); - addAttribute(attrName, value, start) - }else{ - if(!NAMESPACE.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)){ - errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') - } - addAttribute(value, value, start) - } - break; - case S_EQ: - throw new Error('attribute value missed!!'); - } -// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) - return p; - /*xml space '\x20' | #x9 | #xD | #xA; */ - case '\u0080': - c = ' '; - default: - if(c<= ' '){//space - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p));//tagName - s = S_TAG_SPACE; - break; - case S_ATTR: - attrName = source.slice(start,p) - s = S_ATTR_SPACE; - break; - case S_ATTR_NOQUOT_VALUE: - var value = source.slice(start, p); - errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - addAttribute(attrName, value, start) - case S_ATTR_END: - s = S_TAG_SPACE; - break; - //case S_TAG_SPACE: - //case S_EQ: - //case S_ATTR_SPACE: - // void();break; - //case S_TAG_CLOSE: - //ignore warning - } - }else{//not space -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE - switch(s){ - //case S_TAG:void();break; - //case S_ATTR:void();break; - //case S_ATTR_NOQUOT_VALUE:void();break; - case S_ATTR_SPACE: - var tagName = el.tagName; - if (!NAMESPACE.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) { - errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') - } - addAttribute(attrName, attrName, start); - start = p; - s = S_ATTR; - break; - case S_ATTR_END: - errorHandler.warning('attribute space is required"'+attrName+'"!!') - case S_TAG_SPACE: - s = S_ATTR; - start = p; - break; - case S_EQ: - s = S_ATTR_NOQUOT_VALUE; - start = p; - break; - case S_TAG_CLOSE: - throw new Error("elements closed character '/' and '>' must be connected to"); - } - } - }//end outer switch - //console.log('p++',p) - p++; - } -} -/** - * @return true if has new namespace define - */ -function appendElement(el,domBuilder,currentNSMap){ - var tagName = el.tagName; - var localNSMap = null; - //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; - var i = el.length; - while(i--){ - var a = el[i]; - var qName = a.qName; - var value = a.value; - var nsp = qName.indexOf(':'); - if(nsp>0){ - var prefix = a.prefix = qName.slice(0,nsp); - var localName = qName.slice(nsp+1); - var nsPrefix = prefix === 'xmlns' && localName - }else{ - localName = qName; - prefix = null - nsPrefix = qName === 'xmlns' && '' - } - //can not set prefix,because prefix !== '' - a.localName = localName ; - //prefix == null for no ns prefix attribute - if(nsPrefix !== false){//hack!! - if(localNSMap == null){ - localNSMap = {} - //console.log(currentNSMap,0) - _copy(currentNSMap,currentNSMap={}) - //console.log(currentNSMap,1) - } - currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; - a.uri = NAMESPACE.XMLNS - domBuilder.startPrefixMapping(nsPrefix, value) - } - } - var i = el.length; - while(i--){ - a = el[i]; - var prefix = a.prefix; - if(prefix){//no prefix attribute has no namespace - if(prefix === 'xml'){ - a.uri = NAMESPACE.XML; - }if(prefix !== 'xmlns'){ - a.uri = currentNSMap[prefix || ''] - - //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} - } - } - } - var nsp = tagName.indexOf(':'); - if(nsp>0){ - prefix = el.prefix = tagName.slice(0,nsp); - localName = el.localName = tagName.slice(nsp+1); - }else{ - prefix = null;//important!! - localName = el.localName = tagName; - } - //no prefix element has default namespace - var ns = el.uri = currentNSMap[prefix || '']; - domBuilder.startElement(ns,localName,tagName,el); - //endPrefixMapping and startPrefixMapping have not any help for dom builder - //localNSMap = null - if(el.closed){ - domBuilder.endElement(ns,localName,tagName); - if(localNSMap){ - for (prefix in localNSMap) { - if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) { - domBuilder.endPrefixMapping(prefix); - } - } - } - }else{ - el.currentNSMap = currentNSMap; - el.localNSMap = localNSMap; - //parseStack.push(el); - return true; - } -} -function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ - if(/^(?:script|textarea)$/i.test(tagName)){ - var elEndStart = source.indexOf('',elStartEnd); - var text = source.substring(elStartEnd+1,elEndStart); - if(/[&<]/.test(text)){ - if(/^script$/i.test(tagName)){ - //if(!/\]\]>/.test(text)){ - //lexHandler.startCDATA(); - domBuilder.characters(text,0,text.length); - //lexHandler.endCDATA(); - return elEndStart; - //} - }//}else{//text area - text = text.replace(/&#?\w+;/g,entityReplacer); - domBuilder.characters(text,0,text.length); - return elEndStart; - //} - - } - } - return elStartEnd+1; -} -function fixSelfClosed(source,elStartEnd,tagName,closeMap){ - //if(tagName in closeMap){ - var pos = closeMap[tagName]; - if(pos == null){ - //console.log(tagName) - pos = source.lastIndexOf('') - if(pos',start+4); - //append comment source.substring(4,end)//"); + case DOCUMENT_TYPE_NODE: + var pubid = node.publicId; + var sysid = node.systemId; + buf.push(''); + }else if(sysid && sysid!='.'){ + buf.push(' SYSTEM ', sysid, '>'); + }else{ + var sub = node.internalSubset; + if(sub){ + buf.push(" [",sub,"]"); + } + buf.push(">"); + } + return; + case PROCESSING_INSTRUCTION_NODE: + return buf.push( ""); + case ENTITY_REFERENCE_NODE: + return buf.push( '&',node.nodeName,';'); + //case ENTITY_NODE: + //case NOTATION_NODE: + default: + buf.push('??',node.nodeName); + } } -function ktToList(k) { - var list = ''; - var y = ['Read', 'Append', 'Write', 'Control']; - for (var i = 0; i < 4; i++) { - if (k & 1 << i) { - list += y[i]; - } - } - return list; +function importNode(doc,node,deep){ + var node2; + switch (node.nodeType) { + case ELEMENT_NODE: + node2 = node.cloneNode(false); + node2.ownerDocument = doc; + //var attrs = node2.attributes; + //var len = attrs.length; + //for(var i=0;i { + +var freeze = (__webpack_require__(/*! ./conventions */ "./node_modules/@xmldom/xmldom/lib/conventions.js").freeze); + +/** + * The entities that are predefined in every XML document. + * + * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-predefined-ent W3C XML 1.1 + * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent W3C XML 1.0 + * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML Wikipedia + */ +exports.XML_ENTITIES = freeze({amp:'&', apos:"'", gt:'>', lt:'<', quot:'"'}) + +/** + * A map of currently 241 entities that are detected in an HTML document. + * They contain all entries from `XML_ENTITIES`. + * + * @see XML_ENTITIES + * @see DOMParser.parseFromString + * @see DOMImplementation.prototype.createHTMLDocument + * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec + * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names + * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML + * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML) + * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML) + */ +exports.HTML_ENTITIES = freeze({ + lt: '<', + gt: '>', + amp: '&', + quot: '"', + apos: "'", + Agrave: "À", + Aacute: "Á", + Acirc: "Â", + Atilde: "Ã", + Auml: "Ä", + Aring: "Å", + AElig: "Æ", + Ccedil: "Ç", + Egrave: "È", + Eacute: "É", + Ecirc: "Ê", + Euml: "Ë", + Igrave: "Ì", + Iacute: "Í", + Icirc: "Î", + Iuml: "Ï", + ETH: "Ð", + Ntilde: "Ñ", + Ograve: "Ò", + Oacute: "Ó", + Ocirc: "Ô", + Otilde: "Õ", + Ouml: "Ö", + Oslash: "Ø", + Ugrave: "Ù", + Uacute: "Ú", + Ucirc: "Û", + Uuml: "Ü", + Yacute: "Ý", + THORN: "Þ", + szlig: "ß", + agrave: "à", + aacute: "á", + acirc: "â", + atilde: "ã", + auml: "ä", + aring: "å", + aelig: "æ", + ccedil: "ç", + egrave: "è", + eacute: "é", + ecirc: "ê", + euml: "ë", + igrave: "ì", + iacute: "í", + icirc: "î", + iuml: "ï", + eth: "ð", + ntilde: "ñ", + ograve: "ò", + oacute: "ó", + ocirc: "ô", + otilde: "õ", + ouml: "ö", + oslash: "ø", + ugrave: "ù", + uacute: "ú", + ucirc: "û", + uuml: "ü", + yacute: "ý", + thorn: "þ", + yuml: "ÿ", + nbsp: "\u00a0", + iexcl: "¡", + cent: "¢", + pound: "£", + curren: "¤", + yen: "¥", + brvbar: "¦", + sect: "§", + uml: "¨", + copy: "©", + ordf: "ª", + laquo: "«", + not: "¬", + shy: "­­", + reg: "®", + macr: "¯", + deg: "°", + plusmn: "±", + sup2: "²", + sup3: "³", + acute: "´", + micro: "µ", + para: "¶", + middot: "·", + cedil: "¸", + sup1: "¹", + ordm: "º", + raquo: "»", + frac14: "¼", + frac12: "½", + frac34: "¾", + iquest: "¿", + times: "×", + divide: "÷", + forall: "∀", + part: "∂", + exist: "∃", + empty: "∅", + nabla: "∇", + isin: "∈", + notin: "∉", + ni: "∋", + prod: "∏", + sum: "∑", + minus: "−", + lowast: "∗", + radic: "√", + prop: "∝", + infin: "∞", + ang: "∠", + and: "∧", + or: "∨", + cap: "∩", + cup: "∪", + 'int': "∫", + there4: "∴", + sim: "∼", + cong: "≅", + asymp: "≈", + ne: "≠", + equiv: "≡", + le: "≤", + ge: "≥", + sub: "⊂", + sup: "⊃", + nsub: "⊄", + sube: "⊆", + supe: "⊇", + oplus: "⊕", + otimes: "⊗", + perp: "⊥", + sdot: "⋅", + Alpha: "Α", + Beta: "Β", + Gamma: "Γ", + Delta: "Δ", + Epsilon: "Ε", + Zeta: "Ζ", + Eta: "Η", + Theta: "Θ", + Iota: "Ι", + Kappa: "Κ", + Lambda: "Λ", + Mu: "Μ", + Nu: "Ν", + Xi: "Ξ", + Omicron: "Ο", + Pi: "Π", + Rho: "Ρ", + Sigma: "Σ", + Tau: "Τ", + Upsilon: "Υ", + Phi: "Φ", + Chi: "Χ", + Psi: "Ψ", + Omega: "Ω", + alpha: "α", + beta: "β", + gamma: "γ", + delta: "δ", + epsilon: "ε", + zeta: "ζ", + eta: "η", + theta: "θ", + iota: "ι", + kappa: "κ", + lambda: "λ", + mu: "μ", + nu: "ν", + xi: "ξ", + omicron: "ο", + pi: "π", + rho: "ρ", + sigmaf: "ς", + sigma: "σ", + tau: "τ", + upsilon: "υ", + phi: "φ", + chi: "χ", + psi: "ψ", + omega: "ω", + thetasym: "ϑ", + upsih: "ϒ", + piv: "ϖ", + OElig: "Œ", + oelig: "œ", + Scaron: "Š", + scaron: "š", + Yuml: "Ÿ", + fnof: "ƒ", + circ: "ˆ", + tilde: "˜", + ensp: " ", + emsp: " ", + thinsp: " ", + zwnj: "‌", + zwj: "‍", + lrm: "‎", + rlm: "‏", + ndash: "–", + mdash: "—", + lsquo: "‘", + rsquo: "’", + sbquo: "‚", + ldquo: "“", + rdquo: "”", + bdquo: "„", + dagger: "†", + Dagger: "‡", + bull: "•", + hellip: "…", + permil: "‰", + prime: "′", + Prime: "″", + lsaquo: "‹", + rsaquo: "›", + oline: "‾", + euro: "€", + trade: "™", + larr: "←", + uarr: "↑", + rarr: "→", + darr: "↓", + harr: "↔", + crarr: "↵", + lceil: "⌈", + rceil: "⌉", + lfloor: "⌊", + rfloor: "⌋", + loz: "◊", + spades: "♠", + clubs: "♣", + hearts: "♥", + diams: "♦" +}); + +/** + * @deprecated use `HTML_ENTITIES` instead + * @see HTML_ENTITIES + */ +exports.entityMap = exports.HTML_ENTITIES - if (obj.sameTerm(ns.foaf('Agent')) || obj.sameTerm(ns.acl('AuthenticatedAgent')) || - // AuthenticatedAgent - obj.sameTerm(ns.rdf('Resource')) || obj.sameTerm(ns.owl('Thing'))) { - return { - pred: 'agentClass', - obj: obj - }; - } - if (ns.vcard('Individual').uri in types || ns.foaf('Person').uri in types || ns.foaf('Agent').uri in types) { - var pref = kb.any(obj, ns.foaf('preferredURI')); - if (pref) return { - pred: 'agent', - obj: (0, _rdflib.sym)(pref) - }; - return { - pred: 'agent', - obj: obj - }; - } - if (ns.solid('AppProvider').uri in types) { - return { - pred: 'origin', - obj: obj - }; - } - if (ns.solid('AppProviderClass').uri in types) { - return { - pred: 'originClass', - obj: obj - }; - } - debug.log(' Triage fails for ' + uri); - return null; -} -//# sourceMappingURL=access-groups.js.map /***/ }), -/***/ "./lib/acl/acl-control.js": -/*!********************************!*\ - !*** ./lib/acl/acl-control.js ***! - \********************************/ +/***/ "./node_modules/@xmldom/xmldom/lib/index.js": +/*!**************************************************!*\ + !*** ./node_modules/@xmldom/xmldom/lib/index.js ***! + \**************************************************/ /***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; +var dom = __webpack_require__(/*! ./dom */ "./node_modules/@xmldom/xmldom/lib/dom.js") +exports.DOMImplementation = dom.DOMImplementation +exports.XMLSerializer = dom.XMLSerializer +exports.DOMParser = __webpack_require__(/*! ./dom-parser */ "./node_modules/@xmldom/xmldom/lib/dom-parser.js").DOMParser -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ACLControlBox5 = ACLControlBox5; -exports.handleDrop = handleDrop; -exports.preventBrowserDropEvents = preventBrowserDropEvents; -exports.preventDrag = preventDrag; -exports.setGlobalWindow = setGlobalWindow; -exports.shortNameForFolder = shortNameForFolder; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var _acl = __webpack_require__(/*! ./acl */ "./lib/acl/acl.js"); -var _accessController = __webpack_require__(/*! ./access-controller */ "./lib/acl/access-controller.js"); -var _jss = __webpack_require__(/*! ../jss */ "./lib/jss/index.js"); -var _styles = __webpack_require__(/*! ./styles */ "./lib/acl/styles.js"); -var _debug = __webpack_require__(/*! ../debug */ "./lib/debug.js"); -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); } -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; } -/** - * Functions for rendering the ACL User Interface. - * See https://github.com/solidos/userguide/blob/main/views/sharing/userguide.md#view - * for a screenshot. - * @packageDocumentation - */ +/***/ }), -var global = window; -var preventBrowserDropEventsDone = Symbol('prevent double triggering of drop event'); +/***/ "./node_modules/@xmldom/xmldom/lib/sax.js": +/*!************************************************!*\ + !*** ./node_modules/@xmldom/xmldom/lib/sax.js ***! + \************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -/** - * See https://coshx.com/preventing-drag-and-drop-disasters-with-a-chrome-userscript - * Without this dropping anything onto a browser page will cause chrome etc to jump to diff page - * throwing away all the user's work. - * - * In apps which may use drag and drop, this utility takes care of the fact - * by default in a browser, an uncaught user drop into a browser window - * causes the browser to lose all its work in that window and navigate to another page - * - * @param document The DOM - * @returns void - */ -function preventBrowserDropEvents(document) { - (0, _debug.log)('preventBrowserDropEvents called.'); - if (typeof global !== 'undefined') { - if (global[preventBrowserDropEventsDone]) return; - global[preventBrowserDropEventsDone] = true; - } - document.addEventListener('drop', handleDrop, false); - document.addEventListener('dragenter', preventDrag, false); - document.addEventListener('dragover', preventDrag, false); -} +var NAMESPACE = (__webpack_require__(/*! ./conventions */ "./node_modules/@xmldom/xmldom/lib/conventions.js").NAMESPACE); -/** @internal */ -function preventDrag(e) { - e.stopPropagation(); - e.preventDefault(); -} +//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] +//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] +//[5] Name ::= NameStartChar (NameChar)* +var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF +var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); +var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); +//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ +//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') -/** @internal */ -function handleDrop(e) { - if (e.dataTransfer.files.length > 0) { - if (!global.confirm('Are you sure you want to drop this file here? (Cancel opens it in a new tab)')) { - e.stopPropagation(); - e.preventDefault(); - (0, _debug.log)('@@@@ document-level DROP suppressed: ' + e.dataTransfer.dropEffect); - } - } -} +//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE +//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE +var S_TAG = 0;//tag name offerring +var S_ATTR = 1;//attr name offerring +var S_ATTR_SPACE=2;//attr name end and space offer +var S_EQ = 3;//=space? +var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) +var S_ATTR_END = 5;//attr value end and no space(quot end) +var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) +var S_TAG_CLOSE = 7;//closed el /** - * Get a folder's own filename in the directory tree. Also works for - * domain names; the URL protocol ('https://') acts as the tree root - * with short name '/' (see also test/unit/acl/acl-control.test.ts). - * - * ```typescript - * shortNameForFolder($rdf.namedNode('http://example.com/some/folder/')) - * // 'folder' - * - * shortNameForFolder($rdf.namedNode('http://example.com/some/folder')) - * // 'folder' - * - * shortNameForFolder($rdf.namedNode('http://example.com/')) - * // 'example.com' - * - * shortNameForFolder($rdf.namedNode('http://example.com')) - * // 'example.com' - * - * shortNameForFolder($rdf.namedNode('http://')) - * // '/' - * ``` - * - * It also works with relative URLs: - * ```typescript - * shortNameForFolder($rdf.namedNode('../folder/')) - * // 'folder' - * ``` + * Creates an error that will not be caught by XMLReader aka the SAX parser. * - * @param x RDF Node for the folder URL - * @returns Short name for the folder + * @param {string} message + * @param {any?} locator Optional, can provide details about the location in the source + * @constructor */ -function shortNameForFolder(x) { - var str = x.uri; - - // Strip the trailing slash - if (str.slice(-1) === '/') { - str = str.slice(0, -1); - } - - // Remove the path if present, keeping only the part - // after the last slash. - var slash = str.lastIndexOf('/'); - if (slash >= 0) { - str = str.slice(slash + 1); - } - // Return the folder's filename, or '/' if nothing found - // (but see https://github.com/solidos/solid-ui/issues/196 - // regarding whether this happens at the domain root or - // not) - return str || '/'; +function ParseError(message, locator) { + this.message = message + this.locator = locator + if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError); } +ParseError.prototype = new Error(); +ParseError.prototype.name = ParseError.name -/** - * A wrapper that retrieves ACL data and uses it - * to render an [[AccessController]] component. - * Presumably the '5' is a version number of some sort, - * but all we know is it was already called ACLControlBox5 - * when it was introduced into solid-ui in - * https://github.com/solidos/solid-ui/commit/948b874bd93e7bf5160e6e224821b888f07d15f3#diff-4192a29f38a0ababd563b36b47eba5bbR54 - */ -function ACLControlBox5(subject, context, noun, kb) { - var dom = context.dom; - var doc = subject.doc(); // The ACL is actually to the doc describing the thing - var classes = (0, _jss.getClasses)(dom.head, _styles.styles).classes; - var container = dom.createElement('div'); - container.classList.add(classes.aclControlBoxContainer); - var header = container.appendChild(dom.createElement('h1')); - header.textContent = "Sharing for ".concat(noun, " ").concat(utils.label(subject)); - header.classList.add(classes.aclControlBoxHeader); - var status = container.appendChild(dom.createElement('div')); - status.classList.add(classes.aclControlBoxStatus); - try { - loadController(doc, kb, subject, noun, context, classes, dom, status).then(function (controller) { - return container.appendChild(controller.render()); - }); - } catch (error) { - status.innerText = error; - } - return container; -} -function loadController(_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8) { - return _loadController.apply(this, arguments); -} -function _loadController() { - _loadController = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(doc, kb, subject, noun, context, classes, dom, status) { - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) switch (_context2.prev = _context2.next) { - case 0: - return _context2.abrupt("return", new Promise(function (resolve, reject) { - return (0, _acl.getACLorDefault)(doc, /*#__PURE__*/function () { - var _ref = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(ok, isDirectACL, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc) { - var targetDirectory, targetIsProtected, prospectiveDefaultHolder, getController; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - getController = function _getController(prospectiveDefaultHolder) { - return new _accessController.AccessController(subject, noun, context, status, classes, targetIsProtected, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc, prospectiveDefaultHolder, kb, dom); - }; - if (ok) { - _context.next = 3; - break; - } - return _context.abrupt("return", reject(new Error("Error reading ".concat(isDirectACL ? '' : ' default ', "ACL. status ").concat(targetDoc, ": ").concat(targetACLDoc)))); - case 3: - targetDirectory = getDirectory(targetDoc); - targetIsProtected = isStorage(targetDoc, targetACLDoc, kb) || hasProtectedAcl(targetDoc); - if (!(!targetIsProtected && targetDirectory)) { - _context.next = 16; - break; - } - _context.prev = 6; - _context.next = 9; - return (0, _acl.getProspectiveHolder)(targetDirectory); - case 9: - prospectiveDefaultHolder = _context.sent; - return _context.abrupt("return", resolve(getController(prospectiveDefaultHolder))); - case 13: - _context.prev = 13; - _context.t0 = _context["catch"](6); - // No need to show this error in status, but good to warn about it in console - (0, _debug.warn)(_context.t0); - case 16: - return _context.abrupt("return", resolve(getController())); - case 17: - case "end": - return _context.stop(); - } - }, _callee, null, [[6, 13]]); - })); - return function (_x9, _x10, _x11, _x12, _x13, _x14) { - return _ref.apply(this, arguments); - }; - }()); - })); - case 1: - case "end": - return _context2.stop(); - } - }, _callee2); - })); - return _loadController.apply(this, arguments); -} -function getDirectory(doc) { - var str = doc.uri.split('#')[0]; - var p = str.slice(0, -1).lastIndexOf('/'); - var q = str.indexOf('//'); - return q >= 0 && p < q + 2 || p < 0 ? null : str.slice(0, p + 1); -} -function isStorage(doc, aclDoc, store) { - // @@ TODO: The methods used for targetIsStorage are HACKs - it should not be relied upon, and work is - // @@ underway to standardize a behavior that does not rely upon this hack - // @@ hopefully fixed as part of https://github.com/solidos/data-interoperability-panel/issues/10 - return store.holds(doc, ns.rdf('type'), ns.space('Storage'), aclDoc); -} -function hasProtectedAcl(targetDoc) { - // @@ TODO: This is hacky way of knowing whether or not a certain ACL file can be removed - // Hopefully we'll find a better, standardized solution to this - https://github.com/solidos/specification/issues/37 - return targetDoc.uri === targetDoc.site().uri; -} +function XMLReader(){ -/** @internal */ -function setGlobalWindow(window) { - global = window; } -//# sourceMappingURL=acl-control.js.map - -/***/ }), - -/***/ "./lib/acl/acl.js": -/*!************************!*\ - !*** ./lib/acl/acl.js ***! - \************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; - - -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.ACLToString = ACLToString; -exports.ACLbyCombination = ACLbyCombination; -exports.ACLunion = ACLunion; -exports.adoptACLDefault = adoptACLDefault; -exports.comboToString = comboToString; -exports.fixIndividualACL = fixIndividualACL; -exports.fixIndividualCardACL = fixIndividualCardACL; -exports.getACL = getACL; -exports.getACLorDefault = getACLorDefault; -exports.getProspectiveHolder = getProspectiveHolder; -exports.loadUnionACL = loadUnionACL; -exports.makeACLGraph = makeACLGraph; -exports.makeACLGraphbyCombo = makeACLGraphbyCombo; -exports.makeACLString = makeACLString; -exports.putACLObject = putACLObject; -exports.putACLbyCombo = putACLbyCombo; -exports.readACL = readACL; -exports.sameACL = sameACL; -exports.setACL = setACL; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var ns = _interopRequireWildcard(__webpack_require__(/*! ../ns */ "./lib/ns.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "../solid-logic/lib/index.js"); -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _rdflib = __webpack_require__(/*! rdflib */ "../rdflib/esm/index.js"); -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); } -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; } -/** - * Non-UI functions for access control. - * See https://github.com/solidos/web-access-control-spec - * for the spec that defines how ACL documents work. - * @packageDocumentation - */ +XMLReader.prototype = { + parse:function(source,defaultNSMap,entityMap){ + var domBuilder = this.domBuilder; + domBuilder.startDocument(); + _copy(defaultNSMap ,defaultNSMap = {}) + parse(source,defaultNSMap,entityMap, + domBuilder,this.errorHandler); + domBuilder.endDocument(); + } +} +function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ + function fixedFromCharCode(code) { + // String.prototype.fromCharCode does not supports + // > 2 bytes unicode chars directly + if (code > 0xffff) { + code -= 0x10000; + var surrogate1 = 0xd800 + (code >> 10) + , surrogate2 = 0xdc00 + (code & 0x3ff); -var kb = _solidLogic.solidLogicSingleton.store; + return String.fromCharCode(surrogate1, surrogate2); + } else { + return String.fromCharCode(code); + } + } + function entityReplacer(a){ + var k = a.slice(1,-1); + if (Object.hasOwnProperty.call(entityMap, k)) { + return entityMap[k]; + }else if(k.charAt(0) === '#'){ + return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) + }else{ + errorHandler.error('entity not found:'+a); + return a; + } + } + function appendText(end){//has some bugs + if(end>start){ + var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); + locator&&position(start); + domBuilder.characters(xt,0,end-start); + start = end + } + } + function position(p,m){ + while(p>=lineEnd && (m = linePattern.exec(source))){ + lineStart = m.index; + lineEnd = lineStart + m[0].length; + locator.lineNumber++; + //console.log('line++:',locator,startPos,endPos) + } + locator.columnNumber = p-lineStart+1; + } + var lineStart = 0; + var lineEnd = 0; + var linePattern = /.*(?:\r\n?|\n)|.*$/g + var locator = domBuilder.locator; -/** - * Take the "default" ACL and convert it into the equivlent ACL - * which the resource would have had. Return it as a new separate store. - * The "defaultForNew" predicate is also accepted, as a deprecated - * synonym for "default". - */ -function adoptACLDefault(doc, aclDoc, defaultResource, defaultACLDoc) { - var ACL = ns.acl; - var isContainer = doc.uri.slice(-1) === '/'; // Give default for all directories + var parseStack = [{currentNSMap:defaultNSMapCopy}] + var closeMap = {}; + var start = 0; + while(true){ + try{ + var tagStart = source.indexOf('<',start); + if(tagStart<0){ + if(!source.substr(start).match(/^\s*$/)){ + var doc = domBuilder.doc; + var text = doc.createTextNode(source.substr(start)); + doc.appendChild(text); + domBuilder.currentElement = text; + } + return; + } + if(tagStart>start){ + appendText(tagStart); + } + switch(source.charAt(tagStart+1)){ + case '/': + var end = source.indexOf('>',tagStart+3); + var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, ''); + var config = parseStack.pop(); + if(end<0){ - var defaults = kb.each(undefined, ACL('default'), defaultResource, defaultACLDoc).concat(kb.each(undefined, ACL('defaultForNew'), defaultResource, defaultACLDoc)); - var proposed = defaults.reduce(function (accumulatedStatements, da) { - return accumulatedStatements.concat(kb.statementsMatching(da, ns.rdf('type'), ACL('Authorization'), defaultACLDoc)).concat(kb.statementsMatching(da, ACL('agent'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('agentClass'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('agentGroup'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('origin'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('originClass'), undefined, defaultACLDoc)).concat(kb.statementsMatching(da, ACL('mode'), undefined, defaultACLDoc)).concat((0, _rdflib.st)(da, ACL('accessTo'), doc, defaultACLDoc)).concat(isContainer ? (0, _rdflib.st)(da, ACL('default'), doc, defaultACLDoc) : []); - }, []); - var kb2 = (0, _rdflib.graph)(); // Potential - derived is kept apart - proposed.forEach(function (st) { - return kb2.add(move(st.subject), move(st.predicate), move(st.object), (0, _rdflib.sym)(aclDoc.uri)); - }); - return kb2; - function move(symbol) { - var y = defaultACLDoc.uri.length; // The default ACL file - return (0, _rdflib.sym)(symbol.uri.slice(0, y) === defaultACLDoc.uri ? aclDoc.uri + symbol.uri.slice(y) : symbol.uri); - } -} + tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); + errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); + end = tagStart+1+tagName.length; + }else if(tagName.match(/\s 2 && arguments[2] !== undefined ? arguments[2] : kb; - var getDefaults = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; - var auths = getDefaults ? getDefaultsFallback(kb2, ns) : kb2.each(undefined, ns.acl('accessTo'), doc); - var ACL = ns.acl; - var ac = { - agent: {}, - agentClass: {}, - agentGroup: {}, - origin: {}, - originClass: {} - }; - Object.keys(ac).forEach(function (pred) { - auths.forEach(function (a) { - kb2.each(a, ACL('mode')).forEach(function (mode) { - kb2.each(a, ACL(pred)).forEach(function (agent) { - ac[pred][agent.uri] = ac[pred][agent.uri] || {}; - ac[pred][agent.uri][mode.uri] = a; // could be "true" but leave pointer just in case - }); - }); - }); - }); + end++; + break; + // end elment + case '?':// + locator&&position(tagStart); + end = parseInstruction(source,tagStart,domBuilder); + break; + case '!':// start){ + start = end; + }else{ + //TODO: 这里有可能sax回退,有位置错误风险 + appendText(Math.max(tagStart,start)+1); + } + } } -/** - * Merge ACLs lists from things to form union - */ -function loadUnionACL(subjectList, callbackFunction) { - var aclList = []; - var doList = function doList(list) { - if (list.length) { - var doc = list.shift().doc(); - getACLorDefault(doc, function (ok, p2, targetDoc, targetACLDoc, defaultHolder, defaultACLDoc) { - var defa = !p2; - if (!ok || !defaultHolder || !defaultACLDoc) return callbackFunction(ok, targetACLDoc); - var acl = defa ? readACL(defaultHolder, defaultACLDoc) : readACL(targetDoc, targetACLDoc); - aclList.push(acl); - doList(list.slice(1)); - }); - } else { - // all gone - callbackFunction(true, ACLunion(aclList)); - } - }; - doList(subjectList); +function copyLocator(f,t){ + t.lineNumber = f.lineNumber; + t.columnNumber = f.columnNumber; + return t; } /** - * Represents these as an RDF graph by combination of modes - * - * Each agent can only be in one place in this model, one combination of modes. - * Combos are like full control, read append, read only etc. + * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); + * @return end of the elementStartPart(end of elementEndPart for selfClosed el) */ -function ACLbyCombination(ac) { - var byCombo = {}; - ['agent', 'agentClass', 'agentGroup', 'origin', 'originClass'].forEach(function (pred) { - for (var agent in ac[pred]) { - var combo = []; - for (var mode in ac[pred][agent]) { - combo.push(mode); - } - combo.sort(); - var combo2 = combo.join('\n'); - if (!byCombo[combo2]) byCombo[combo2] = []; - byCombo[combo2].push([pred, agent]); - } - }); - return byCombo; -} +function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ -/** - * Write ACL graph to store from AC - */ -function makeACLGraph(kb, x, ac, aclDoc) { - var byCombo = ACLbyCombination(ac); - return makeACLGraphbyCombo(kb, x, byCombo, aclDoc); + /** + * @param {string} qname + * @param {string} value + * @param {number} startIndex + */ + function addAttribute(qname, value, startIndex) { + if (el.attributeNames.hasOwnProperty(qname)) { + errorHandler.fatalError('Attribute ' + qname + ' redefined') + } + el.addValue( + qname, + // @see https://www.w3.org/TR/xml/#AVNormalize + // since the xmldom sax parser does not "interpret" DTD the following is not implemented: + // - recursive replacement of (DTD) entity references + // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA + value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer), + startIndex + ) + } + var attrName; + var value; + var p = ++start; + var s = S_TAG;//status + while(true){ + var c = source.charAt(p); + switch(c){ + case '=': + if(s === S_ATTR){//attrName + attrName = source.slice(start,p); + s = S_EQ; + }else if(s === S_ATTR_SPACE){ + s = S_EQ; + }else{ + //fatalError: equal must after attrName or space after attrName + throw new Error('attribute equal must after attrName'); // No known test case + } + break; + case '\'': + case '"': + if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE + ){//equal + if(s === S_ATTR){ + errorHandler.warning('attribute value must after "="') + attrName = source.slice(start,p) + } + start = p+1; + p = source.indexOf(c,start) + if(p>0){ + value = source.slice(start, p); + addAttribute(attrName, value, start-1); + s = S_ATTR_END; + }else{ + //fatalError: no end quot match + throw new Error('attribute value no end \''+c+'\' match'); + } + }else if(s == S_ATTR_NOQUOT_VALUE){ + value = source.slice(start, p); + addAttribute(attrName, value, start); + errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); + start = p+1; + s = S_ATTR_END + }else{ + //fatalError: no equal before + throw new Error('attribute value must after "="'); // No known test case + } + break; + case '/': + switch(s){ + case S_TAG: + el.setTagName(source.slice(start,p)); + case S_ATTR_END: + case S_TAG_SPACE: + case S_TAG_CLOSE: + s =S_TAG_CLOSE; + el.closed = true; + case S_ATTR_NOQUOT_VALUE: + case S_ATTR: + break; + case S_ATTR_SPACE: + el.closed = true; + break; + //case S_EQ: + default: + throw new Error("attribute invalid close char('/')") // No known test case + } + break; + case ''://end document + errorHandler.error('unexpected end of input'); + if(s == S_TAG){ + el.setTagName(source.slice(start,p)); + } + return p; + case '>': + switch(s){ + case S_TAG: + el.setTagName(source.slice(start,p)); + case S_ATTR_END: + case S_TAG_SPACE: + case S_TAG_CLOSE: + break;//normal + case S_ATTR_NOQUOT_VALUE://Compatible state + case S_ATTR: + value = source.slice(start,p); + if(value.slice(-1) === '/'){ + el.closed = true; + value = value.slice(0,-1) + } + case S_ATTR_SPACE: + if(s === S_ATTR_SPACE){ + value = attrName; + } + if(s == S_ATTR_NOQUOT_VALUE){ + errorHandler.warning('attribute "'+value+'" missed quot(")!'); + addAttribute(attrName, value, start) + }else{ + if(!NAMESPACE.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)){ + errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') + } + addAttribute(value, value, start) + } + break; + case S_EQ: + throw new Error('attribute value missed!!'); + } +// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) + return p; + /*xml space '\x20' | #x9 | #xD | #xA; */ + case '\u0080': + c = ' '; + default: + if(c<= ' '){//space + switch(s){ + case S_TAG: + el.setTagName(source.slice(start,p));//tagName + s = S_TAG_SPACE; + break; + case S_ATTR: + attrName = source.slice(start,p) + s = S_ATTR_SPACE; + break; + case S_ATTR_NOQUOT_VALUE: + var value = source.slice(start, p); + errorHandler.warning('attribute "'+value+'" missed quot(")!!'); + addAttribute(attrName, value, start) + case S_ATTR_END: + s = S_TAG_SPACE; + break; + //case S_TAG_SPACE: + //case S_EQ: + //case S_ATTR_SPACE: + // void();break; + //case S_TAG_CLOSE: + //ignore warning + } + }else{//not space +//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE +//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE + switch(s){ + //case S_TAG:void();break; + //case S_ATTR:void();break; + //case S_ATTR_NOQUOT_VALUE:void();break; + case S_ATTR_SPACE: + var tagName = el.tagName; + if (!NAMESPACE.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) { + errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') + } + addAttribute(attrName, attrName, start); + start = p; + s = S_ATTR; + break; + case S_ATTR_END: + errorHandler.warning('attribute space is required"'+attrName+'"!!') + case S_TAG_SPACE: + s = S_ATTR; + start = p; + break; + case S_EQ: + s = S_ATTR_NOQUOT_VALUE; + start = p; + break; + case S_TAG_CLOSE: + throw new Error("elements closed character '/' and '>' must be connected to"); + } + } + }//end outer switch + //console.log('p++',p) + p++; + } } - /** - * Write ACL graph to store from combo + * @return true if has new namespace define */ -function makeACLGraphbyCombo(kb, x, byCombo, aclDoc, main, defa) { - var ACL = ns.acl; - for (var combo in byCombo) { - var pairs = byCombo[combo]; - if (!pairs.length) continue; // do not add to store when no agent - var modeURIs = combo.split('\n'); - var _short = modeURIs.map(function (u) { - return u.split('#')[1]; - }).join(''); - if (defa && !main) _short += 'Default'; // don't muddle authorizations - var _a = kb.sym(aclDoc.uri + '#' + _short); - kb.add(_a, ns.rdf('type'), ACL('Authorization'), aclDoc); - if (main) { - kb.add(_a, ACL('accessTo'), x, aclDoc); - } - if (defa) { - kb.add(_a, ACL('default'), x, aclDoc); - } - for (var i = 0; i < modeURIs.length; i++) { - kb.add(_a, ACL('mode'), kb.sym(modeURIs[i]), aclDoc); - } - for (var _i = 0; _i < pairs.length; _i++) { - var pred = pairs[_i][0]; - var ag = pairs[_i][1]; - kb.add(_a, ACL(pred), kb.sym(ag), aclDoc); - } - } -} +function appendElement(el,domBuilder,currentNSMap){ + var tagName = el.tagName; + var localNSMap = null; + //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; + var i = el.length; + while(i--){ + var a = el[i]; + var qName = a.qName; + var value = a.value; + var nsp = qName.indexOf(':'); + if(nsp>0){ + var prefix = a.prefix = qName.slice(0,nsp); + var localName = qName.slice(nsp+1); + var nsPrefix = prefix === 'xmlns' && localName + }else{ + localName = qName; + prefix = null + nsPrefix = qName === 'xmlns' && '' + } + //can not set prefix,because prefix !== '' + a.localName = localName ; + //prefix == null for no ns prefix attribute + if(nsPrefix !== false){//hack!! + if(localNSMap == null){ + localNSMap = {} + //console.log(currentNSMap,0) + _copy(currentNSMap,currentNSMap={}) + //console.log(currentNSMap,1) + } + currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; + a.uri = NAMESPACE.XMLNS + domBuilder.startPrefixMapping(nsPrefix, value) + } + } + var i = el.length; + while(i--){ + a = el[i]; + var prefix = a.prefix; + if(prefix){//no prefix attribute has no namespace + if(prefix === 'xml'){ + a.uri = NAMESPACE.XML; + }if(prefix !== 'xmlns'){ + a.uri = currentNSMap[prefix || ''] -/** - * Debugging short strings for dumping ACL - * and possibly in the UI - */ -function ACLToString(ac) { - return comboToString(ACLbyCombination(ac)); + //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} + } + } + } + var nsp = tagName.indexOf(':'); + if(nsp>0){ + prefix = el.prefix = tagName.slice(0,nsp); + localName = el.localName = tagName.slice(nsp+1); + }else{ + prefix = null;//important!! + localName = el.localName = tagName; + } + //no prefix element has default namespace + var ns = el.uri = currentNSMap[prefix || '']; + domBuilder.startElement(ns,localName,tagName,el); + //endPrefixMapping and startPrefixMapping have not any help for dom builder + //localNSMap = null + if(el.closed){ + domBuilder.endElement(ns,localName,tagName); + if(localNSMap){ + for (prefix in localNSMap) { + if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) { + domBuilder.endPrefixMapping(prefix); + } + } + } + }else{ + el.currentNSMap = currentNSMap; + el.localNSMap = localNSMap; + //parseStack.push(el); + return true; + } } +function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ + if(/^(?:script|textarea)$/i.test(tagName)){ + var elEndStart = source.indexOf('',elStartEnd); + var text = source.substring(elStartEnd+1,elEndStart); + if(/[&<]/.test(text)){ + if(/^script$/i.test(tagName)){ + //if(!/\]\]>/.test(text)){ + //lexHandler.startCDATA(); + domBuilder.characters(text,0,text.length); + //lexHandler.endCDATA(); + return elEndStart; + //} + }//}else{//text area + text = text.replace(/&#?\w+;/g,entityReplacer); + domBuilder.characters(text,0,text.length); + return elEndStart; + //} -/** - * Convert a [[ComboList]] to a string - */ -function comboToString(byCombo) { - var str = ''; - for (var combo in byCombo) { - var modeURIs = combo.split('\n'); - var initials = modeURIs.map(function (u) { - return u.split('#')[1][0]; - }).join(''); - str += initials + ':'; - var pairs = byCombo[combo]; - for (var i = 0; i < pairs.length; i++) { - var pred = pairs[i][0]; - var ag = (0, _rdflib.sym)(pairs[i][1]); - str += pred === 'agent' ? '@' : ''; - str += ag.sameTerm(ns.foaf('Agent')) ? '*' : utils.label(ag); - if (i < pairs.length - 1) str += ','; - } - str += ';'; - } - return '{' + str.slice(0, -1) + '}'; // drop extra semicolon + } + } + return elStartEnd+1; } - -/** - * Write ACL graph as Turtle - */ -function makeACLString(x, ac, aclDoc) { - var kb2 = (0, _rdflib.graph)(); - makeACLGraph(kb2, x, ac, aclDoc); - return (0, _rdflib.serialize)(aclDoc, kb2, aclDoc.uri, 'text/turtle') || ''; +function fixSelfClosed(source,elStartEnd,tagName,closeMap){ + //if(tagName in closeMap){ + var pos = closeMap[tagName]; + if(pos == null){ + //console.log(tagName) + pos = source.lastIndexOf('') + if(pos',start+4); + //append comment source.substring(4,end)//'; - }, true); // capture vs bubble - col3.appendChild(button); - }, true); // capture vs bubble - } + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); +}; + + +/***/ }), + +/***/ "./node_modules/querystring/index.js": +/*!*******************************************!*\ + !*** ./node_modules/querystring/index.js ***! + \*******************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +exports.decode = exports.parse = __webpack_require__(/*! ./decode */ "./node_modules/querystring/decode.js"); +exports.encode = exports.stringify = __webpack_require__(/*! ./encode */ "./node_modules/querystring/encode.js"); + + +/***/ }), + +/***/ "./node_modules/queue-microtask/index.js": +/*!***********************************************!*\ + !*** ./node_modules/queue-microtask/index.js ***! + \***********************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/*! queue-microtask. MIT License. Feross Aboukhadijeh */ +let promise + +module.exports = typeof queueMicrotask === 'function' + ? queueMicrotask.bind(typeof window !== 'undefined' ? window : __webpack_require__.g) + // reuse resolved promise, and allocate it lazily + : cb => (promise || (promise = Promise.resolve())) + .then(cb) + .catch(err => setTimeout(() => { throw err }, 0)) + + +/***/ }), + +/***/ "./node_modules/rdflib/esm/blank-node.js": +/*!***********************************************!*\ + !*** ./node_modules/rdflib/esm/blank-node.js ***! + \***********************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ BlankNode) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); + + + + + + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - // last line with "Make new workspace" - var trLast = dom.createElement('tr'); - col2 = dom.createElement('td'); - col2.setAttribute('style', cellStyle); - col2.textContent = '+ Make a new workspace'; - col2.addEventListener('click', makeNewWorkspace); - trLast.appendChild(col2); - table.appendChild(trLast); - } // displayOptions - // console.log('kicking off async operation') - ensureLoadedPreferences(context) // kick off async operation - .then(displayOptions)["catch"](function (err) { - // console.log("err from async op") - box.appendChild(widgets.errorMessageBlock(context.dom, err)); - }); - return box; // return the box element, while login proceeds -} // selectWorkspace /** - * Creates a new instance of an app. - * - * An instance of an app could be e.g. an issue tracker for a given project, - * or a chess game, or calendar, or a health/fitness record for a person. - * - * Note that this use of the term 'app' refers more to entries in the user's - * type index than to actual software applications that use the personal data - * to which these entries point. - * - * @param dom - * @param appDetails - * @param callback - * - * @returns A div with a button in it for making a new app instance - */ -function newAppInstance(dom, appDetails, callback) { - var gotWS = function gotWS(ws, base) { - // log.debug("newAppInstance: Selected workspace = " + (ws? ws.uri : 'none')) - callback(ws, base); - }; - var div = dom.createElement('div'); - var b = dom.createElement('button'); - b.setAttribute('type', 'button'); - div.appendChild(b); - b.innerHTML = "Make new ".concat(appDetails.noun); - b.addEventListener('click', function (_event) { - div.appendChild(selectWorkspace(dom, appDetails, gotWS)); - }, false); - div.appendChild(b); - return div; -} -/** - * Retrieves whether the currently logged in user is a power user - * and/or a developer - */ -function getUserRoles() { - return _getUserRoles.apply(this, arguments); -} -/** - * Filters which panes should be available, based on the result of [[getUserRoles]] + * An RDF blank node is a Node without a URI + * @link https://rdf.js.org/data-model-spec/#blanknode-interface */ -function _getUserRoles() { - _getUserRoles = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10() { - var _yield$ensureLoadedPr, me, preferencesFile, preferencesFileError; - return _regenerator["default"].wrap(function _callee10$(_context11) { - while (1) switch (_context11.prev = _context11.next) { - case 0: - _context11.prev = 0; - _context11.next = 3; - return ensureLoadedPreferences({}); - case 3: - _yield$ensureLoadedPr = _context11.sent; - me = _yield$ensureLoadedPr.me; - preferencesFile = _yield$ensureLoadedPr.preferencesFile; - preferencesFileError = _yield$ensureLoadedPr.preferencesFileError; - if (!(!preferencesFile || preferencesFileError)) { - _context11.next = 9; - break; - } - throw new Error(preferencesFileError); - case 9: - return _context11.abrupt("return", _solidLogic.solidLogicSingleton.store.each(me, ns.rdf('type'), null, preferencesFile.doc())); - case 12: - _context11.prev = 12; - _context11.t0 = _context11["catch"](0); - debug.warn('Unable to fetch your preferences - this was the error: ', _context11.t0); - case 15: - return _context11.abrupt("return", []); - case 16: - case "end": - return _context11.stop(); +var BlankNode = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(BlankNode, _Node); + var _super = _createSuper(BlankNode); + /** + * Initializes this node + * @param [id] The identifier for the blank node + */ + function BlankNode(id) { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, BlankNode); + _this = _super.call(this, BlankNode.getId(id)); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.BlankNodeTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_8__["default"].BlankNode); + /** Whether this is a blank node */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isBlank", 1); + /** + * This type of node is a variable. + * + * Note that the existence of this property already indicates that it is a variable. + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 1); + return _this; + } + + /** + * The identifier for the blank node + */ + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(BlankNode, [{ + key: "id", + get: function get() { + return this.value; + }, + set: function set(value) { + this.value = value; + } + }, { + key: "compareTerm", + value: function compareTerm(other) { + if (this.classOrder < other.classOrder) { + return -1; } - }, _callee10, null, [[0, 12]]); - })); - return _getUserRoles.apply(this, arguments); -} -function filterAvailablePanes(_x13) { - return _filterAvailablePanes.apply(this, arguments); -} -function _filterAvailablePanes() { - _filterAvailablePanes = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(panes) { - var userRoles; - return _regenerator["default"].wrap(function _callee11$(_context12) { - while (1) switch (_context12.prev = _context12.next) { - case 0: - _context12.next = 2; - return getUserRoles(); - case 2: - userRoles = _context12.sent; - return _context12.abrupt("return", panes.filter(function (pane) { - return isMatchingAudience(pane, userRoles); - })); - case 4: - case "end": - return _context12.stop(); + if (this.classOrder > other.classOrder) { + return +1; } - }, _callee11); - })); - return _filterAvailablePanes.apply(this, arguments); -} -function isMatchingAudience(pane, userRoles) { - var audience = pane.audience || []; - return audience.reduce(function (isMatch, audienceRole) { - return isMatch && !!userRoles.find(function (role) { - return role.equals(audienceRole); - }); - }, true); -} -//# sourceMappingURL=login.js.map + if (this.id < other.id) { + return -1; + } + if (this.id > other.id) { + return +1; + } + return 0; + } + + /** + * Gets a copy of this blank node in the specified formula + * @param formula The formula + */ + }, { + key: "copy", + value: function copy(formula) { + // depends on the formula + var bnodeNew = new BlankNode(); + formula.copyTo(this, bnodeNew); + return bnodeNew; + } + }, { + key: "toCanonical", + value: function toCanonical() { + return BlankNode.NTAnonymousNodePrefix + this.value; + } + }, { + key: "toString", + value: function toString() { + return BlankNode.NTAnonymousNodePrefix + this.id; + } + }], [{ + key: "getId", + value: function getId(id) { + if (id) { + if (typeof id !== 'string') { + throw new Error('Bad id argument to new blank node: ' + id); + } + if (id.includes('#')) { + // Is a URI with hash fragment + var fragments = id.split('#'); + return fragments[fragments.length - 1]; + } + return id; + } + return 'n' + BlankNode.nextId++; + } + }]); + return BlankNode; +}(_node_internal__WEBPACK_IMPORTED_MODULE_9__["default"]); +/** + * The next unique identifier for blank nodes + */ +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(BlankNode, "nextId", 0); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(BlankNode, "NTAnonymousNodePrefix", '_:'); + /***/ }), -/***/ "./lib/matrix/index.js": -/*!*****************************!*\ - !*** ./lib/matrix/index.js ***! - \*****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "./node_modules/rdflib/esm/class-order.js": +/*!************************************************!*\ + !*** ./node_modules/rdflib/esm/class-order.js ***! + \************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.matrix = void 0; -var _matrix = __webpack_require__(/*! ./matrix */ "./lib/matrix/matrix.js"); -var matrix = { - matrixForQuery: _matrix.matrixForQuery +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** +* Class orders +*/ +var ClassOrder = { + 'Literal': 1, + 'Collection': 3, + 'Graph': 4, + 'NamedNode': 5, + 'BlankNode': 6, + 'Variable': 7 }; -exports.matrix = matrix; -//# sourceMappingURL=index.js.map +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ClassOrder); /***/ }), -/***/ "./lib/matrix/matrix.js": -/*!******************************!*\ - !*** ./lib/matrix/matrix.js ***! - \******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "./node_modules/rdflib/esm/collection.js": +/*!***********************************************!*\ + !*** ./node_modules/rdflib/esm/collection.js ***! + \***********************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Collection), +/* harmony export */ "fromValue": () => (/* binding */ fromValue) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./blank-node */ "./node_modules/rdflib/esm/blank-node.js"); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./literal */ "./node_modules/rdflib/esm/literal.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.matrixForQuery = matrixForQuery; -var utils = _interopRequireWildcard(__webpack_require__(/*! ../utils */ "./lib/utils/index.js")); -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "../rdflib/esm/index.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "../solid-logic/lib/index.js"); -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); } -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; } -// Build a 2D matrix of values -// -// dom AKA document -// query a Query object of rdflib.js with a valid pattern -// vx A variable object, the one to be used for the X variable (horiz) -// vy A variable object, the one to be used for the Y variable (vertical) -// vvalue A variable object, the one to be used for the cell value -// returns A DOM element with the matrix in it, which has a .refresh() function. -// -// Options: -// cellFunction(td, x, y, value) fill the TD element of a single cell -// xDecreasing set true for x axis to be in decreasing order. -// yDecreasing set true for y axis to be in decreasing order. -// set_x array of X values to be define initial rows (order irrelevant) -// set_y array of Y values to be define initial columns -// -// Features: -// Header row at top (x axis) and left (y-axis) generated automatically. -// Extra rows and columns are inserted as needed to hold new data points -// matrix.refresh() will re-run the query and adjust the display -var kb = _solidLogic.solidLogicSingleton.store; -function matrixForQuery(dom, query, vx, vy, vvalue, options, whenDone) { - // @@ TODO Remove need to cast to any - var matrix = dom.createElement('table'); - var header = dom.createElement('tr'); - var corner = header.appendChild(dom.createElement('td')); - corner.setAttribute('class', 'MatrixCorner'); - matrix.appendChild(header); // just one for now - matrix.lastHeader = header; // Element before data - var columns = []; // Vector - var rows = []; // Associative array - var setCell = function setCell(cell, x, y, value) { - while (cell.firstChild) { - // Empty any previous - cell.removeChild(cell.firstChild); - } - cell.setAttribute('style', ''); - cell.style.textAlign = 'center'; - if (options.cellFunction) { - options.cellFunction(cell, x, y, value); - } else { - cell.textContent = utils.label(value); - cell.setAttribute('style', 'padding: 0.3em'); - } - delete cell.old; - }; - var rowFor = function rowFor(y1) { - var y = y1.toNT(); - if (rows[y]) return rows[y]; - // @@ TODO Remove need for casting to any - var tr = dom.createElement('tr'); - var header = tr.appendChild(dom.createElement('td')); - header.setAttribute('style', 'padding: 0.3em;'); - header.textContent = utils.label(y1); // first approximation - if (y1.termType === 'NamedNode') { - kb.fetcher.nowOrWhenFetched(y1.uri.split('#')[0], undefined, function (ok, _body, _response) { - if (ok) header.textContent = utils.label(y1); - }); - } - for (var i = 0; i < columns.length; i++) { - setCell(tr.appendChild(dom.createElement('td')), $rdf.fromNT(columns[i]), y1, null); - } - tr.dataValueNT = y; - rows[y] = tr; - for (var ele = matrix.lastHeader.nextSibling; ele; ele = ele.nextSibling) { - // skip header - if (y > ele.dataValueNT && options && options.yDecreasing || y < ele.dataValueNT && !(options && options.yDecreasing)) { - return matrix.insertBefore(tr, ele); // return the tr - } - } - return matrix.appendChild(tr); // return the tr - }; - var columnNumberFor = function columnNumberFor(x1) { - var xNT = x1.toNT(); // xNT is a NT string - var col = null; - // These are data columns (not headings) - for (var i = 0; i < columns.length; i++) { - if (columns[i] === xNT) { - return i; - } - if (xNT > columns[i] && options.xDecreasing || xNT < columns[i] && !options.xDecreasing) { - columns = columns.slice(0, i).concat([xNT]).concat(columns.slice(i)); - col = i; - break; - } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + + + + + + +/** + * Creates an RDF Node from a native javascript value. + * RDF Nodes are returned unchanged, undefined returned as itself. + * Arrays return Collections. + * Strings, numbers and booleans return Literals. + * @param value {Node|Date|String|Number|Boolean|Undefined} + * @return {Node|Collection} + */ +function fromValue(value) { + if (typeof value === 'undefined' || value === null) { + return value; + } + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_7__.isTerm)(value)) { + // a Node subclass or a Collection + return value; + } + if (Array.isArray(value)) { + return new Collection(value); + } + return _literal__WEBPACK_IMPORTED_MODULE_8__["default"].fromValue(value); +} + +/** + * A collection of other RDF nodes + * + * Use generic T to control the contents of the array. + */ +var Collection = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Collection, _Node); + var _super = _createSuper(Collection); + function Collection(initial) { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Collection); + _this = _super.call(this, (_blank_node__WEBPACK_IMPORTED_MODULE_9__["default"].nextId++).toString()); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_10__.CollectionTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_11__["default"].Collection); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "closed", false); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "compareTerm", _blank_node__WEBPACK_IMPORTED_MODULE_9__["default"].prototype.compareTerm); + /** + * The nodes in this collection + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "elements", []); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 0); + if (initial && initial.length > 0) { + initial.forEach(function (element) { + _this.elements.push(fromValue(element)); + }); } - if (col === null) { - col = columns.length; - columns.push(xNT); + return _this; + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Collection, [{ + key: "id", + get: function get() { + return this.value; + }, + set: function set(value) { + this.value = value; } - // col is the number of the new column, starting from 0 - for (var row = matrix.firstChild; row; row = row.nextSibling) { - // For every row header or not - var y = row.dataValueNT; - var td = dom.createElement('td'); // Add a new cell - td.style.textAlign = 'center'; - if (row === matrix.firstChild) { - td.textContent = utils.label(x1); - } else { - setCell(td, x1, $rdf.fromNT(y), null); - } - if (col === columns.length - 1) { - row.appendChild(td); - } else { - var t = row.firstChild; - for (var j = 0; j < col + 1; j++) { - // Skip header col too - t = t.nextSibling; - } - row.insertBefore(td, t); - } - } - return col; - }; - var markOldCells = function markOldCells() { - for (var i = 1; i < matrix.children.length; i++) { - var row = matrix.children[i]; - for (var j = 1; j < row.children.length; j++) { - row.children[j].old = true; - } + /** + * Appends an element to this collection + * @param element - The new element + */ + }, { + key: "append", + value: function append(element) { + return this.elements.push(element); } - }; - var clearOldCells = function clearOldCells() { - var row, cell; - var colsUsed = []; - var rowsUsed = []; - if (options.set_y) { - // Knows y values create rows - for (var k = 0; k < options.set_y.length; k++) { - rowsUsed[options.set_y[k]] = true; - } + + /** + * Closes this collection + */ + }, { + key: "close", + value: function close() { + this.closed = true; + return this.closed; } - if (options.set_x) { - for (var _k = 0; _k < options.set_x.length; _k++) { - colsUsed[columnNumberFor(options.set_x[_k]) + 1] = true; - } + + /** + * Removes the first element from the collection (and return it) + */ + }, { + key: "shift", + value: function shift() { + return this.elements.shift(); } - for (var i = 1; i < matrix.children.length; i++) { - row = matrix.children[i]; - for (var j = 1; j < row.children.length; j++) { - cell = row.children[j]; - if (cell.old) { - var y = $rdf.fromNT(row.dataValueNT); - var x = $rdf.fromNT(columns[j - 1]); - setCell(cell, x, y, null); - } else { - rowsUsed[row.dataValueNT] = true; - colsUsed[j] = true; - } - } + + /** + * Creates a new Collection with the substituting bindings applied + * @param bindings - The bindings to substitute + */ + }, { + key: "substitute", + value: function substitute(bindings) { + var elementsCopy = this.elements.map(function (ea) { + return ea.substitute(bindings); + }); + return new Collection(elementsCopy); } - for (var _i = 0; _i < matrix.children.length; _i++) { - row = matrix.children[_i]; - if (_i > 0 && !rowsUsed[row.dataValueNT]) { - delete rows[row.dataValueNT]; - matrix.removeChild(row); - } else { - for (var _j = row.children.length - 1; _j > 0; _j--) { - // backwards - var _cell = row.children[_j]; - if (!colsUsed[_j]) { - row.removeChild(_cell); - } - } - } + }, { + key: "toNT", + value: function toNT() { + return Collection.toNT(this); } - var newcolumns = []; - for (var _j2 = 0; _j2 < columns.length; _j2++) { - if (colsUsed[_j2 + 1]) { - newcolumns.push(columns[_j2]); - } + }, { + key: "toString", + value: + /** + * Serializes the collection to a string. + * Surrounded by (parentheses) and separated by spaces. + */ + function toString() { + return '(' + this.elements.join(' ') + ')'; } - columns = newcolumns; - }; - matrix.refresh = function () { - markOldCells(); - kb.query(query, addCellFromBindings, undefined, clearOldCells); - }; - var addCellFromBindings = function addCellFromBindings(bindings) { - var x = bindings[vx.toString()]; - var y = bindings[vy.toString()]; - var value = bindings[vvalue.toString()]; - var row = rowFor(y); - var colNo = columnNumberFor(x); - var cell = row.children[colNo + 1]; // number of Y axis headings - setCell(cell, x, y, value); - }; - if (options.set_y) { - // Knows y values create rows - for (var k = 0; k < options.set_y.length; k++) { - rowFor(options.set_y[k]); + + /** + * Prepends the specified element to the collection's front + * @param element - The element to prepend + */ + }, { + key: "unshift", + value: function unshift(element) { + return this.elements.unshift(element); } - } - if (options.set_x) { - for (var _k2 = 0; _k2 < options.set_x.length; _k2++) { - columnNumberFor(options.set_x[_k2]); + }], [{ + key: "toNT", + value: function toNT(collection) { + // return '(' + collection.elements.map(x => x.toNT()).join(' ') + ')' + // As lists are not in NT and toNT() must be a reversible function, we kludge it for a list + return _blank_node__WEBPACK_IMPORTED_MODULE_9__["default"].NTAnonymousNodePrefix + collection.id; } - } - kb.query(query, addCellFromBindings, undefined, whenDone); // Populate the matrix - return matrix; -} -//# sourceMappingURL=matrix.js.map + }]); + return Collection; +}(_node_internal__WEBPACK_IMPORTED_MODULE_12__["default"]); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Collection, "termType", _types__WEBPACK_IMPORTED_MODULE_10__.CollectionTermType); + /***/ }), -/***/ "./lib/media/index.js": -/*!****************************!*\ - !*** ./lib/media/index.js ***! - \****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "./node_modules/rdflib/esm/default-graph.js": +/*!**************************************************!*\ + !*** ./node_modules/rdflib/esm/default-graph.js ***! + \**************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ DefaultGraph), +/* harmony export */ "isDefaultGraph": () => (/* binding */ isDefaultGraph) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./utils/default-graph-uri */ "./node_modules/rdflib/esm/utils/default-graph-uri.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.media = void 0; -var _mediaCapture = __webpack_require__(/*! ./media-capture */ "./lib/media/media-capture.js"); -var media = { - cameraCaptureControl: _mediaCapture.cameraCaptureControl, - cameraButton: _mediaCapture.cameraButton -}; -exports.media = media; -//# sourceMappingURL=index.js.map -/***/ }), -/***/ "./lib/media/media-capture.js": -/*!************************************!*\ - !*** ./lib/media/media-capture.js ***! - \************************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { -"use strict"; -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.cameraButton = cameraButton; -exports.cameraCaptureControl = cameraCaptureControl; -var _regenerator = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js")); -var _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/asyncToGenerator.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ../debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ../iconBase */ "./lib/iconBase.js"); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ../widgets */ "./lib/widgets/index.js")); -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); } -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; } -/// ///////////////////////////////////////////// -// -// Media input widget -// -// -// Workflow: -// The HTML5 functionality (on mobille) is to prompt for either -// a realtime camera capture , OR a selection from images already ont the device -// (eg camera roll). -// -// The solid alternative is to either take a phtoto -// or access cemra roll (etc) OR to access solid cloud storage of favorite photo almbums. -// (Especially latest taken ones) -// +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -/** @module mediaCapture */ -var cameraIcon = _iconBase.icons.iconBase + 'noun_Camera_1618446_000000.svg'; // Get it from github -var retakeIcon = _iconBase.icons.iconBase + 'noun_479395.svg'; // Get it from github -var canvasWidth = '640'; -var canvasHeight = '480'; -var controlStyle = "border-radius: 0.5em; margin: 0.8em; width: ".concat(canvasWidth, "; height:").concat(canvasHeight, ";"); -// const controlStyle = 'border-radius: 0.5em; margin: 0.8em; width: 320; height:240;' -var contentType = 'image/png'; -/** A control to capture a picture using camera - * @param {Docuemnt} dom - The Document object - * @param {IndexedForumla} store - The quadstore to store data in - * @param {NamedNode} getImageDoc() - NN of the image file to be created - * @param {function} doneCallback - Called when a picture has been taken - */ -function cameraCaptureControl(dom, store, getImageDoc, doneCallback) { - var div = dom.createElement('div'); - var destination, imageBlob, player, canvas; - var table = div.appendChild(dom.createElement('table')); - var mainTR = table.appendChild(dom.createElement('tr')); - var main = mainTR.appendChild(dom.createElement('td')); - main.setAttribute('colspan', '4'); - var buttons = table.appendChild(dom.createElement('tr')); - buttons.appendChild(dom.createElement('td')) // Cancel button - .appendChild(widgets.cancelButton(dom)).addEventListener('click', function (_event) { - stopVideo(); - doneCallback(null); - }); - var retakeButton = buttons.appendChild(dom.createElement('td')) // Retake button - .appendChild(widgets.button(dom, retakeIcon, 'Retake')); - retakeButton.addEventListener('click', function (_event) { - retake(); - }); - retakeButton.style.visibility = 'collapse'; // Hide for now +/** The RDF default graph */ +var DefaultGraph = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(DefaultGraph, _Node); + var _super = _createSuper(DefaultGraph); + function DefaultGraph() { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, DefaultGraph); + _this = _super.call(this, ''); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "value", ''); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.DefaultGraphTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "uri", _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_8__.defaultGraphURI); + return _this; + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(DefaultGraph, [{ + key: "toCanonical", + value: function toCanonical() { + return this.value; + } + }, { + key: "toString", + value: function toString() { + return 'DefaultGraph'; + } + }]); + return DefaultGraph; +}(_node_internal__WEBPACK_IMPORTED_MODULE_9__["default"]); - var shutterButton = buttons.appendChild(dom.createElement('td')) // Trigger capture button - .appendChild(widgets.button(dom, _iconBase.icons.iconBase + 'noun_10636.svg', 'Snap')); - shutterButton.addEventListener('click', grabCanvas); - shutterButton.style.visibility = 'collapse'; // Hide for now +function isDefaultGraph(object) { + return !!object && object.termType === _types__WEBPACK_IMPORTED_MODULE_7__.DefaultGraphTermType; +} - var sendButton = buttons.appendChild(dom.createElement('td')) // Confirm and save button - .appendChild(widgets.continueButton(dom)); // @@ or send icon?? - sendButton.addEventListener('click', function (_event) { - saveBlob(imageBlob, destination); - }); - sendButton.style.visibility = 'collapse'; // Hide for now +/***/ }), - function displayPlayer() { - player = main.appendChild(dom.createElement('video')); - player.setAttribute('controls', '1'); - player.setAttribute('autoplay', '1'); - player.setAttribute('style', controlStyle); - if (!navigator.mediaDevices) { - throw new Error('navigator.mediaDevices not available'); - } - navigator.mediaDevices.getUserMedia(constraints).then(function (stream) { - player.srcObject = stream; - shutterButton.style.visibility = 'visible'; // Enable - sendButton.style.visibility = 'collapse'; - retakeButton.style.visibility = 'collapse'; - }); - } - var constraints = { - video: true - }; - function retake() { - main.removeChild(canvas); - displayPlayer(); // Make new one as old one is stuck black - } +/***/ "./node_modules/rdflib/esm/empty.js": +/*!******************************************!*\ + !*** ./node_modules/rdflib/esm/empty.js ***! + \******************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - function grabCanvas() { - // Draw the video frame to the canvas. - canvas = dom.createElement('canvas'); - canvas.setAttribute('width', canvasWidth); - canvas.setAttribute('height', canvasHeight); - canvas.setAttribute('style', controlStyle); - main.appendChild(canvas); - var context = canvas.getContext('2d'); - context.drawImage(player, 0, 0, canvas.width, canvas.height); - player.parentNode.removeChild(player); - canvas.toBlob(function (blob) { - var msg = "got blob type ".concat(blob.type, " size ").concat(blob.size); - debug.log(msg); - destination = getImageDoc(); - imageBlob = blob; // save for review - reviewImage(); - // alert(msg) - }, contentType); // toBlob - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Empty) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); - function reviewImage() { - sendButton.style.visibility = 'visible'; - retakeButton.style.visibility = 'visible'; - shutterButton.style.visibility = 'collapse'; // Hide for now - } - function stopVideo() { - if (player && player.srcObject) { - player.srcObject.getVideoTracks().forEach(function (track) { - return track.stop(); - }); - } - } - function saveBlob(blob, destination) { - var contentType = blob.type; - // if (!confirm('Save picture to ' + destination + ' ?')) return - debug.log('Putting ' + blob.size + ' bytes of ' + contentType + ' to ' + destination) - // @@ TODO Remove casting - ; - store.fetcher.webOperation('PUT', destination.uri, { - data: blob, - contentType: contentType - }).then(function (_resp) { - debug.log('ok saved ' + destination); - stopVideo(); - doneCallback(destination); - }, function (err) { - stopVideo(); - alert(err); - }); - } - // Attach the video stream to the video element and autoplay. - displayPlayer(); - return div; -} -/** A button to capture a picture using camera - * @param {Docuemnt} dom - The Document object - * @param {IndexedForumla} store - The quadstore to store data in - * @param {fuunction} getImageDoc - returns NN of the image file to be created - * @param {function} doneCallback - called with the image taken - * @returns {DomElement} - A div element with the buton in it - * - * This expacts the buttton to a large control when it is pressed - */ -function cameraButton(dom, store, getImageDoc, doneCallback) { - var div = dom.createElement('div'); - var but = widgets.button(dom, cameraIcon, 'Take picture'); - var control; - function restoreButton(_x) { - return _restoreButton.apply(this, arguments); - } - function _restoreButton() { - _restoreButton = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(imageDoc) { - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) switch (_context.prev = _context.next) { - case 0: - div.removeChild(control); - div.appendChild(but); - doneCallback(imageDoc); - case 3: - case "end": - return _context.stop(); - } - }, _callee); - })); - return _restoreButton.apply(this, arguments); + + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + + +/** +* An empty node +*/ +var Empty = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Empty, _Node); + var _super = _createSuper(Empty); + function Empty() { + var _this; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Empty); + _this = _super.call(this, ''); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.EmptyTermType); + return _this; } - div.appendChild(but); - but.addEventListener('click', function (_event) { - div.removeChild(but); - control = cameraCaptureControl(dom, store, getImageDoc, restoreButton); - div.appendChild(control); - }); - return div; -} -//# sourceMappingURL=media-capture.js.map + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Empty, [{ + key: "toString", + value: function toString() { + return '()'; + } + }]); + return Empty; +}(_node_internal__WEBPACK_IMPORTED_MODULE_8__["default"]); + /***/ }), -/***/ "./lib/messageArea.js": -/*!****************************!*\ - !*** ./lib/messageArea.js ***! - \****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "./node_modules/rdflib/esm/factories/canonical-data-factory.js": +/*!*********************************************************************!*\ + !*** ./node_modules/rdflib/esm/factories/canonical-data-factory.js ***! + \*********************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ "defaultGraphURI": () => (/* reexport safe */ _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_1__.defaultGraphURI) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _blank_node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../blank-node */ "./node_modules/rdflib/esm/blank-node.js"); +/* harmony import */ var _literal__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../literal */ "./node_modules/rdflib/esm/literal.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony import */ var _statement__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../statement */ "./node_modules/rdflib/esm/statement.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../variable */ "./node_modules/rdflib/esm/variable.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _default_graph__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../default-graph */ "./node_modules/rdflib/esm/default-graph.js"); +/* harmony import */ var _factory_types__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./factory-types */ "./node_modules/rdflib/esm/factories/factory-types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _utils_default_graph_uri__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../utils/default-graph-uri */ "./node_modules/rdflib/esm/utils/default-graph-uri.js"); +var _supports; -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.messageArea = messageArea; -var _iconBase = __webpack_require__(/*! ./iconBase */ "./lib/iconBase.js"); -var login = _interopRequireWildcard(__webpack_require__(/*! ./login/login */ "./lib/login/login.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "../solid-logic/lib/index.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "../rdflib/esm/index.js")); -var style = _interopRequireWildcard(__webpack_require__(/*! ./style */ "./lib/style.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ./utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ./widgets */ "./lib/widgets/index.js")); -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); } -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; } -// Common code for a discussion are a of messages about something -// -// pull in first avoid cross-refs -var UI = { - icons: _iconBase.icons, - ns: ns, - rdf: rdf, - style: style, - widgets: widgets -}; -function messageArea(dom, kb, subject, messageStore, options) { - kb = kb || _solidLogic.solidLogicSingleton.store; - messageStore = messageStore.doc(); // No hash - var ns = UI.ns; - var WF = rdf.Namespace('http://www.w3.org/2005/01/wf/flow#'); - var DCT = rdf.Namespace('http://purl.org/dc/terms/'); - options = options || {}; - var newestFirst = !!options.newestFirst; - var messageBodyStyle = 'white-space: pre-wrap; width: 90%; font-size:100%; border: 0.07em solid #eee; padding: .2em 0.5em; margin: 0.1em 1em 0.1em 1em;'; - // 'font-size: 100%; margin: 0.1em 1em 0.1em 1em; background-color: white; white-space: pre-wrap; padding: 0.1em;' - var div = dom.createElement('div'); - // eslint-disable-next-line prefer-const - var messageTable; // Shared by initial build and addMessageFromBindings - var me; - var updater = _solidLogic.solidLogicSingleton.store.updater; - var anchor = function anchor(text, term) { - // If there is no link return an element anyway - var a = dom.createElement('a'); - if (term && term.uri) { - a.setAttribute('href', term.uri); - a.addEventListener('click', UI.widgets.openHrefInOutlineMode, true); - a.setAttribute('style', 'color: #3B5998; text-decoration: none; '); // font-weight: bold - } - a.textContent = text; - return a; - }; - var mention = function mention(message, style) { - var pre = dom.createElement('pre'); - pre.setAttribute('style', style || 'color: grey'); - div.appendChild(pre); - pre.appendChild(dom.createTextNode(message)); - return pre; - }; - var announce = { - log: function log(message) { - mention(message, 'color: #111;'); - }, - warn: function warn(message) { - mention(message, 'color: #880;'); - }, - error: function error(message) { - mention(message, 'color: #800;'); - } - }; - // Form for a new message - // - var newMessageForm = function newMessageForm() { - var form = dom.createElement('tr'); - var lhs = dom.createElement('td'); - var middle = dom.createElement('td'); - var rhs = dom.createElement('td'); - form.appendChild(lhs); - form.appendChild(middle); - form.appendChild(rhs); - form.AJAR_date = '9999-01-01T00:00:00Z'; // ISO format for field sort - var sendMessage = function sendMessage() { - // titlefield.setAttribute('class','pendingedit') - // titlefield.disabled = true - field.setAttribute('class', 'pendingedit'); - field.disabled = true; - var sts = []; - var now = new Date(); - var timestamp = '' + now.getTime(); - var dateStamp = rdf.term(now); - // http://www.w3schools.com/jsref/jsref_obj_date.asp - var message = kb.sym(messageStore.uri + '#' + 'Msg' + timestamp); - sts.push(new rdf.Statement(subject, ns.wf('message'), message, messageStore)); - sts.push(new rdf.Statement(message, ns.sioc('content'), kb.literal(field.value), messageStore)); - sts.push(new rdf.Statement(message, DCT('created'), dateStamp, messageStore)); - if (me) { - sts.push(new rdf.Statement(message, ns.foaf('maker'), me, messageStore)); - } - var sendComplete = function sendComplete(uri, success, body) { - if (!success) { - form.appendChild(UI.widgets.errorMessageBlock(dom, 'Error writing message: ' + body)); - } else { - var bindings = { - '?msg': message, - '?content': kb.literal(field.value), - '?date': dateStamp, - '?creator': me - }; - renderMessage(bindings, false); // not green - field.value = ''; // clear from out for reuse - field.setAttribute('class', ''); - field.disabled = false; - } - }; - updater.update([], sts, sendComplete); - }; - form.appendChild(dom.createElement('br')); - var field, sendButton; - var turnOnInput = function turnOnInput() { - creatorAndDate(lhs, me, '', null); - field = dom.createElement('textarea'); - middle.innerHTML = ''; - middle.appendChild(field); - field.rows = 3; - // field.cols = 40 - field.setAttribute('style', messageBodyStyle + 'background-color: #eef;'); - field.addEventListener('keyup', function (e) { - // User preference? - if (e.keyCode === 13) { - if (!e.altKey) { - // Alt-Enter just adds a new line - sendMessage(); - } + + +/** + * Gets the default graph + */ +var _defaultGraph = new _default_graph__WEBPACK_IMPORTED_MODULE_2__["default"](); + +/** A basic internal RDFlib datafactory, which does not support Collections */ +var CanonicalDataFactory = { + supports: (_supports = {}, (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.collections, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.defaultGraphType, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.equalsMethod, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.identity, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.id, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.reversibleId, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_3__.Feature.variableType, true), _supports), + /** + * Creates a new blank node + * @param value - The blank node's identifier + */ + blankNode: function blankNode(value) { + return new _blank_node__WEBPACK_IMPORTED_MODULE_4__["default"](value); + }, + defaultGraph: function defaultGraph() { + return _defaultGraph; + }, + /** + * Compares to (rdf) objects for equality. + */ + equals: function equals(a, b) { + if (a === b || !a || !b) { + return true; + } + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(a) || (0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(b)) { + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(a) && (0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(b)) { + return this.equals(a.subject, b.subject) && this.equals(a.predicate, b.predicate) && this.equals(a.object, b.object) && this.equals(a.graph, b.graph); + } + return false; + } + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isTerm)(a) && (0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isTerm)(b)) { + return this.id(a) === this.id(b); + } + return false; + }, + /** + * Generates a uniquely identifiably *idempotent* string for the given {term}. + * + * Equivalent to [[Term.hashString]] + * + * @example Use this to associate data with a term in an object + * { obj[id(term)] = "myData" } + */ + id: function id(term) { + if (!term) { + return 'undefined'; + } + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_5__.isQuad)(term)) { + return this.quadToNQ(term); + } + switch (term.termType) { + case _types__WEBPACK_IMPORTED_MODULE_6__.DefaultGraphTermType: + return 'defaultGraph'; + case _types__WEBPACK_IMPORTED_MODULE_6__.VariableTermType: + return _variable__WEBPACK_IMPORTED_MODULE_7__["default"].toString(term); + default: + var nq = this.termToNQ(term); + if (nq) { + return nq; } - }, false); - rhs.innerHTML = ''; - sendButton = UI.widgets.button(dom, UI.icons.iconBase + 'noun_383448.svg', 'Send'); - sendButton.setAttribute('style', UI.style.buttonStyle + 'float: right;'); - sendButton.addEventListener('click', sendMessage, false); - rhs.appendChild(sendButton); - }; - var context = { - div: middle, - dom: dom - }; - login.ensureLoggedIn(context).then(function (context) { - me = context.me; - turnOnInput(); - }); - return form; - }; - function nick(person) { - var s = _solidLogic.solidLogicSingleton.store.any(person, UI.ns.foaf('nick')); - if (s) return '' + s.value; - return '' + utils.label(person); - } - function creatorAndDate(td1, creator, date, message) { - var nickAnchor = td1.appendChild(anchor(nick(creator), creator)); - if (creator.uri) { - _solidLogic.solidLogicSingleton.store.fetcher.nowOrWhenFetched(creator.doc(), undefined, function (_ok, _body) { - nickAnchor.textContent = nick(creator); - }); + throw new Error("Can't id term with type '".concat(term.termType, "'")); } - td1.appendChild(dom.createElement('br')); - td1.appendChild(anchor(date, message)); + }, + isQuad: function isQuad(obj) { + return obj instanceof _statement__WEBPACK_IMPORTED_MODULE_8__["default"]; + }, + /** + * Creates a new literal node. Does some JS literal parsing for ease of use. + * @param value - The lexical value + * @param languageOrDatatype - Either the language or the datatype + */ + literal: function literal(value, languageOrDatatype) { + if (typeof value !== "string" && !languageOrDatatype) { + return _literal__WEBPACK_IMPORTED_MODULE_9__["default"].fromValue(value); + } + var strValue = typeof value === 'string' ? value : '' + value; + if (typeof languageOrDatatype === 'string') { + if (languageOrDatatype.indexOf(':') === -1) { + return new _literal__WEBPACK_IMPORTED_MODULE_9__["default"](strValue, languageOrDatatype); + } else { + return new _literal__WEBPACK_IMPORTED_MODULE_9__["default"](strValue, null, this.namedNode(languageOrDatatype)); + } + } else { + return new _literal__WEBPACK_IMPORTED_MODULE_9__["default"](strValue, null, languageOrDatatype); + } + }, + /** + * Creates a new named node + * @param value - The new named node + */ + namedNode: function namedNode(value) { + return new _named_node__WEBPACK_IMPORTED_MODULE_10__["default"](value); + }, + /** + * Creates a new statement + * @param subject - The subject + * @param predicate - The predicate + * @param object - The object + * @param graph - The containing graph + */ + quad: function quad(subject, predicate, object, graph) { + return new _statement__WEBPACK_IMPORTED_MODULE_8__["default"](subject, predicate, object, graph || _defaultGraph); + }, + /** + * Creates a new statement + * @param subject - The subject + * @param predicate - The predicate + * @param object - The object + * @param graph - The containing graph + */ + triple: function triple(subject, predicate, object, graph) { + return this.quad(subject, predicate, object, graph); + }, + quadToNQ: function quadToNQ(q) { + return "".concat(this.termToNQ(q.subject), " ").concat(this.termToNQ(q.predicate), " ").concat(this.termToNQ(q.object), " ").concat(this.termToNQ(q.graph), " ."); + }, + /** Stringify a {term} to n-quads serialization. */termToNQ: function termToNQ(term) { + var _this = this; + switch (term.termType) { + case _types__WEBPACK_IMPORTED_MODULE_6__.BlankNodeTermType: + return '_:' + term.value; + case _types__WEBPACK_IMPORTED_MODULE_6__.DefaultGraphTermType: + return ''; + case _types__WEBPACK_IMPORTED_MODULE_6__.EmptyTermType: + return ''; + case _types__WEBPACK_IMPORTED_MODULE_6__.LiteralTermType: + return _literal__WEBPACK_IMPORTED_MODULE_9__["default"].toNT(term); + case _types__WEBPACK_IMPORTED_MODULE_6__.GraphTermType: + case _types__WEBPACK_IMPORTED_MODULE_6__.NamedNodeTermType: + return '<' + term.value + '>'; + case _types__WEBPACK_IMPORTED_MODULE_6__.CollectionTermType: + return '(' + term.elements.map(function (t) { + return _this.termToNQ(t); + }).join(' ') + ')'; + default: + throw new Error("Can't serialize nonstandard term type (was '".concat(term.termType, "')")); + } + }, + /** Convert an rdf object (term or quad) to n-quads serialization. */toNQ: function toNQ(term) { + if (this.isQuad(term)) { + return this.quadToNQ(term); + } + return this.termToNQ(term); + }, + /** + * Creates a new variable + * @param name - The name for the variable + */ + variable: function variable(name) { + return new _variable__WEBPACK_IMPORTED_MODULE_7__["default"](name); } +}; + +/** Contains the factory methods as defined in the spec, plus id */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (CanonicalDataFactory); + +/***/ }), + +/***/ "./node_modules/rdflib/esm/factories/extended-term-factory.js": +/*!********************************************************************!*\ + !*** ./node_modules/rdflib/esm/factories/extended-term-factory.js ***! + \********************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../collection */ "./node_modules/rdflib/esm/collection.js"); +/* harmony import */ var _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./canonical-data-factory */ "./node_modules/rdflib/esm/factories/canonical-data-factory.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _factory_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./factory-types */ "./node_modules/rdflib/esm/factories/factory-types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../variable */ "./node_modules/rdflib/esm/variable.js"); - // /////////////////////////////////////////////////////////////////////// +var _supports; +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } - function syncMessages(about, messageTable) { - var displayed = {}; - var ele, ele2; - for (ele = messageTable.firstChild; ele; ele = ele.nextSibling) { - if (ele.AJAR_subject) { - displayed[ele.AJAR_subject.uri] = true; - } - } - var messages = kb.each(about, ns.wf('message')); - var stored = {}; - messages.forEach(function (m) { - stored[m.uri] = true; - if (!displayed[m.uri]) { - addMessage(m); - } - }); - // eslint-disable-next-line space-in-parens - for (ele = messageTable.firstChild; ele;) { - ele2 = ele.nextSibling; - if (ele.AJAR_subject && !stored[ele.AJAR_subject.uri]) { - messageTable.removeChild(ele); - } - ele = ele2; - } - } - var deleteMessage = function deleteMessage(message) { - var deletions = kb.statementsMatching(message).concat(kb.statementsMatching(undefined, undefined, message)); - updater.update(deletions, [], function (uri, ok, body) { - if (!ok) { - announce.error('Cant delete messages:' + body); - } else { - syncMessages(subject, messageTable); - } - }); - }; - var addMessage = function addMessage(message) { - var bindings = { - '?msg': message, - '?creator': kb.any(message, ns.foaf('maker')), - '?date': kb.any(message, DCT('created')), - '?content': kb.any(message, ns.sioc('content')) - }; - renderMessage(bindings, true); // fresh from elsewhere - }; - var renderMessage = function renderMessage(bindings, fresh) { - var creator = bindings['?creator']; - var message = bindings['?msg']; - var date = bindings['?date']; - var content = bindings['?content']; - var dateString = date.value; - var tr = dom.createElement('tr'); - tr.AJAR_date = dateString; - tr.AJAR_subject = message; - var done = false; - for (var ele = messageTable.firstChild;; ele = ele.nextSibling) { - if (!ele) { - // empty - break; - } - if (dateString > ele.AJAR_date && newestFirst || dateString < ele.AJAR_date && !newestFirst) { - messageTable.insertBefore(tr, ele); - done = true; - break; - } + + + +/** + * Data factory which also supports Collections + * + * Necessary for preventing circular dependencies. + */ +var ExtendedTermFactory = _objectSpread(_objectSpread({}, _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"]), {}, { + supports: (_supports = {}, (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.collections, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.defaultGraphType, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.equalsMethod, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.identity, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.id, true), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.reversibleId, false), (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(_supports, _factory_types__WEBPACK_IMPORTED_MODULE_2__.Feature.variableType, true), _supports), + /** + * Creates a new collection + * @param elements - The initial element + */ + collection: function collection(elements) { + return new _collection__WEBPACK_IMPORTED_MODULE_3__["default"](elements); + }, + id: function id(term) { + var _this = this; + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_4__.isCollection)(term)) { + return "( ".concat(term.elements.map(function (e) { + return _this.id(e); + }).join(', '), " )"); } - if (!done) { - messageTable.appendChild(tr); + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_4__.isVariable)(term)) { + return _variable__WEBPACK_IMPORTED_MODULE_5__["default"].toString(term); } - var td1 = dom.createElement('td'); - tr.appendChild(td1); - creatorAndDate(td1, creator, UI.widgets.shortDate(dateString), message); - var td2 = dom.createElement('td'); - tr.appendChild(td2); - var pre = dom.createElement('p'); - pre.setAttribute('style', messageBodyStyle + (fresh ? 'background-color: #e8ffe8;' : 'background-color: #white;')); - td2.appendChild(pre); - pre.textContent = content.value; - var td3 = dom.createElement('td'); - tr.appendChild(td3); - var delButton = dom.createElement('button'); - td3.appendChild(delButton); - delButton.textContent = '-'; - tr.setAttribute('class', 'hoverControl'); // See tabbedtab.css (sigh global CSS) - delButton.setAttribute('class', 'hoverControlHide'); - delButton.setAttribute('style', 'color: red;'); - delButton.addEventListener('click', function (_event) { - td3.removeChild(delButton); // Ask -- are you sure? - var cancelButton = dom.createElement('button'); - cancelButton.textContent = 'cancel'; - td3.appendChild(cancelButton).addEventListener('click', function (_event) { - td3.removeChild(sureButton); - td3.removeChild(cancelButton); - td3.appendChild(delButton); - }, false); - var sureButton = dom.createElement('button'); - sureButton.textContent = 'Delete message'; - td3.appendChild(sureButton).addEventListener('click', function (_event) { - td3.removeChild(sureButton); - td3.removeChild(cancelButton); - deleteMessage(message); - }, false); - }, false); - }; + return _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"].id(term); + }, + termToNQ: function termToNQ(term) { + if (term.termType === _types__WEBPACK_IMPORTED_MODULE_6__.CollectionTermType) { + return _collection__WEBPACK_IMPORTED_MODULE_3__["default"].toNT(term); + } + return _canonical_data_factory__WEBPACK_IMPORTED_MODULE_1__["default"].termToNQ(term); + } +}); +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ExtendedTermFactory); - // Messages with date, author etc +/***/ }), - messageTable = dom.createElement('table'); - messageTable.fresh = false; - div.appendChild(messageTable); - messageTable.setAttribute('style', 'width: 100%;'); // fill that div! +/***/ "./node_modules/rdflib/esm/factories/factory-types.js": +/*!************************************************************!*\ + !*** ./node_modules/rdflib/esm/factories/factory-types.js ***! + \************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { - var tr = newMessageForm(); - if (newestFirst) { - messageTable.insertBefore(tr, messageTable.firstChild); // If newestFirst - } else { - messageTable.appendChild(tr); // not newestFirst - } +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Feature": () => (/* binding */ Feature) +/* harmony export */ }); +/** A set of features that may be supported by a Data Factory */ - var query; - // Do this with a live query to pull in messages from web - if (options.query) { - query = options.query; - } else { - query = new rdf.Query('Messages'); - var v = {}; // semicolon needed - var vs = ['msg', 'date', 'creator', 'content']; - vs.forEach(function (x) { - query.vars.push(v[x] = rdf.variable(x)); - }); - query.pat.add(subject, WF('message'), v.msg); - query.pat.add(v.msg, ns.dct('created'), v.date); - query.pat.add(v.msg, ns.foaf('maker'), v.creator); - query.pat.add(v.msg, ns.sioc('content'), v.content); - } - function doneQuery() { - messageTable.fresh = true; // any new are fresh and so will be greenish - } +var Feature = /*#__PURE__*/function (Feature) { + Feature["collections"] = "COLLECTIONS"; + Feature["defaultGraphType"] = "DEFAULT_GRAPH_TYPE"; + Feature["equalsMethod"] = "EQUALS_METHOD"; + Feature["id"] = "ID"; + Feature["identity"] = "IDENTITY"; + Feature["reversibleId"] = "REVERSIBLE_ID"; + Feature["variableType"] = "VARIABLE_TYPE"; + return Feature; +}({}); - kb.query(query, renderMessage, undefined, doneQuery); - div.refresh = function () { - syncMessages(subject, messageTable); - }; - // syncMessages(subject, messageTable) // no the query will do this async - return div; -} -//# sourceMappingURL=messageArea.js.map +/** + * Defines a DataFactory as used in rdflib, based on the RDF/JS: Data model specification, + * but with additional extensions + * + * bnIndex is optional but useful. + */ /***/ }), -/***/ "./lib/ns.js": -/*!*******************!*\ - !*** ./lib/ns.js ***! - \*******************/ -/***/ ((module, __unused_webpack_exports, __webpack_require__) => { +/***/ "./node_modules/rdflib/esm/factories/rdflib-data-factory.js": +/*!******************************************************************!*\ + !*** ./node_modules/rdflib/esm/factories/rdflib-data-factory.js ***! + \******************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../store */ "./node_modules/rdflib/esm/store.js"); +/* harmony import */ var _fetcher__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../fetcher */ "./node_modules/rdflib/esm/fetcher.js"); +/* harmony import */ var _extended_term_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./extended-term-factory */ "./node_modules/rdflib/esm/factories/extended-term-factory.js"); +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -var _solidNamespace = _interopRequireDefault(__webpack_require__(/*! solid-namespace */ "./node_modules/solid-namespace/index.js")); -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "../rdflib/esm/index.js")); -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); } -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; } -// Namespaces we commonly use and have common prefixes for around Solid -// - -// Delegate to this which takes RDFlib as param. -module.exports = (0, _solidNamespace["default"])($rdf); -// export * from ns2 -// ends -//# sourceMappingURL=ns.js.map +/** Full RDFLib.js Data Factory */ +var RDFlibDataFactory = _objectSpread(_objectSpread({}, _extended_term_factory__WEBPACK_IMPORTED_MODULE_1__["default"]), {}, { + /** + * Creates a new fetcher + * @param store - The store to use + * @param options - The options + */ + fetcher: function fetcher(store, options) { + return new _fetcher__WEBPACK_IMPORTED_MODULE_2__["default"](store, options); + }, + /** + * Creates a new graph (store) + */ + graph: function graph() { + var features = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; + var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + return new _store__WEBPACK_IMPORTED_MODULE_3__["default"](features, opts || { + rdfFactory: _extended_term_factory__WEBPACK_IMPORTED_MODULE_1__["default"] + }); + }, + /** + * Creates a new literal node + * @param val The lexical value + * @param lang The language + * @param dt The datatype + */ + lit: function lit(val, lang, dt) { + return this.literal('' + val, lang || dt); + }, + /** + * Creates a new statement + * @param subject The subject + * @param predicate The predicate + * @param object The object + * @param graph The containing graph + */ + st: function st(subject, predicate, object, graph) { + return this.quad(subject, predicate, object, graph); + } +}); +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (RDFlibDataFactory); /***/ }), -/***/ "./lib/pad.js": -/*!********************!*\ - !*** ./lib/pad.js ***! - \********************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "./node_modules/rdflib/esm/fetcher.js": +/*!********************************************!*\ + !*** ./node_modules/rdflib/esm/fetcher.js ***! + \********************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Fetcher) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7__); +/* harmony import */ var _store__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./store */ "./node_modules/rdflib/esm/store.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); +/* harmony import */ var _n3parser__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./n3parser */ "./node_modules/rdflib/esm/n3parser.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./namespace */ "./node_modules/rdflib/esm/namespace.js"); +/* harmony import */ var _parse__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./parse */ "./node_modules/rdflib/esm/parse.js"); +/* harmony import */ var _rdfaparser__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./rdfaparser */ "./node_modules/rdflib/esm/rdfaparser.js"); +/* harmony import */ var _rdfxmlparser__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./rdfxmlparser */ "./node_modules/rdflib/esm/rdfxmlparser.js"); +/* harmony import */ var _uri__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./uri */ "./node_modules/rdflib/esm/uri.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils-js */ "./node_modules/rdflib/esm/utils-js.js"); +/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./serialize */ "./node_modules/rdflib/esm/serialize.js"); +/* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! cross-fetch */ "./node_modules/cross-fetch/dist/browser-ponyfill.js"); +/* harmony import */ var cross_fetch__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(cross_fetch__WEBPACK_IMPORTED_MODULE_8__); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_termValue__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./utils/termValue */ "./node_modules/rdflib/esm/utils/termValue.js"); +/* harmony import */ var _jsonldparser__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./jsonldparser */ "./node_modules/rdflib/esm/jsonldparser.js"); -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.getChunks = getChunks; -exports.lightColorHash = lightColorHash; -Object.defineProperty(exports, "manageParticipation", ({ - enumerable: true, - get: function get() { - return _participation.manageParticipation; - } -})); -exports.notepad = notepad; -exports.notepadToHTML = notepadToHTML; -Object.defineProperty(exports, "participationObject", ({ - enumerable: true, - get: function get() { - return _participation.participationObject; - } -})); -Object.defineProperty(exports, "recordParticipation", ({ - enumerable: true, - get: function get() { - return _participation.recordParticipation; - } -})); -Object.defineProperty(exports, "renderPartipants", ({ - enumerable: true, - get: function get() { - return _participation.renderPartipants; - } -})); -exports.xmlEncode = xmlEncode; -var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); -var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); -var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js")); -var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js")); -var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js")); -var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js")); -var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "./node_modules/@babel/runtime/helpers/wrapNativeSuper.js")); -var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var _rdflib = __webpack_require__(/*! rdflib */ "../rdflib/esm/index.js"); -var _widgets = __webpack_require__(/*! ./widgets */ "./lib/widgets/index.js"); -var _utils = __webpack_require__(/*! ./utils */ "./lib/utils/index.js"); -var _debug = __webpack_require__(/*! ./debug */ "./lib/debug.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "../solid-logic/lib/index.js"); -var _participation = __webpack_require__(/*! ./participation */ "./lib/participation.js"); -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); } -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; } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } + + + + + + +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; } } }; } +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); } +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; } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -var store = _solidLogic.solidLogicSingleton.store; -var PAD = (0, _rdflib.Namespace)('http://www.w3.org/ns/pim/pad#'); +/* global $SolidTestEnvironment */ /** - * @ignore + * + * Project: rdflib.js + * + * @file: fetcher.js + * + * Description: contains functions for requesting/fetching/retracting + * This implements quite a lot of the web architecture. + * A fetcher is bound to a specific quad store, into which + * it loads stuff and into which it writes its metadata + * @@ The metadata could be optionally a separate graph + * + * - implements semantics of HTTP headers, Internet Content Types + * - selects parsers for rdf/xml, n3, rdfa, grddl + * + * TO do: + * - Implement a runtime registry for parsers and serializers + * - */ -var NotepadElement = /*#__PURE__*/function (_HTMLElement) { - (0, _inherits2["default"])(NotepadElement, _HTMLElement); - var _super = _createSuper(NotepadElement); - function NotepadElement() { - var _this; - (0, _classCallCheck2["default"])(this, NotepadElement); - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - _this = _super.call.apply(_super, [this].concat(args)); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "subject", void 0); - return _this; - } - return (0, _createClass2["default"])(NotepadElement); -}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(HTMLElement)); + /** - * @ignore - */ -var NotepadPart = /*#__PURE__*/function (_HTMLElement2) { - (0, _inherits2["default"])(NotepadPart, _HTMLElement2); - var _super2 = _createSuper(NotepadPart); - function NotepadPart() { - var _this2; - (0, _classCallCheck2["default"])(this, NotepadPart); - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - _this2 = _super2.call.apply(_super2, [this].concat(args)); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "subject", void 0); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "value", void 0); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "state", void 0); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this2), "lastSent", void 0); - return _this2; - } - return (0, _createClass2["default"])(NotepadPart); -}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(HTMLElement)); -/** Figure out a random color from my webid - * - * @param {NamedNode} author - The author of text being displayed - * @returns {String} The CSS color generated, constrained to be light for a background color + * Things to test: callbacks on request, refresh, retract + * loading from HTTP, HTTPS, FTP, FILE, others? + * To do: + * Firing up a mail client for mid: (message:) URLs */ -function lightColorHash(author) { - var hash = function hash(x) { - return x.split('').reduce(function (a, b) { - a = (a << 5) - a + b.charCodeAt(0); - return a & a; - }, 0); + + + + + + + + + + + + + + + + +var Parsable = { + 'text/n3': true, + 'text/turtle': true, + 'application/rdf+xml': true, + 'application/xhtml+xml': true, + 'text/html': true, + 'application/ld+json': true +}; + +// This is a minimal set to allow the use of damaged servers if necessary +var CONTENT_TYPE_BY_EXT = { + 'rdf': _types__WEBPACK_IMPORTED_MODULE_9__.RDFXMLContentType, + 'owl': _types__WEBPACK_IMPORTED_MODULE_9__.RDFXMLContentType, + 'n3': 'text/n3', + 'ttl': 'text/turtle', + 'nt': 'text/n3', + 'acl': 'text/n3', + 'html': 'text/html', + 'xml': 'text/xml' +}; + +// Convenience namespaces needed in this module. +// These are deliberately not exported as the user application should +// make its own list and not rely on the prefixes used here, +// and not be tempted to add to them, and them clash with those of another +// application. +var getNS = function getNS(factory) { + return { + link: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2007/ont/link#', factory), + http: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2007/ont/http#', factory), + httph: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2007/ont/httph#', factory), + // headers + rdf: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/1999/02/22-rdf-syntax-ns#', factory), + rdfs: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/2000/01/rdf-schema#', factory), + dc: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://purl.org/dc/elements/1.1/', factory), + ldp: (0,_namespace__WEBPACK_IMPORTED_MODULE_10__["default"])('http://www.w3.org/ns/ldp#', factory) }; - return author && author.uri ? '#' + (hash(author.uri) & 0xffffff | 0xc0c0c0).toString(16) : '#ffffff'; // c0c0c0 forces pale -} // no id -> white +}; +var ns = getNS(); -/** notepad - * - * @param {HTMLDocument} dom - the web page of the browser - * @param {NamedNode} padDoc - the document into which the particpation should be shown - * @param {NamedNode} subject - the thing in which participation is happening - * @param {NamedNode} me - person who is logged into the pod - * @param {notepadOptions} options - the options that can be passed in consist of statusArea, exists - */ -function notepad(dom, padDoc, subject, me, options) { - options = options || {}; - var exists = options.exists; - var table = dom.createElement('table'); - var kb = store; - if (me && !me.uri) throw new Error('UI.pad.notepad: Invalid userid'); - var updater = store.updater; - var PAD = (0, _rdflib.Namespace)('http://www.w3.org/ns/pim/pad#'); - table.setAttribute('style', 'padding: 1em; overflow: auto; resize: horizontal; min-width: 40em;'); - var upstreamStatus = null; - var downstreamStatus = null; - if (options.statusArea) { - var t = options.statusArea.appendChild(dom.createElement('table')); - var tr = t.appendChild(dom.createElement('tr')); - upstreamStatus = tr.appendChild(dom.createElement('td')); - downstreamStatus = tr.appendChild(dom.createElement('td')); - if (upstreamStatus) { - upstreamStatus.setAttribute('style', 'width:50%'); - } - if (downstreamStatus) { - downstreamStatus.setAttribute('style', 'width:50%'); - } +/** An extended interface of Response, since RDFlib.js adds some properties. */ + +/** tell typescript that a 'panes' child may exist on Window */ + +/** All valid inputs for initFetchOptions */ + +/** Initiated by initFetchOptions, which runs on load */ +var Handler = /*#__PURE__*/(0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(function Handler(response, dom) { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, Handler); + // TODO: Document, type + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "response", void 0); + // TODO: Document, type + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "dom", void 0); + this.response = response; + // The type assertion operator here might need to be removed. + this.dom = dom; +}); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Handler, "pattern", void 0); +var RDFXMLHandler = /*#__PURE__*/function (_Handler) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(RDFXMLHandler, _Handler); + var _super = _createSuper(RDFXMLHandler); + function RDFXMLHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, RDFXMLHandler); + return _super.apply(this, arguments); } - /* @@ TODO want to look into this, it seems upstream should be a boolean and default to false ? - * - */ - var complain = function complain(message) { - var upstream = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - (0, _debug.log)(message); - if (options.statusArea) { - ; - (upstream ? upstreamStatus : downstreamStatus).appendChild((0, _widgets.errorMessageBlock)(dom, message, 'pink')); + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(RDFXMLHandler, [{ + key: "parse", + value: function parse(fetcher, /** An XML String */ + responseText, /** Requires .original */ + options) { + var kb = fetcher.store; + if (!this.dom) { + this.dom = _utils_js__WEBPACK_IMPORTED_MODULE_11__.parseXML(responseText); + } + var root = this.dom.documentElement; + if (root.nodeName === 'parsererror') { + // Mozilla only See issue/issue110 + // have to fail the request + return fetcher.failFetch(options, 'Badly formed XML in ' + options.resource.value, 'parse_error'); + } + var parser = new _rdfxmlparser__WEBPACK_IMPORTED_MODULE_12__["default"](kb); + try { + parser.parse(this.dom, options.original.value, options.original); + } catch (err) { + return fetcher.failFetch(options, 'Syntax error parsing RDF/XML! ' + err, 'parse_error'); + } + if (!options.noMeta) { + kb.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode); + } + return fetcher.doneFetch(options, this.response); } - }; - // @@ TODO need to refactor so that we don't have to type cast - var clearStatus = function clearStatus(_upsteam) { - if (options.statusArea) { - options.statusArea.innerHTML = ''; + }], [{ + key: "toString", + value: function toString() { + return 'RDFXMLHandler'; } - }; - var setPartStyle = function setPartStyle(part, colors, pending) { - var chunk = part.subject; - colors = colors || ''; - var baseStyle = 'font-size: 100%; font-family: monospace; width: 100%; border: none; white-space: pre-wrap;'; - var headingCore = 'font-family: sans-serif; font-weight: bold; border: none;'; - var headingStyle = ['font-size: 110%; padding-top: 0.5em; padding-bottom: 0.5em; width: 100%;', 'font-size: 120%; padding-top: 1em; padding-bottom: 1em; width: 100%;', 'font-size: 150%; padding-top: 1em; padding-bottom: 1em; width: 100%;']; - var author = kb.any(chunk, ns.dc('author')); - if (!colors && author) { - // Hash the user webid for now -- later allow user selection! - var bgcolor = lightColorHash(author); - colors = 'color: ' + (pending ? '#888' : 'black') + '; background-color: ' + bgcolor + ';'; + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes[_types__WEBPACK_IMPORTED_MODULE_9__.RDFXMLContentType] = { + 'q': 0.9 + }; } + }]); + return RDFXMLHandler; +}(Handler); +RDFXMLHandler.pattern = new RegExp('application/rdf\\+xml'); +var XHTMLHandler = /*#__PURE__*/function (_Handler2) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(XHTMLHandler, _Handler2); + var _super2 = _createSuper(XHTMLHandler); + function XHTMLHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, XHTMLHandler); + return _super2.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(XHTMLHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + var relation, reverse; + if (!this.dom) { + this.dom = _utils_js__WEBPACK_IMPORTED_MODULE_11__.parseXML(responseText); + } + var kb = fetcher.store; - // @@ TODO Need to research when this can be an object with the indent stored in value - // and when the indent is stored as a Number itself, not in an object. - var indent = kb.any(chunk, PAD('indent')); - indent = indent ? indent.value : 0; - var style = indent >= 0 ? baseStyle + 'text-indent: ' + indent * 3 + 'em;' : headingCore + headingStyle[-1 - indent]; - // ? baseStyle + 'padding-left: ' + (indent * 3) + 'em;' - part.setAttribute('style', style + colors); - }; - var removePart = function removePart(part) { - var chunk = part.subject; - if (!chunk) throw new Error('No chunk for line to be deleted!'); // just in case - var prev = kb.any(undefined, PAD('next'), chunk); - var next = kb.any(chunk, PAD('next')); - if (prev.sameTerm(subject) && next.sameTerm(subject)) { - // Last one - (0, _debug.log)("You can't delete the only line."); - return; - } - var del = kb.statementsMatching(chunk, undefined, undefined, padDoc).concat(kb.statementsMatching(undefined, undefined, chunk, padDoc)); - var ins = [(0, _rdflib.st)(prev, PAD('next'), next, padDoc)]; + // dc:title + var title = this.dom.getElementsByTagName('title'); + if (title.length > 0) { + kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(title[0].textContent), options.resource); + // log.info("Inferring title of " + xhr.resource) + } - // @@ TODO what should we do if chunk is not a NamedNode should we - // assume then it is a string? - if (chunk instanceof _rdflib.NamedNode) { - var label = chunk.uri.slice(-4); - (0, _debug.log)('Deleting line ' + label); - } - if (!updater) { - throw new Error('have no updater'); - } - // @@ TODO below you can see that before is redefined and not a boolean - updater.update(del, ins, function (uri, ok, errorMessage, response) { - if (ok) { - var row = part.parentNode; - if (row) { - var before = row.previousSibling; - if (row.parentNode) { - row.parentNode.removeChild(row); - } - // console.log(' deleted line ' + label + ' ok ' + part.value) - if (before && before.firstChild) { - // @@ TODO IMPORTANT FOCUS ISN'T A PROPERTY ON A CHILDNODE - before.firstChild.focus(); - } + // link rel + var links = this.dom.getElementsByTagName('link'); + for (var x = links.length - 1; x >= 0; x--) { + // @@ rev + relation = links[x].getAttribute('rel'); + reverse = false; + if (!relation) { + relation = links[x].getAttribute('rev'); + reverse = true; + } + if (relation) { + fetcher.linkData(options.original, relation, links[x].getAttribute('href'), options.resource, reverse); } - } else if (response && response.status === 409) { - // Conflict - setPartStyle(part, 'color: black; background-color: #ffd;'); // yellow - part.state = 0; // Needs downstream refresh - (0, _utils.beep)(0.5, 512); // Ooops clash with other person - setTimeout(function () { - // Ideally, beep! @@ - reloadAndSync(); // Throw away our changes and - // updater.requestDownstreamAction(padDoc, reloadAndSync) - }, 1000); - } else { - (0, _debug.log)(' removePart FAILED ' + chunk + ': ' + errorMessage); - (0, _debug.log)(" removePart was deleteing :'" + del); - setPartStyle(part, 'color: black; background-color: #fdd;'); // failed - var res = response ? response.status : ' [no response field] '; - complain('Error ' + res + ' saving changes: ' + errorMessage["true"]); // upstream, - // updater.requestDownstreamAction(padDoc, reloadAndSync); } - }); - }; // removePart - var changeIndent = function changeIndent(part, chunk, delta) { - var del = kb.statementsMatching(chunk, PAD('indent')); - var current = del.length ? Number(del[0].object.value) : 0; - if (current + delta < -3) return; // limit negative indent - var newIndent = current + delta; - var ins = (0, _rdflib.st)(chunk, PAD('indent'), newIndent, padDoc); - if (!updater) { - throw new Error('no updater'); - } - updater.update(del, ins, function (uri, ok, errorBody) { - if (!ok) { - (0, _debug.log)("Indent change FAILED '" + newIndent + "' for " + padDoc + ': ' + errorBody); - setPartStyle(part, 'color: black; background-color: #fdd;'); // failed - updater.requestDownstreamAction(padDoc, reloadAndSync); - } else { - setPartStyle(part); // Implement the indent + // Data Islands + var scripts = this.dom.getElementsByTagName('script'); + for (var i = 0; i < scripts.length; i++) { + var contentType = scripts[i].getAttribute('type'); + if (Parsable[contentType]) { + // @ts-ignore incompatibility between Store.add and Formula.add + (0,_parse__WEBPACK_IMPORTED_MODULE_13__["default"])(scripts[i].textContent, kb, options.original.value, contentType); + // @ts-ignore incompatibility between Store.add and Formula.add + (0,_parse__WEBPACK_IMPORTED_MODULE_13__["default"])(scripts[i].textContent, kb, options.original.value, contentType); + } } - }); - }; - - // Use this sort of code to split the line when return pressed in the middle @@ - /* - function doGetCaretPosition doGetCaretPosition (oField) { - var iCaretPos = 0 - // IE Support - if (document.selection) { - // Set focus on the element to avoid IE bug - oField.focus() - // To get cursor position, get empty selection range - var oSel = document.selection.createRange() - // Move selection start to 0 position - oSel.moveStart('character', -oField.value.length) - // The caret position is selection length - iCaretPos = oSel.text.length - // Firefox suppor - } else if (oField.selectionStart || oField.selectionStart === '0') { - iCaretPos = oField.selectionStart + if (!options.noMeta) { + kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode); + } + if (!options.noRDFa && _rdfaparser__WEBPACK_IMPORTED_MODULE_14__.parseRDFaDOM) { + // enable by default + try { + (0,_rdfaparser__WEBPACK_IMPORTED_MODULE_14__.parseRDFaDOM)(this.dom, kb, options.original.value); + } catch (err) { + // @ts-ignore + var msg = 'Error trying to parse ' + options.resource + ' as RDFa:\n' + err + ':\n' + err.stack; + return fetcher.failFetch(options, msg, 'parse_error'); + } + } + return fetcher.doneFetch(options, this.response); } - // Return results - return (iCaretPos) + }], [{ + key: "toString", + value: function toString() { + return 'XHTMLHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes[_types__WEBPACK_IMPORTED_MODULE_9__.XHTMLContentType] = {}; + } + }]); + return XHTMLHandler; +}(Handler); +XHTMLHandler.pattern = new RegExp('application/xhtml'); +var XMLHandler = /*#__PURE__*/function (_Handler3) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(XMLHandler, _Handler3); + var _super3 = _createSuper(XMLHandler); + function XMLHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, XMLHandler); + return _super3.apply(this, arguments); } - */ - var addListeners = function addListeners(part, chunk) { - part.addEventListener('keydown', function (event) { - if (!updater) { - throw new Error('no updater'); - } - var queueProperty, queue; - // up 38; down 40; left 37; right 39 tab 9; shift 16; escape 27 - switch (event.keyCode) { - case 13: - // Return - { - var before = event.shiftKey; - (0, _debug.log)('enter'); // Shift-return inserts before -- only way to add to top of pad. - if (before) { - queue = kb.any(undefined, PAD('next'), chunk); - queueProperty = 'newlinesAfter'; - } else { - queue = kb.any(chunk, PAD('next')); - queueProperty = 'newlinesBefore'; - } - queue[queueProperty] = queue[queueProperty] || 0; - queue[queueProperty] += 1; - if (queue[queueProperty] > 1) { - (0, _debug.log)(' queueing newline queue = ' + queue[queueProperty]); - return; - } - (0, _debug.log)(' go ahead line before ' + queue[queueProperty]); - newChunk(part, before); // was document.activeElement - break; - } - case 8: - // Delete - if (part.value.length === 0) { - (0, _debug.log)('Delete key line ' + chunk.uri.slice(-4) + ' state ' + part.state); - switch (part.state) { - case 1: // contents being sent - case 2: - // contents need to be sent again - part.state = 4; // delete me - return; - case 3: // being deleted already - case 4: - // already deleme state - return; - case undefined: - case 0: - part.state = 3; // being deleted - removePart(part); - event.preventDefault(); - break; - // continue - default: - throw new Error('pad: Unexpected state ' + part); - } - } - break; - case 9: - // Tab - { - var delta = event.shiftKey ? -1 : 1; - changeIndent(part, chunk, delta); - event.preventDefault(); // default is to highlight next field - break; - } - case 27: - // ESC - (0, _debug.log)('escape'); - updater.requestDownstreamAction(padDoc, reloadAndSync); - event.preventDefault(); - break; - case 38: - // Up - if (part.parentNode.previousSibling) { - part.parentNode.previousSibling.firstChild.focus(); - event.preventDefault(); - } - break; - case 40: - // Down - if (part.parentNode.nextSibling) { - part.parentNode.nextSibling.firstChild.focus(); - event.preventDefault(); + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(XMLHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + var dom = _utils_js__WEBPACK_IMPORTED_MODULE_11__.parseXML(responseText); + + // XML Semantics defined by root element namespace + // figure out the root element + for (var c = 0; c < dom.childNodes.length; c++) { + var node = dom.childNodes[c]; + // is this node an element? + if (XMLHandler.isElement(node)) { + // We've found the first element, it's the root + var _ns = node.namespaceURI; + + // Is it RDF/XML? + if (_ns && _ns === _ns['rdf']) { + fetcher.addStatus(options.req, 'Has XML root element in the RDF namespace, so assume RDF/XML.'); + var rdfHandler = new RDFXMLHandler(this.response, dom); + return rdfHandler.parse(fetcher, responseText, options); } break; - default: + } } - }); - var updateStore = function updateStore(part) { - var chunk = part.subject; - setPartStyle(part, undefined, true); - var old = kb.any(chunk, ns.sioc('content')).value; - var del = [(0, _rdflib.st)(chunk, ns.sioc('content'), old, padDoc)]; - var ins; - if (part.value) { - ins = [(0, _rdflib.st)(chunk, ns.sioc('content'), part.value, padDoc)]; + + // Or it could be XHTML? + // Maybe it has an XHTML DOCTYPE? + if (dom.doctype) { + // log.info("We found a DOCTYPE in " + xhr.resource) + if (dom.doctype.name === 'html' && dom.doctype.publicId.match(/^-\/\/W3C\/\/DTD XHTML/) && dom.doctype.systemId.match(/http:\/\/www.w3.org\/TR\/xhtml/)) { + fetcher.addStatus(options.req, 'Has XHTML DOCTYPE. Switching to XHTML Handler.\n'); + var xhtmlHandler = new XHTMLHandler(this.response, dom); + return xhtmlHandler.parse(fetcher, responseText, options); + } } - var newOne = part.value; - // DEBUGGING ONLY - if (part.lastSent) { - if (old !== part.lastSent) { - throw new Error("Out of order, last sent expected '" + old + "' but found '" + part.lastSent + "'"); + // Or what about an XHTML namespace? + var html = dom.getElementsByTagName('html')[0]; + if (html) { + var xmlns = html.getAttribute('xmlns'); + if (xmlns && xmlns.match(/^http:\/\/www.w3.org\/1999\/xhtml/)) { + fetcher.addStatus(options.req, 'Has a default namespace for ' + 'XHTML. Switching to XHTMLHandler.\n'); + var _xhtmlHandler = new XHTMLHandler(this.response, dom); + return _xhtmlHandler.parse(fetcher, responseText, options); } } - part.lastSent = newOne; - /* console.log( - ' Patch proposed to ' + - chunk.uri.slice(-4) + - " '" + - old + - "' -> '" + - newOne + - "' " - ) */ - if (!updater) { - throw new Error('no updater'); + // At this point we should check the namespace document (cache it!) and + // look for a GRDDL transform + // @@ Get namespace document , parse it, look for grddl:namespaceTransform ?y + // Apply ?y to dom + // We give up. What dialect is this? + return fetcher.failFetch(options, 'Unsupported dialect of XML: not RDF or XHTML namespace, etc.\n' + responseText.slice(0, 80), 901); + } + }], [{ + key: "toString", + value: function toString() { + return 'XMLHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/xml'] = { + 'q': 0.5 + }; + fetcher.mediatypes['application/xml'] = { + 'q': 0.5 + }; + } + }, { + key: "isElement", + value: function isElement(node) { + return node.nodeType === Node.ELEMENT_NODE; + } + }]); + return XMLHandler; +}(Handler); +XMLHandler.pattern = new RegExp('(text|application)/(.*)xml'); +var HTMLHandler = /*#__PURE__*/function (_Handler4) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(HTMLHandler, _Handler4); + var _super4 = _createSuper(HTMLHandler); + function HTMLHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, HTMLHandler); + return _super4.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(HTMLHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + var kb = fetcher.store; + + // We only handle XHTML so we have to figure out if this is XML + // log.info("Sniffing HTML " + xhr.resource + " for XHTML.") + if (isXML(responseText)) { + fetcher.addStatus(options.req, "Has an XML declaration. We'll assume " + "it's XHTML as the content-type was text/html.\n"); + var xhtmlHandler = new XHTMLHandler(this.response); + return xhtmlHandler.parse(fetcher, responseText, options); } - updater.update(del, ins, function (uri, ok, errorBody, xhr) { - if (!ok) { - // alert("clash " + errorBody); - (0, _debug.log)(' patch FAILED ' + xhr.status + " for '" + old + "' -> '" + newOne + "': " + errorBody); - if (xhr.status === 409) { - // Conflict - @@ we assume someone else - setPartStyle(part, 'color: black; background-color: #fdd;'); - part.state = 0; // Needs downstream refresh - (0, _utils.beep)(0.5, 512); // Ooops clash with other person - setTimeout(function () { - updater.requestDownstreamAction(padDoc, reloadAndSync); - }, 1000); - } else { - setPartStyle(part, 'color: black; background-color: #fdd;'); // failed pink - part.state = 0; - complain(' Error ' + xhr.status + ' sending data: ' + errorBody, true); - (0, _utils.beep)(1.0, 128); // Other - // @@@ Do soemthing more serious with other errors eg auth, etc - } - } else { - clearStatus(true); // upstream - setPartStyle(part); // synced - (0, _debug.log)(" Patch ok '" + old + "' -> '" + newOne + "' "); - if (part.state === 4) { - // delete me - part.state = 3; - removePart(part); - } else if (part.state === 3) { - // being deleted - // pass - } else if (part.state === 2) { - part.state = 1; // pending: lock - updateStore(part); - } else { - part.state = 0; // clear lock - } - } - }); - }; - part.addEventListener('input', function inputChangeListener(_event) { - // debug.log("input changed "+part.value); - setPartStyle(part, undefined, true); // grey out - not synced - (0, _debug.log)('Input event state ' + part.state + " value '" + part.value + "'"); - switch (part.state) { - case 3: - // being deleted - return; - case 4: - // needs to be deleted - return; - case 2: - // needs content updating, we know - return; - case 1: - part.state = 2; // lag we need another patch - return; - case 0: - case undefined: - part.state = 1; // being upadted - updateStore(part); + // DOCTYPE html + if (isXHTML(responseText)) { + fetcher.addStatus(options.req, 'Has XHTML DOCTYPE. Switching to XHTMLHandler.\n'); + var _xhtmlHandler2 = new XHTMLHandler(this.response); + return _xhtmlHandler2.parse(fetcher, responseText, options); } - }); // listener - }; // addlisteners - // @@ TODO Need to research before as it appears to be used as an Element and a boolean - var newPartAfter = function newPartAfter(tr1, chunk, before) { - // @@ take chunk and add listeners - var text = kb.any(chunk, ns.sioc('content')); - text = text ? text.value : ''; - var tr = dom.createElement('tr'); - if (before) { - table.insertBefore(tr, tr1); - } else { - // after - if (tr1 && tr1.nextSibling) { - table.insertBefore(tr, tr1.nextSibling); - } else { - table.appendChild(tr); + // xmlns + if (isXMLNS(responseText)) { + fetcher.addStatus(options.req, 'Has default namespace for XHTML, so switching to XHTMLHandler.\n'); + var _xhtmlHandler3 = new XHTMLHandler(this.response); + return _xhtmlHandler3.parse(fetcher, responseText, options); } - } - var part = tr.appendChild(dom.createElement('input')); - part.subject = chunk; - part.setAttribute('type', 'text'); - part.value = text; - if (me) { - setPartStyle(part, ''); - addListeners(part, chunk); - } else { - setPartStyle(part, 'color: #222; background-color: #fff'); - (0, _debug.log)("Note can't add listeners - not logged in"); - } - return part; - }; - /* @@ TODO we need to look at indent, it can be a Number or an Object this doesn't seem correct. - */ - var newChunk = function newChunk(ele, before) { - // element of chunk being split - var kb = store; - var indent = 0; - var queueProperty = null; - var here, prev, next, queue, tr1; - if (ele) { - if (ele.tagName.toLowerCase() !== 'input') { - (0, _debug.log)('return pressed when current document is: ' + ele.tagName); - } - here = ele.subject; - indent = kb.any(here, PAD('indent')); - indent = indent ? Number(indent.value) : 0; - if (before) { - prev = kb.any(undefined, PAD('next'), here); - next = here; - queue = prev; - queueProperty = 'newlinesAfter'; - } else { - prev = here; - next = kb.any(here, PAD('next')); - queue = next; - queueProperty = 'newlinesBefore'; + // dc:title + // no need to escape '/' here + var titleMatch = new RegExp('([\\s\\S]+?)', 'im').exec(responseText); + if (titleMatch) { + kb.add(options.resource, ns.dc('title'), kb.rdfFactory.literal(titleMatch[1]), options.resource); // think about xml:lang later } - tr1 = ele.parentNode; - } else { - prev = subject; - next = subject; - tr1 = undefined; + + kb.add(options.resource, ns.rdf('type'), ns.link('WebPage'), fetcher.appNode); + fetcher.addStatus(options.req, 'non-XML HTML document, not parsed for data.'); + return fetcher.doneFetch(options, this.response); } - var chunk = (0, _widgets.newThing)(padDoc); - var label = chunk.uri.slice(-4); - var del = [(0, _rdflib.st)(prev, PAD('next'), next, padDoc)]; - var ins = [(0, _rdflib.st)(prev, PAD('next'), chunk, padDoc), (0, _rdflib.st)(chunk, PAD('next'), next, padDoc), (0, _rdflib.st)(chunk, ns.dc('author'), me, padDoc), (0, _rdflib.st)(chunk, ns.sioc('content'), '', padDoc)]; - if (indent > 0) { - // Do not inherit - ins.push((0, _rdflib.st)(chunk, PAD('indent'), indent, padDoc)); + }], [{ + key: "toString", + value: function toString() { + return 'HTMLHandler'; } - (0, _debug.log)(' Fresh chunk ' + label + ' proposed'); - if (!updater) { - throw new Error('no updater'); + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/html'] = { + 'q': 0.9 + }; } - updater.update(del, ins, function (uri, ok, errorBody, _xhr) { - if (!ok) { - // alert("Error writing new line " + label + ": " + errorBody); - (0, _debug.log)(' ERROR writing new line ' + label + ': ' + errorBody); - } else { - var newPart = newPartAfter(tr1, chunk, before); - setPartStyle(newPart); - newPart.focus(); // Note this is delayed - if (queueProperty) { - (0, _debug.log)(' Fresh chunk ' + label + ' updated, queue = ' + queue[queueProperty]); - queue[queueProperty] -= 1; - if (queue[queueProperty] > 0) { - (0, _debug.log)(' Implementing queued newlines = ' + next.newLinesBefore); - newChunk(newPart, before); - } + }]); + return HTMLHandler; +}(Handler); +HTMLHandler.pattern = new RegExp('text/html'); +var JsonLdHandler = /*#__PURE__*/function (_Handler5) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(JsonLdHandler, _Handler5); + var _super5 = _createSuper(JsonLdHandler); + function JsonLdHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, JsonLdHandler); + return _super5.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(JsonLdHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options, response) { + var kb = fetcher.store; + return new Promise(function (resolve, reject) { + try { + (0,_jsonldparser__WEBPACK_IMPORTED_MODULE_15__["default"])(responseText, kb, options.original.value, function () { + resolve(fetcher.doneFetch(options, response)); + }); + } catch (err) { + var msg = 'Error trying to parse ' + options.resource + ' as JSON-LD:\n' + err; // not err.stack -- irrelevant + resolve(fetcher.failFetch(options, msg, 'parse_error', response)); } - } - }); - }; - var consistencyCheck = function consistencyCheck() { - var found = {}; - var failed = 0; - function complain2(msg) { - complain(msg); - failed++; + }); } - if (!kb.the(subject, PAD('next'))) { - complain2('No initial next pointer'); - return false; // can't do linked list + }], [{ + key: "toString", + value: function toString() { + return 'JsonLdHandler'; } - // var chunk = kb.the(subject, PAD('next')) - var prev = subject; - var chunk; - for (;;) { - chunk = kb.the(prev, PAD('next')); - if (!chunk) { - complain2('No next pointer from ' + prev); + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['application/ld+json'] = { + 'q': 0.9 + }; + } + }]); + return JsonLdHandler; +}(Handler); +JsonLdHandler.pattern = /application\/ld\+json/; +var TextHandler = /*#__PURE__*/function (_Handler6) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(TextHandler, _Handler6); + var _super6 = _createSuper(TextHandler); + function TextHandler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, TextHandler); + return _super6.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(TextHandler, [{ + key: "parse", + value: function parse(fetcher, responseText, options) { + // We only speak dialects of XML right now. Is this XML? + + // Look for an XML declaration + if (isXML(responseText)) { + fetcher.addStatus(options.req, 'Warning: ' + options.resource + " has an XML declaration. We'll assume " + "it's XML but its content-type wasn't XML.\n"); + var xmlHandler = new XMLHandler(this.response); + return xmlHandler.parse(fetcher, responseText, options); } - if (chunk.sameTerm(subject)) { - break; + + // Look for an XML declaration + if (responseText.slice(0, 500).match(/xmlns:/)) { + fetcher.addStatus(options.req, "May have an XML namespace. We'll assume " + "it's XML but its content-type wasn't XML.\n"); + var _xmlHandler = new XMLHandler(this.response); + return _xmlHandler.parse(fetcher, responseText, options); } - prev = chunk; - var label = chunk.uri.split('#')[1]; - if (found[chunk.uri]) { - complain2('Loop!'); - return false; + + // We give up finding semantics - this is not an error, just no data + fetcher.addStatus(options.req, 'Plain text document, no known RDF semantics.'); + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'TextHandler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/plain'] = { + 'q': 0.5 + }; + } + }]); + return TextHandler; +}(Handler); +TextHandler.pattern = new RegExp('text/plain'); +var N3Handler = /*#__PURE__*/function (_Handler7) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_1__["default"])(N3Handler, _Handler7); + var _super7 = _createSuper(N3Handler); + function N3Handler() { + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, N3Handler); + return _super7.apply(this, arguments); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(N3Handler, [{ + key: "parse", + value: function parse(fetcher, responseText, options, response) { + // Parse the text of this N3 file + var kb = fetcher.store; + var p = (0,_n3parser__WEBPACK_IMPORTED_MODULE_16__["default"])(kb, kb, options.original.value, options.original.value, null, null, '', null); + // p.loadBuf(xhr.responseText) + try { + p.loadBuf(responseText); + } catch (err) { + var msg = 'Error trying to parse ' + options.resource + ' as Notation3:\n' + err; // not err.stack -- irrelevant + return fetcher.failFetch(options, msg, 'parse_error', response); } - found[chunk.uri] = true; - var k = kb.each(chunk, PAD('next')).length; - if (k !== 1) { - complain2('Should be 1 not ' + k + ' next pointer for ' + label); + fetcher.addStatus(options.req, 'N3 parsed: ' + p.statementCount + ' triples in ' + p.lines + ' lines.'); + fetcher.store.add(options.original, ns.rdf('type'), ns.link('RDFDocument'), fetcher.appNode); + return fetcher.doneFetch(options, this.response); + } + }], [{ + key: "toString", + value: function toString() { + return 'N3Handler'; + } + }, { + key: "register", + value: function register(fetcher) { + fetcher.mediatypes['text/n3'] = { + 'q': '1.0' + }; // as per 2008 spec + /* + fetcher.mediatypes['application/x-turtle'] = { + 'q': 1.0 + } // pre 2008 + */ + fetcher.mediatypes['text/turtle'] = { + 'q': 1.0 + }; // post 2008 + } + }]); + return N3Handler; +}(Handler); +N3Handler.pattern = new RegExp('(application|text)/(x-)?(rdf\\+)?(n3|turtle)'); +var defaultHandlers = { + RDFXMLHandler: RDFXMLHandler, + XHTMLHandler: XHTMLHandler, + XMLHandler: XMLHandler, + HTMLHandler: HTMLHandler, + TextHandler: TextHandler, + N3Handler: N3Handler, + JsonLdHandler: JsonLdHandler +}; +function isXHTML(responseText) { + var docTypeStart = responseText.indexOf(''); + if (docTypeStart === -1 || docTypeEnd === -1 || docTypeStart > docTypeEnd) { + return false; + } + return responseText.substr(docTypeStart, docTypeEnd - docTypeStart).indexOf('XHTML') !== -1; +} +function isXML(responseText) { + var match = responseText.match(/\s*<\?xml\s+version\s*=[^<>]+\?>/); + return !!match; +} +function isXMLNS(responseText) { + var match = responseText.match(/[^(/); + return !!match; +} + +// Not sure about the shapes of this. Response? FetchError? + +/** Differs from normal Fetch, has an extended Response type */ +/** Fetcher + * + * The Fetcher object is a helper object for a quadstore + * which turns it from an offline store to an online store. + * The fetcher deals with loading data files rom the web, + * figuring how to parse them. It will also refresh, remove, the data + * and put back the data to the web. + */ +var Fetcher = /*#__PURE__*/function () { + function Fetcher(store) { + var _this = this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_5__["default"])(this, Fetcher); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "store", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "timeout", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "_fetch", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "mediatypes", void 0); + /** Denoting this session */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "appNode", void 0); + /** + * this.requested[uri] states: + * undefined no record of web access or records reset + * true has been requested, fetch in progress + * 'done' received, Ok + * 401 Not logged in + * 403 HTTP status unauthorized + * 404 Resource does not exist. Can be created etc. + * 'redirected' In attempt to counter CORS problems retried. + * 'parse_error' Parse error + * 'unsupported_protocol' URI is not a protocol Fetcher can deal with + * other strings mean various other errors. + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "requested", void 0); + /** List of timeouts associated with a requested URL */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "timeouts", void 0); + /** Redirected from *key uri* to *value uri* */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "redirectedTo", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "fetchQueue", void 0); + /** fetchCallbacks[uri].push(callback) */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "fetchCallbacks", void 0); + /** Keep track of explicit 404s -> we can overwrite etc */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "nonexistent", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "lookedUp", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "handlers", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "ns", void 0); + /** Methods added by calling Util.callbackify in the constructor*/ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(this, "fireCallbacks", void 0); + this.store = store || new _store__WEBPACK_IMPORTED_MODULE_17__["default"](); + this.ns = getNS(this.store.rdfFactory); + this.timeout = options.timeout || 30000; + + // solidFetcher is deprecated + this._fetch = options.fetch || typeof __webpack_require__.g !== 'undefined' && (__webpack_require__.g.solidFetcher || __webpack_require__.g.solidFetch) || typeof window !== 'undefined' && (window.solidFetcher || window.solidFetch) || (cross_fetch__WEBPACK_IMPORTED_MODULE_8___default()); + if (!this._fetch) { + throw new Error('No _fetch function available for Fetcher'); + } + // This is the name of the graph we store all the HTTP metadata in + this.appNode = this.store.sym('chrome://TheCurrentSession'); + // this.appNode = this.store.rdfFactory.blankNode() // Needs to have a URI in tests + this.store.fetcher = this; // Bi-linked + this.requested = {}; + this.timeouts = {}; + this.redirectedTo = {}; + this.fetchQueue = {}; + this.fetchCallbacks = {}; + this.nonexistent = {}; + this.lookedUp = {}; + this.handlers = []; + this.mediatypes = { + 'image/*': { + 'q': 0.9 + }, + '*/*': { + 'q': 0.1 + } // Must allow access to random content + }; + + // Util.callbackify(this, ['request', 'recv', 'headers', 'load', 'fail', + // 'refresh', 'retract', 'done']) + // In switching to fetch(), 'recv', 'headers' and 'load' do not make sense + _utils_js__WEBPACK_IMPORTED_MODULE_11__.callbackify(this, ['request', 'fail', 'refresh', 'retract', 'done']); + Object.keys(options.handlers || defaultHandlers).map(function (key) { + return _this.addHandler(defaultHandlers[key]); + }); + } + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__["default"])(Fetcher, [{ + key: "load", + value: + /** + * Promise-based load function + * + * Loads a web resource or resources into the store. + * + * A resource may be given as NamedNode object, or as a plain URI. + * an array of resources will be given, in which they will be fetched in parallel. + * By default, the HTTP headers are recorded also, in the same store, in a separate graph. + * This allows code like editable() for example to test things about the resource. + * + * @param uri {Array|Array|RDFlibNamedNode|string} + * + * @param [options={}] {Object} + * + * @param [options.fetch] {Function} + * + * @param [options.referringTerm] {RDFlibNamedNode} Referring term, the resource which + * referred to this (for tracking bad links) + * + * @param [options.contentType] {string} Provided content type (for writes) + * + * @param [options.forceContentType] {string} Override the incoming header to + * force the data to be treated as this content-type (for reads) + * + * @param [options.force] {boolean} Load the data even if loaded before. + * Also sets the `Cache-Control:` header to `no-cache` + * + * @param [options.baseURI=docuri] {Node|string} Original uri to preserve + * through proxying etc (`xhr.original`). + * + * @param [options.proxyUsed] {boolean} Whether this request is a retry via + * a proxy (generally done from an error handler) + * + * @param [options.withCredentials] {boolean} flag for XHR/CORS etc + * + * @param [options.clearPreviousData] {boolean} Before we parse new data, + * clear old, but only on status 200 responses + * + * @param [options.noMeta] {boolean} Prevents the addition of various metadata + * triples (about the fetch request) to the store + * + * @param [options.noRDFa] {boolean} + * + * @returns {Promise} + */ + function load(uri) { + var _this2 = this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + options = Object.assign({}, options); // Take a copy as we add stuff to the options!! + if (uri instanceof Array) { + return Promise.all(uri.map(function (x) { + return _this2.load(x, Object.assign({}, options)); + })); } - k = kb.each(chunk, PAD('indent')).length; - if (k > 1) { - complain2('Should be 0 or 1 not ' + k + ' indent for ' + label); + var uriIn = uri; + var docuri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uriIn); + docuri = docuri.split('#')[0]; + options = this.initFetchOptions(docuri, options); + // if metadata flaged clear cache and removeDocument + var meta = this.appNode; + var kb = this.store; + var requests = kb.statementsMatching(undefined, this.ns.link('requestedURI'), kb.sym(docuri), meta).map(function (st) { + return st.subject; + }); + var _iterator = _createForOfIteratorHelper(requests), + _step; + try { + for (_iterator.s(); !(_step = _iterator.n()).done;) { + var request = _step.value; + var _response = kb.any(request, this.ns.link('response'), null, meta); + if (_response !== undefined) { + // ts + var quad = kb.statementsMatching(_response, this.ns.link('outOfDate'), true, meta); + kb.remove(quad); + options.force = true; + options.clearPreviousData = true; + } + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } - k = kb.each(chunk, ns.sioc('content')).length; - if (k !== 1) { - complain2('Should be 1 not ' + k + ' contents for ' + label); + var initialisedOptions = this.initFetchOptions(docuri, options); + return this.pendingFetchPromise(docuri, initialisedOptions.baseURI, initialisedOptions); + } + }, { + key: "pendingFetchPromise", + value: function () { + var _pendingFetchPromise = (0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().mark(function _callee(uri, originalUri, options) { + var _this3 = this; + var pendingPromise; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + _context.t0 = !options.force; + if (!_context.t0) { + _context.next = 5; + break; + } + _context.next = 4; + return this.fetchQueue[originalUri]; + case 4: + _context.t0 = _context.sent; + case 5: + if (!_context.t0) { + _context.next = 9; + break; + } + pendingPromise = this.fetchQueue[originalUri]; + _context.next = 12; + break; + case 9: + pendingPromise = Promise.race([this.setRequestTimeout(uri, options), this.fetchUri(uri, options)]); + this.fetchQueue[originalUri] = pendingPromise; + + // Clean up the queued promise after a time, if it's resolved + this.cleanupFetchRequest(originalUri, undefined, this.timeout); + case 12: + return _context.abrupt("return", pendingPromise.then(function (x) { + if (uri in _this3.timeouts) { + _this3.timeouts[uri].forEach(clearTimeout); + delete _this3.timeouts[uri]; + } + return x; + })); + case 13: + case "end": + return _context.stop(); + } + }, _callee, this); + })); + function pendingFetchPromise(_x, _x2, _x3) { + return _pendingFetchPromise.apply(this, arguments); } - k = kb.each(chunk, ns.dc('author')).length; - if (k !== 1) { - complain2('Should be 1 not ' + k + ' author for ' + label); + return pendingFetchPromise; + }() + /** + * @param _options - DEPRECATED + */ + }, { + key: "cleanupFetchRequest", + value: function cleanupFetchRequest(originalUri, _options, timeout) { + var _this4 = this; + if (_options !== undefined) { + console.warn("_options is deprecated"); } - var sts = kb.statementsMatching(undefined, ns.sioc('contents')); - sts.forEach(function (st) { - if (!found[st.subject.value]) { - complain2('Loose chunk! ' + st.subject.value); + this.timeouts[originalUri] = (this.timeouts[originalUri] || []).concat(setTimeout(function () { + if (!_this4.isPending(originalUri)) { + delete _this4.fetchQueue[originalUri]; } - }); + }, timeout)); } - return !failed; - }; - - // Ensure that the display matches the current state of the - // @@ TODO really need to refactor this so that we don't need to cast types - var sync = function sync() { - // var first = kb.the(subject, PAD('next')) - if (kb.each(subject, PAD('next')).length !== 1) { - var msg = 'Pad: Inconsistent data - NEXT pointers: ' + kb.each(subject, PAD('next')).length; - (0, _debug.log)(msg); - if (options.statusArea) { - options.statusArea.textContent += msg; + }, { + key: "initFetchOptions", + value: function initFetchOptions(uri, options) { + var kb = this.store; + var isGet = !options.method || options.method.toUpperCase() === 'GET'; + if (!isGet) { + options.force = true; } - return; - } - // var last = kb.the(undefined, PAD('previous'), subject) - // var chunk = first // = kb.the(subject, PAD('next')); - var row; - - // First see which of the logical chunks have existing physical manifestations - var manif = []; - // Find which lines correspond to existing chunks - - for (var chunk = kb.the(subject, PAD('next')); !chunk.sameTerm(subject); chunk = kb.the(chunk, PAD('next'))) { - for (var i = 0; i < table.children.length; i++) { - var _tr = table.children[i]; - if (_tr.firstChild) { - if (_tr.firstChild.subject.sameTerm(chunk)) { - manif[chunk.uri] = _tr.firstChild; - } - } + options.resource = kb.rdfFactory.namedNode(uri); // This might be proxified + options.baseURI = options.baseURI || uri; // Preserve though proxying etc + options.original = kb.rdfFactory.namedNode(options.baseURI); + options.req = kb.bnode(); + options.headers = options.headers || new cross_fetch__WEBPACK_IMPORTED_MODULE_8__.Headers(); + if (options.contentType) { + // @ts-ignore + options.headers['content-type'] = options.contentType; } - } - - // Remove any deleted lines - for (var _i = table.children.length - 1; _i >= 0; _i--) { - row = table.children[_i]; - if (!manif[row.firstChild.subject.uri]) { - table.removeChild(row); + if (options.force) { + options.cache = 'no-cache'; } - } - // Insert any new lines and update old ones - row = table.firstChild; // might be null - for (var _chunk = kb.the(subject, PAD('next')); !_chunk.sameTerm(subject); _chunk = kb.the(_chunk, PAD('next'))) { - var text = kb.any(_chunk, ns.sioc('content')).value; - // superstitious -- don't mess with unchanged input fields - // which may be selected by the user - if (row && manif[_chunk.uri]) { - var part = row.firstChild; - if (text !== part.value) { - part.value = text; - } - setPartStyle(part); - part.state = 0; // Clear the state machine - delete part.lastSent; // DEBUG ONLY - row = row.nextSibling; - } else { - newPartAfter(row, _chunk, true); // actually before + var acceptString = this.acceptString(); + // @ts-ignore + options.headers['accept'] = acceptString; + var requestedURI = Fetcher.offlineOverride(uri); + options.requestedURI = requestedURI; + Fetcher.setCredentials(requestedURI, options); + var actualProxyURI = Fetcher.proxyIfNecessary(requestedURI); + if (requestedURI !== actualProxyURI) { + options.proxyUsed = true; } - } - }; - - // Refresh the DOM tree - - var refreshTree = function refreshTree(root) { - if (root.refresh) { - root.refresh(); - return; - } - for (var i = 0; i < root.children.length; i++) { - refreshTree(root.children[i]); - } - }; - var reloading = false; - var checkAndSync = function checkAndSync() { - (0, _debug.log)(' reloaded OK'); - clearStatus(); - if (!consistencyCheck()) { - complain('CONSITENCY CHECK FAILED'); - } else { - refreshTree(table); - } - }; - var reloadAndSync = function reloadAndSync() { - if (reloading) { - (0, _debug.log)(' Already reloading - stop'); - return; // once only needed + options.actualProxyURI = actualProxyURI; + return options; } - reloading = true; - var retryTimeout = 1000; // ms - var tryReload = function tryReload() { - (0, _debug.log)('try reload - timeout = ' + retryTimeout); - if (!updater) { - throw new Error('no updater'); + /** + * (The promise chain ends in either a `failFetch()` or a `doneFetch()`) + * + * @param docuri {string} + * @param options {Object} + * + * @returns {Promise} fetch() result or an { error, status } object + */ + }, { + key: "fetchUri", + value: function fetchUri(docuri, options) { + var _this5 = this; + if (!docuri) { + return Promise.reject(new Error('Cannot fetch an empty uri')); } - updater.reload(updater.store, padDoc, function (ok, message, xhr) { - reloading = false; - if (ok) { - checkAndSync(); - } else { - if (xhr.status === 0) { - complain('Network error refreshing the pad. Retrying in ' + retryTimeout / 1000); - reloading = true; - retryTimeout = retryTimeout * 2; - setTimeout(tryReload, retryTimeout); - } else { - complain('Error ' + xhr.status + 'refreshing the pad:' + message + '. Stopped. ' + padDoc); - } - } - }); - }; - tryReload(); - }; - table.refresh = sync; // Catch downward propagating refresh events - table.reloadAndSync = reloadAndSync; - if (!me) (0, _debug.log)('Warning: must be logged in for pad to be edited'); - if (exists) { - (0, _debug.log)('Existing pad.'); - if (consistencyCheck()) { - sync(); - if (kb.holds(subject, PAD('next'), subject)) { - // Empty list untenable - newChunk(); // require at least one line + if (Fetcher.unsupportedProtocol(docuri)) { + return this.failFetch(options, 'fetcher: Unsupported protocol', 'unsupported_protocol'); } - } else { - (0, _debug.log)(table.textContent = 'Inconsistent data. Abort'); - } - } else { - // Make new pad - (0, _debug.log)('No pad exists - making new one.'); - var insertables = [(0, _rdflib.st)(subject, ns.rdf('type'), PAD('Notepad'), padDoc), (0, _rdflib.st)(subject, ns.dc('author'), me, padDoc), (0, _rdflib.st)(subject, ns.dc('created'), new Date(), padDoc), (0, _rdflib.st)(subject, PAD('next'), subject, padDoc)]; - if (!updater) { - throw new Error('no updater'); - } - updater.update([], insertables, function (uri, ok, errorBody) { - if (!ok) { - complain(errorBody || ''); + var state = this.getState(docuri); + if (!options.force) { + if (state === 'fetched') { + // URI already fetched and added to store + return Promise.resolve( + // @ts-ignore This is not a valid response object + this.doneFetch(options, { + status: 200, + ok: true, + statusText: 'Already loaded into quadstore.' + })); + } + if (state === 'failed' && this.requested[docuri] === 404) { + // Remember nonexistence + var _message = 'Previously failed: ' + this.requested[docuri]; + // @ts-ignore This is not a valid response object + var dummyResponse = { + url: docuri, + // This does not comply to Fetch spec, it can be a string value in rdflib + status: this.requested[docuri], + statusText: _message, + responseText: _message, + headers: new cross_fetch__WEBPACK_IMPORTED_MODULE_8__.Headers(), + // Headers() ??? + ok: false, + body: null, + bodyUsed: false, + size: 0, + timeout: 0 + }; + return this.failFetch(options, _message, this.requested[docuri], dummyResponse); + } } else { - (0, _debug.log)('Initial pad created'); - newChunk(); // Add a first chunck - // getResults(); + // options.force == true + delete this.nonexistent[docuri]; } - }); - } - - return table; -} - -/** - * Get the chunks of the notepad - * They are stored in a RDF linked list - */ - -// @ignore exporting this only for the unit test -function getChunks(subject, kb) { - var chunks = []; - for (var chunk = kb.the(subject, PAD('next')); !chunk.sameTerm(subject); chunk = kb.the(chunk, PAD('next'))) { - chunks.push(chunk); - } - return chunks; -} - -/** - * Encode content to be put in XML or HTML elements - */ -// @ignore exporting this only for the unit test -function xmlEncode(str) { - return str.replace('&', '&').replace('<', '<').replace('>', '>'); -} + this.fireCallbacks('request', [docuri]); + this.requested[docuri] = true; // mark this uri as 'requested' -/** - * Convert a notepad to HTML - * @param { } pad - the notepad - * @param {store} pad - the data store - */ -function notepadToHTML(pad, kb) { - var chunks = getChunks(pad, kb); - var html = '\n \n'; - var title = kb.anyValue(pad, ns.dct('title')); - if (title) { - html += " ".concat(xmlEncode(title), "\n"); - } - html += ' \n \n'; - var level = 0; - function increaseLevel(indent) { - for (; level < indent; level++) { - html += '
    \n'; - } - } - function decreaseLevel(indent) { - for (; level > indent; level--) { - html += '
\n'; - } - } - chunks.forEach(function (chunk) { - var indent = kb.anyJS(chunk, PAD('indent')); - var rawContent = kb.anyJS(chunk, ns.sioc('content')); - if (!rawContent) return; // seed chunk is dummy - var content = xmlEncode(rawContent); - if (indent < 0) { - // negative indent levels represent heading levels - decreaseLevel(0); - var h = indent >= -3 ? 4 + indent : 1; // -1 -> h4, -2 -> h3 - html += "\n").concat(content, "\n"); - } else { - // >= 0 - if (indent > 0) { - // Lists - decreaseLevel(indent); - increaseLevel(indent); - html += "
  • ".concat(content, "
  • \n"); - } else { - // indent 0 - decreaseLevel(indent); - html += "

    ".concat(content, "

    \n"); + if (!options.noMeta) { + this.saveRequestMetadata(docuri, options); } - } - }); // foreach chunk - // At the end decreaseLevel any open ULs - decreaseLevel(0); - html += ' \n\n'; - return html; -} -//# sourceMappingURL=pad.js.map - -/***/ }), - -/***/ "./lib/participation.js": -/*!******************************!*\ - !*** ./lib/participation.js ***! - \******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; + var actualProxyURI = options.actualProxyURI; + // Map might get mistakenly added into headers + // error TS2339: Property 'map' does not exist on type 'Headers'. + /* let map + if (options.headers && map in options.headers) { + delete options.headers.map + } */ -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.manageParticipation = manageParticipation; -exports.participationObject = participationObject; -exports.recordParticipation = recordParticipation; -exports.renderPartipants = renderPartipants; -var _createClass2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/createClass.js")); -var _classCallCheck2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/classCallCheck.js")); -var _assertThisInitialized2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/assertThisInitialized.js")); -var _inherits2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/inherits.js")); -var _possibleConstructorReturn2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js")); -var _getPrototypeOf2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/getPrototypeOf.js")); -var _wrapNativeSuper2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/wrapNativeSuper */ "./node_modules/@babel/runtime/helpers/wrapNativeSuper.js")); -var _defineProperty2 = _interopRequireDefault(__webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/defineProperty.js")); -var debug = _interopRequireWildcard(__webpack_require__(/*! ./debug */ "./lib/debug.js")); -var _rdflib = __webpack_require__(/*! rdflib */ "../rdflib/esm/index.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var _widgets = __webpack_require__(/*! ./widgets */ "./lib/widgets/index.js"); -var _utils = __webpack_require__(/*! ./utils */ "./lib/utils/index.js"); -var _pad = __webpack_require__(/*! ./pad */ "./lib/pad.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "../solid-logic/lib/index.js"); -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); } -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; } -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; } } }; } -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); } -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; } -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } -var ParticipationTableElement = /*#__PURE__*/function (_HTMLTableElement) { - (0, _inherits2["default"])(ParticipationTableElement, _HTMLTableElement); - var _super = _createSuper(ParticipationTableElement); - function ParticipationTableElement() { - var _this; - (0, _classCallCheck2["default"])(this, ParticipationTableElement); - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - _this = _super.call.apply(_super, [this].concat(args)); - (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "refresh", void 0); - return _this; - } - return (0, _createClass2["default"])(ParticipationTableElement); -}( /*#__PURE__*/(0, _wrapNativeSuper2["default"])(HTMLTableElement)); -var store = _solidLogic.solidLogicSingleton.store; + return this._fetch(actualProxyURI, options).then(function (response) { + return _this5.handleResponse(response, docuri, options); + }, function (error) { + // @@ handleError? + // @ts-ignore Invalid response object + var dummyResponse = { + url: actualProxyURI, + status: 999, + // @@ what number/string should fetch failures report? + statusText: (error.name || 'network failure') + ': ' + (error.errno || error.code || error.type), + responseText: error.message, + headers: new cross_fetch__WEBPACK_IMPORTED_MODULE_8__.Headers(), + // Headers() ??? + ok: false, + body: null, + bodyUsed: false, + size: 0, + timeout: 0 + }; + // console.log('Fetcher: <' + actualProxyURI + '> Non-HTTP fetch exception: ' + error) + return _this5.handleError(dummyResponse, docuri, options); // possible credentials retry + // return this.failFetch(options, 'fetch failed: ' + error, 999, dummyResponse) // Fake status code: fetch exception -/** Manage participation in this session -* -* @param {Document} dom - the web page loaded into the browser -* @param {HTMLTableElement} table - the table element -* @param {NamedNode} unused1/document - the document to render (this argument is no longer used, but left in for backwards compatibility) -* @param {NamedNode} subject - the thing in which the participation is happening -* @param {NamedNode} unused2/me - user that is logged into the pod (this argument is no longer used, but left in for backwards compatibility) -* @param {ParticipationOptions} options - the options that can be passed in are deleteFunction, link, and draggable these are used by the personTR button -*/ -function renderPartipants(dom, table, unused1, subject, unused2, options) { - table.setAttribute('style', 'margin: 0.8em;'); - var newRowForParticpation = function newRowForParticpation(parp) { - var person = store.any(parp, ns.wf('participant')); - var tr; - if (!person) { - tr = dom.createElement('tr'); - tr.textContent = '???'; // Don't crash - invalid part'n entry - return tr; + // handleError expects a response so we fake some important bits. + /* + this.handleError(, docuri, options) + */ + }); } - var bg = store.anyValue(parp, ns.ui('backgroundColor')) || 'white'; - var block = dom.createElement('div'); - block.setAttribute('style', 'height: 1.5em; width: 1.5em; margin: 0.3em; border 0.01em solid #888; background-color: ' + bg); - tr = (0, _widgets.personTR)(dom, null, person, options); - table.appendChild(tr); - var td = dom.createElement('td'); - td.setAttribute('style', 'vertical-align: middle;'); - td.appendChild(block); - tr.insertBefore(td, tr.firstChild); - return tr; - }; - var syncTable = function syncTable() { - var parps = store.each(subject, ns.wf('participation')).map(function (parp) { - (0, debug.log)('in participants'); - return [store.anyValue(parp, ns.cal('dtstart')) || '9999-12-31', parp]; - }); - parps.sort(); // List in order of joining - var participations = parps.map(function (p) { - return p[1]; - }); - (0, _utils.syncTableToArray)(table, participations, newRowForParticpation); - }; - table.refresh = syncTable; - syncTable(); - return table; -} -/** Record, or find old, Particpation object - * - * A particpaption object is a place to record things specifically about - * subject and the user, such as preferences, start of membership, etc - * @param {NamedNode} subject - the thing in which the participation is happening - * @param {NamedNode} document - where to record the data - * @param {NamedNode} me - the logged in user - * - */ -function participationObject(subject, padDoc, me) { - return new Promise(function (resolve, reject) { - if (!me) { - throw new Error('No user id'); - } - var parps = store.each(subject, ns.wf('participation')).filter(function (pn) { - return store.holds(pn, ns.wf('participant'), me); - }); - if (parps.length > 1) { - // This can happen. https://github.com/solidos/chat-pane/issues/71 - var candidates = []; - var _iterator = _createForOfIteratorHelper(parps), - _step; - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var participation = _step.value; - var date = store.anyValue(participation, ns.cal('dtstart')); - if (date) { - candidates.push([date, participation]); - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); + /** + * Asks for a doc to be loaded if necessary then calls back + * + * Calling methods: + * nowOrWhenFetched (uri, userCallback) + * nowOrWhenFetched (uri, options, userCallback) + * nowOrWhenFetched (uri, referringTerm, userCallback, options) <-- old + * nowOrWhenFetched (uri, referringTerm, userCallback) <-- old + * + * Options include: + * referringTerm The document in which this link was found. + * this is valuable when finding the source of bad URIs + * force boolean. Never mind whether you have tried before, + * load this from scratch. + * forceContentType Override the incoming header to force the data to be + * treated as this content-type. + * + * Callback function takes: + * + * ok True if the fetch worked, and got a 200 response. + * False if any error happened + * + * errmessage Text error message if not OK. + * + * response The fetch Response object (was: XHR) if there was was one + * includes response.status as the HTTP status if any. + */ + }, { + key: "nowOrWhenFetched", + value: function nowOrWhenFetched(uriIn, p2, userCallback) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uriIn); + if (typeof p2 === 'function') { + // nowOrWhenFetched (uri, userCallback) + userCallback = p2; + } else if (typeof p2 === 'undefined') {// original calling signature + // referringTerm = undefined + } else if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_19__.isNamedNode)(p2)) { + // referringTerm = p2 + options.referringTerm = p2; + } else { + // nowOrWhenFetched (uri, options, userCallback) + options = p2; } - candidates.sort(); // Pick the earliest - // @@ Possibly, for extra credit, delete the others, if we have write access - debug.warn('Multiple particpation objects, picking earliest, in ' + padDoc); - resolve(candidates[0][1]); - // throw new Error('Multiple records of your participation') - } + this.load(uri, options).then(function (fetchResponse) { + if (userCallback) { + if (fetchResponse) { + if (fetchResponse.ok) { + userCallback(true, 'OK', fetchResponse); + } else { + var oops = 'HTTP error: Status ' + fetchResponse.status + ' (' + fetchResponse.statusText + ')'; + if (fetchResponse.responseText) { + oops += ' ' + fetchResponse.responseText; // not in 404, dns error, nock failure + } - if (parps.length) { - // If I am not already recorded - resolve(parps[0]); // returns the particpation object - } else { - var _participation2 = (0, _widgets.newThing)(padDoc); - var ins = [(0, _rdflib.st)(subject, ns.wf('participation'), _participation2, padDoc), (0, _rdflib.st)(_participation2, ns.wf('participant'), me, padDoc), (0, _rdflib.st)(_participation2, ns.cal('dtstart'), new Date(), padDoc), (0, _rdflib.st)(_participation2, ns.ui('backgroundColor'), (0, _pad.lightColorHash)(me), padDoc)]; - store.updater.update([], ins, function (uri, ok, errorMessage) { - if (!ok) { - reject(new Error('Error recording your partipation: ' + errorMessage)); - } else { - resolve(_participation2); + userCallback(false, oops, fetchResponse); + } + } else { + var _oops = '@@ nowOrWhenFetched: no response object!'; + userCallback(false, _oops); + } + } + }, function (err) { + var message = err.message || err.statusText; + message = 'Failed to load <' + uri + '> ' + message; + if (err.response && err.response.status) { + message += ' status: ' + err.response.status; } + userCallback(false, message, err.response); }); - resolve(_participation2); } - }); -} - -/** Record my participation and display participants - * - * @param {NamedNode} subject - the thing in which participation is happening - * @param {NamedNode} padDoc - the document into which the particpation should be recorded - * @param {DOMNode} refreshable - a DOM element whose refresh() is to be called if the change works - * - */ -function recordParticipation(subject, padDoc, refreshable) { - var me = _solidLogic.authn.currentUser(); - if (!me) return; // Not logged in - var parps = store.each(subject, ns.wf('participation')).filter(function (pn) { - return store.holds(pn, ns.wf('participant'), me); - }); - if (parps.length > 1) { - throw new Error('Multiple records of your participation'); - } - if (parps.length) { - // If I am not already recorded - return parps[0]; // returns the particpation object - } else { - if (!store.updater.editable(padDoc)) { - debug.log('Not recording participation, as no write acesss as ' + me + ' to ' + padDoc); - return null; + /** + * Records a status message (as a literal node) by appending it to the + * request's metadata status collection. + * + */ + }, { + key: "addStatus", + value: function addStatus(req, statusMessage) { + // + var now = new Date(); + statusMessage = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '.' + now.getMilliseconds() + '] ' + statusMessage; + // + var kb = this.store; + var statusNode = kb.the(req, this.ns.link('status')); + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_19__.isCollection)(statusNode)) { + statusNode.append(kb.rdfFactory.literal(statusMessage)); + } else { + _log__WEBPACK_IMPORTED_MODULE_20__["default"].warn('web.js: No list to add to: ' + statusNode + ',' + statusMessage); + } } - var participation = (0, _widgets.newThing)(padDoc); - var ins = [(0, _rdflib.st)(subject, ns.wf('participation'), participation, padDoc), (0, _rdflib.st)(participation, ns.wf('participant'), me, padDoc), (0, _rdflib.st)(participation, ns.cal('dtstart'), new Date(), padDoc), (0, _rdflib.st)(participation, ns.ui('backgroundColor'), (0, _pad.lightColorHash)(me), padDoc)]; - store.updater.update([], ins, function (uri, ok, errorMessage) { - if (!ok) { - throw new Error('Error recording your partipation: ' + errorMessage); + + /** + * Records errors in the system on failure: + * + * - Adds an entry to the request status collection + * - Adds an error triple with the fail message to the metadata + * - Fires the 'fail' callback + * - Rejects with an error result object, which has a response object if any + */ + }, { + key: "failFetch", + value: function failFetch(options, errorMessage, statusCode, response) { + this.addStatus(options.req, errorMessage); + if (!options.noMeta) { + this.store.add(options.original, this.ns.link('error'), this.store.rdfFactory.literal(errorMessage)); } - if (refreshable && refreshable.refresh) { - refreshable.refresh(); + var meth = (options.method || 'GET').toUpperCase(); + var isGet = meth === 'GET' || meth === 'HEAD'; + if (isGet) { + // only cache the status code on GET or HEAD + if (!options.resource.equals(options.original)) { + // console.log('@@ Recording failure ' + meth + ' original ' + options.original +option '( as ' + options.resource + ') : ' + statusCode) + } else { + // console.log('@@ Recording ' + meth + ' failure for ' + options.original + ': ' + statusCode) + } + this.requested[_uri__WEBPACK_IMPORTED_MODULE_21__.docpart(options.original.value)] = statusCode; + this.fireCallbacks('fail', [options.original.value, errorMessage]); } - // UI.pad.renderPartipants(dom, table, padDoc, subject, me, options) - }); - - return participation; - } -} - -/** Record my participation and display participants -* -* @param {Document} dom - the web page loaded into the browser -* @param {HTMLDivElement} container - the container element where the participants should be displayed -* @param {NamedNode} document - the document into which the particpation should be shown -* @param {NamedNode} subject - the thing in which participation is happening -* @param {NamedNode} me - the logged in user -* @param {ParticipationOptions} options - the options that can be passed in are deleteFunction, link, and draggable these are used by the personTR button -* -*/ -function manageParticipation(dom, container, padDoc, subject, me, options) { - var table = dom.createElement('table'); - container.appendChild(table); - renderPartipants(dom, table, padDoc, subject, me, options); - var _participation; - try { - _participation = recordParticipation(subject, padDoc, table); - } catch (e) { - container.appendChild((0, _widgets.errorMessageBlock)(dom, 'Error recording your partipation: ' + e)); // Clean up? - } - - return table; -} -//# sourceMappingURL=participation.js.map - -/***/ }), - -/***/ "./lib/preferences.js": -/*!****************************!*\ - !*** ./lib/preferences.js ***! - \****************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { - -"use strict"; - - -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.get = get; -exports.getPreferencesForClass = getPreferencesForClass; -exports.recordPersonalDefaults = recordPersonalDefaults; -exports.recordSharedPreferences = recordSharedPreferences; -exports.renderPreferencesForm = renderPreferencesForm; -exports.set = set; -exports.value = void 0; -var $rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "../rdflib/esm/index.js")); -var _solidLogic = __webpack_require__(/*! solid-logic */ "../solid-logic/lib/index.js"); -var debug = _interopRequireWildcard(__webpack_require__(/*! ./debug */ "./lib/debug.js")); -var _login = __webpack_require__(/*! ./login/login */ "./lib/login/login.js"); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var participation = _interopRequireWildcard(__webpack_require__(/*! ./participation */ "./lib/participation.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ./widgets */ "./lib/widgets/index.js")); -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); } -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; } -// Solid-UI preferences -// ===================== -// - -// pull in first avoid cross-refs + var err = new Error('Fetcher: ' + errorMessage); -// @ts-ignore + // err.ok = false // Is taken as a response, will work too @@ phase out? + err.status = statusCode; + err.statusText = errorMessage; + err.response = response; + return Promise.reject(err); + } -var kb = _solidLogic.store; + // in the why part of the quad distinguish between HTML and HTTP header + // Reverse is set iif the link was rev= as opposed to rel= + }, { + key: "linkData", + value: function linkData(originalUri, rel, uri, why, reverse) { + if (!uri) return; + var kb = this.store; + var predicate; + // See http://www.w3.org/TR/powder-dr/#httplink for describedby 2008-12-10 + var obj = kb.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_21__.join(uri, originalUri.value)); + if (rel === 'alternate' || rel === 'seeAlso' || rel === 'meta' || rel === 'describedby') { + if (obj.value === originalUri.value) { + return; + } + predicate = this.ns.rdfs('seeAlso'); + } else if (rel === 'type') { + predicate = kb.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'); + } else { + // See https://www.iana.org/assignments/link-relations/link-relations.xml + // Alas not yet in RDF yet for each predicate + // encode space in e.g. rel="shortcut icon" + predicate = kb.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_21__.join(encodeURIComponent(rel), 'http://www.iana.org/assignments/link-relations/')); + } + if (reverse) { + kb.add(obj, predicate, originalUri, why); + } else { + kb.add(originalUri, predicate, obj, why); + } + } + }, { + key: "parseLinkHeader", + value: function parseLinkHeader(linkHeader, originalUri, reqNode) { + if (!linkHeader) { + return; + } -// This was tabulator . preferences in the tabulator -// Is this functionality used anywhere? -// + // const linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^()<>@,;:"/[]?={} \t]+)|("[^"]*")))*(,|$)/g + // const paramexp = /[^()<>@,;:"/[]?={} \t]+=(([^()<>@,;:"/[]?={} \t]+)|("[^"]*"))/g -// used for storing user name -// @@ Deprocate these functions. They were used for -// communication around the tabulator functionality about the user session + // From https://www.dcode.fr/regular-expression-simplificator: + // const linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} t]+=["]))*[,$]/g + // const paramexp = /[^\\<>@,;:"\/\[\]?={} \t]+=["])/g + // Original: + var linkexp = /<[^>]*>\s*(\s*;\s*[^()<>@,;:"/[\]?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|$)/g; + var paramexp = /[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g; + var matches = linkHeader.match(linkexp); + if (matches == null) return; + for (var i = 0; i < matches.length; i++) { + var split = matches[i].split('>'); + var href = split[0].substring(1); + var ps = split[1]; + var s = ps.match(paramexp); + if (s == null) return; + for (var j = 0; j < s.length; j++) { + var p = s[j]; + var paramsplit = p.split('='); + // var name = paramsplit[0] + var rel = paramsplit[1].replace(/["']/g, ''); // '" + this.linkData(originalUri, rel, href, reqNode); + } + } + } + }, { + key: "doneFetch", + value: function doneFetch(options, response) { + this.addStatus(options.req, 'Done.'); + this.requested[options.original.value] = 'done'; + this.fireCallbacks('done', [options.original.value]); + response.req = options.req; // Set the request meta blank node -var value = []; -exports.value = value; -function get(k) { - return value[k]; -} -function set(k, v) { - if (typeof v !== 'string') { - debug.log('Non-string value of preference ' + k + ': ' + v); - throw new Error('Non-string value of preference ' + k + ': ' + v); - } - this.value[k] = v; -} + return response; + } -// In a solid world, Preferences are stored in the web -// -// Make an RDF node for recording the common view preferences for any object -// (maybe make it in a separate file?) -function recordSharedPreferences(subject, context) { - return new Promise(function (resolve, reject) { - var sharedPreferences = kb.any(subject, ns.ui('sharedPreferences')); - if (!sharedPreferences) { - var sp = $rdf.sym(subject.doc().uri + '#SharedPreferences'); - var ins = [$rdf.st(subject, ns.ui('sharedPreferences'), sp, subject.doc())]; - debug.log('Creating shared preferences ' + sp); - kb.updater.update([], ins, function (uri, ok, errorMessage) { - if (!ok) { - reject(new Error('Error creating shared prefs: ' + errorMessage)); - } else { - context.sharedPreferences = sp; - resolve(context); + /** + * Note two nodes are now smushed + * If only one was flagged as looked up, then the new node is looked up again, + * which will make sure all the URIs are dereferenced + */ + }, { + key: "nowKnownAs", + value: function nowKnownAs(was, now) { + if (this.lookedUp[was.value]) { + // Transfer userCallback + if (!this.lookedUp[now.value]) { + this.lookUpThing(now, was); } - }); - } else { - context.sharedPreferences = sharedPreferences; - resolve(context); + } else if (this.lookedUp[now.value]) { + if (!this.lookedUp[was.value]) { + this.lookUpThing(was, now); + } + } } - }); -} -// Construct a personal defaults node in the preferences file for a given class of object -// -function recordPersonalDefaults(theClass, context) { - return new Promise(function (resolve, reject) { - (0, _login.ensureLoadedPreferences)(context).then(function (context) { - if (!context.preferencesFile) { - debug.log('Not doing private class preferences as no access to preferences file. ' + context.preferencesFileError); - return; + /** + * Writes back to the web what we have in the store for this uri + */ + }, { + key: "putBack", + value: function putBack(uri) { + var _this6 = this; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var uriSting = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uri); + var doc = new _named_node__WEBPACK_IMPORTED_MODULE_22__["default"](uriSting).doc(); // strip off # + options.contentType = options["content-type"] || options["Content-Type"] || options.contentType || _types__WEBPACK_IMPORTED_MODULE_9__.TurtleContentType; + if (options.contentType === 'application/ld+json') { + return new Promise(function (resolve, reject) { + (0,_serialize__WEBPACK_IMPORTED_MODULE_23__["default"])(doc, _this6.store, doc.uri, options.contentType, function (err, jsonString) { + if (err) { + reject(err); + } else { + // @ts-ignore + options.data = jsonString; + _this6.webOperation('PUT', uri, options).then(function (res) { + return resolve(res); + }).catch(function (error) { + return reject(error); + }); + } + }); + }); } - var regs = kb.each(null, ns.solid('forClass'), theClass, context.preferencesFile); - var ins = []; - var prefs; - var reg; - if (regs.length) { - // Use existing node if we can - regs.forEach(function (r) { - prefs = prefs || kb.any(r, ns.solid('personalDefaults')); + options.data = (0,_serialize__WEBPACK_IMPORTED_MODULE_23__["default"])(doc, this.store, doc.value, options.contentType); + return this.webOperation('PUT', uriSting, options); + } + }, { + key: "webCopy", + value: function webCopy(here, there, contentType) { + var _this7 = this; + return this.webOperation('GET', here).then(function (result) { + return _this7.webOperation('PUT', + // change to binary from text + there, { + data: result.responseText, + contentType: contentType }); - if (prefs) { - context.personalDefaults = prefs; // Found one - resolve(context); - return; - } else { - prefs = widgets.newThing(context.preferencesFile); - reg = regs[0]; + }); + } + }, { + key: "delete", + value: function _delete(uri, options) { + var _this8 = this; + return this.webOperation('DELETE', uri, options).then(function (response) { + _this8.requested[uri] = 404; + _this8.nonexistent[uri] = true; + _this8.unload(_this8.store.rdfFactory.namedNode(uri)); + return response; + }); + } + + /** Create an empty resource if it really does not exist + * Be absolutely sure something does not exist before creating a new empty file + * as otherwise existing could be deleted. + * @param doc - The resource + */ + }, { + key: "createIfNotExists", + value: function () { + var _createIfNotExists = (0,_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__["default"])( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().mark(function _callee2(doc) { + var contentType, + data, + fetcher, + response, + _args2 = arguments; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_7___default().wrap(function _callee2$(_context2) { + while (1) switch (_context2.prev = _context2.next) { + case 0: + contentType = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : _types__WEBPACK_IMPORTED_MODULE_9__.TurtleContentType; + data = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : ''; + fetcher = this; + _context2.prev = 3; + _context2.next = 6; + return fetcher.load(doc); + case 6: + response = _context2.sent; + _context2.next = 26; + break; + case 9: + _context2.prev = 9; + _context2.t0 = _context2["catch"](3); + if (!(_context2.t0.response.status === 404)) { + _context2.next = 25; + break; + } + _context2.prev = 12; + _context2.next = 15; + return fetcher.webOperation('PUT', doc.value, { + data: data, + contentType: contentType + }); + case 15: + response = _context2.sent; + _context2.next = 21; + break; + case 18: + _context2.prev = 18; + _context2.t1 = _context2["catch"](12); + throw _context2.t1; + case 21: + delete fetcher.requested[doc.value]; // delete cached 404 error + // console.log('createIfNotExists doc created ok ' + doc) + return _context2.abrupt("return", response); + case 25: + throw _context2.t0; + case 26: + return _context2.abrupt("return", response); + case 27: + case "end": + return _context2.stop(); + } + }, _callee2, this, [[3, 9], [12, 18]]); + })); + function createIfNotExists(_x4) { + return _createIfNotExists.apply(this, arguments); + } + return createIfNotExists; + }() + /** + * @param parentURI URI of parent container + * @param folderName - Optional folder name (slug) + * @param data - Optional folder metadata + */ + }, { + key: "createContainer", + value: function createContainer(parentURI, folderName, data) { + var headers = { + // Force the right mime type for containers + 'content-type': _types__WEBPACK_IMPORTED_MODULE_9__.TurtleContentType, + 'link': this.ns.ldp('BasicContainer') + '; rel="type"' + }; + if (folderName) { + headers['slug'] = folderName; + } + + // @ts-ignore These headers lack some of the required operators. + var options = { + headers: headers + }; + if (data) { + options.body = data; + } + return this.webOperation('POST', parentURI, options); + } + }, { + key: "invalidateCache", + value: function invalidateCache(iri) { + var uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(iri); + var fetcher = this; + // @ts-ignore + if (fetcher.fetchQueue && fetcher.fetchQueue[uri]) { + // console.log('Internal error - fetchQueue exists ' + uri) + var promise = fetcher.fetchQueue[uri]; + if (promise['PromiseStatus'] === 'resolved') { + delete fetcher.fetchQueue[uri]; + } else { + // pending + delete fetcher.fetchQueue[uri]; + // console.log('*** Fetcher: pending fetchQueue deleted ' + uri) } + } + + if (fetcher.requested[uri] && fetcher.requested[uri] !== 'done' && fetcher.requested[uri] !== 'failed' && fetcher.requested[uri] !== 404) { + var msg = "Rdflib: fetcher: Destructive operation on <".concat(fetcher.requested[uri], "> file being fetched! ") + uri; + console.error(msg); + // alert(msg) } else { - // no regs fo class - reg = widgets.newThing(context.preferencesFile); - ins = [$rdf.st(reg, ns.rdf('type'), ns.solid('TypeRegistration'), context.preferencesFile), $rdf.st(reg, ns.solid('forClass'), theClass, context.preferencesFile)]; + delete fetcher.requested[uri]; // invalidate read cache -- @@ messes up logic if request in progress ?? + delete fetcher.nonexistent[uri]; } - prefs = widgets.newThing(context.preferencesFile); - ins.push($rdf.st(reg, ns.solid('personalDefaults'), prefs, context.preferencesFile)); - kb.updater.update([], ins, function (uri, ok, errm) { - if (!ok) { - reject(new Error('Setting preferences for ' + theClass + ': ' + errm)); - } else { - context.personalDefaults = prefs; - resolve(context); - } - }); - }, function (err) { - reject(err); - }); - }); -} -function renderPreferencesForm(subject, theClass, preferencesForm, context) { - var prefContainer = context.dom.createElement('div'); - participation.participationObject(subject, subject.doc(), context.me).then(function (participation) { - var dom = context.dom; - function heading(text) { - prefContainer.appendChild(dom.createElement('h5')).textContent = text; } - heading('My view of this ' + context.noun); - widgets.appendForm(dom, prefContainer, {}, participation, preferencesForm, subject.doc(), function (ok, mes) { - if (!ok) widgets.complain(context, mes); - }); - heading("Everyone's view of this " + context.noun); - recordSharedPreferences(subject, context).then(function (context) { - var sharedPreferences = context.sharedPreferences; - widgets.appendForm(dom, prefContainer, {}, sharedPreferences, preferencesForm, subject.doc(), function (ok, mes) { - if (!ok) widgets.complain(context, mes); - }); - heading('My default view of any ' + context.noun); - recordPersonalDefaults(theClass, context).then(function (context) { - widgets.appendForm(dom, prefContainer, {}, context.personalDefaults, preferencesForm, context.preferencesFile, function (ok, mes) { - if (!ok) widgets.complain(context, mes); - }); - }, function (err) { - widgets.complain(context, err); - }); - }); - }, function (err) { - // parp object fails - prefContainer.appendChild(widgets.errorMessageBlock(context.dom, err)); - }); - return prefContainer; -} - -// This should be part of rdflib.js ad part of the RDFJS Standard!! - -function toJS(term) { - if (!term.datatype) return term; // Objects remain objects - if (term.datatype.equals(ns.xsd('boolean'))) { - return term.value === '1'; - } - if (term.datatype.equals(ns.xsd('dateTime')) || term.datatype.equals(ns.xsd('date'))) { - return new Date(term.value); - } - if (term.datatype.equals(ns.xsd('integer')) || term.datatype.equals(ns.xsd('float')) || term.datatype.equals(ns.xsd('decimal'))) { - return Number(term.value); - } - return term.value; -} -// This is the function which acuakly reads and combines the preferences -// -// @@ make it much more tolerant of missing buts of prefernces -function getPreferencesForClass(subject, theClass, predicates, context) { - return new Promise(function (resolve, reject) { - recordSharedPreferences(subject, context).then(function (context) { - var sharedPreferences = context.sharedPreferences; - if (context.me) { - participation.participationObject(subject, subject.doc(), context.me).then(function (participation) { - recordPersonalDefaults(theClass, context).then(function (context) { - var results = []; - var personalDefaults = context.personalDefaults; - predicates.forEach(function (pred) { - // Order of preference: My settings on object, Global settings on object, my settings on class - var v1 = kb.any(participation, pred) || kb.any(sharedPreferences, pred) || kb.any(personalDefaults, pred); - if (v1) { - results[pred.uri] = toJS(v1); - } - }); - resolve(results); - }, reject); - }, reject); - } else { - // no user defined, just use common prefs - var results = []; - predicates.forEach(function (pred) { - var v1 = kb.any(sharedPreferences, pred); - if (v1) { - results[pred.uri] = toJS(v1); + /** + * A generic web operation, at the fetch() level. + * does not involve the quad store. + * + * Returns promise of Response + * If data is returned, copies it to response.responseText before returning + */ + }, { + key: "webOperation", + value: function webOperation(method, uriIn) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var uri = (0,_utils_termValue__WEBPACK_IMPORTED_MODULE_18__.termValue)(uriIn); + options.method = method; + options.body = options.data || options.body; + options.force = true; + var fetcher = this; + if (options.body && !options.contentType) { + throw new Error('Web operation sending data must have a defined contentType.'); + } + if (options.contentType) { + options.headers = options.headers || {}; + options.headers['content-type'] = options.contentType; + } + Fetcher.setCredentials(uri, options); + return new Promise(function (resolve, reject) { + fetcher._fetch(uri, options).then(function (response) { + if (response.ok) { + if (method === 'PUT' || method === 'PATCH' || method === 'POST' || method === 'DELETE') { + fetcher.invalidateCache(uri); + } // response.body with Chrome can't be relied on + if (response.text) { + // Was: response.body https://github.com/linkeddata/rdflib.js/issues/506 + response.text().then(function (data) { + response.responseText = data; + resolve(response); + }); + } else { + resolve(response); + } + } else { + var msg = 'Web error: ' + response.status; + if (response.statusText) msg += ' (' + response.statusText + ')'; + msg += ' on ' + method + ' of <' + uri + '>'; + if (response.responseText) msg += ': ' + response.responseText; + var e2 = new Error(msg); + e2.response = response; + reject(e2); } + }, function (err) { + var msg = 'Fetch error for ' + method + ' of <' + uri + '>:' + err; + reject(new Error(msg)); }); - resolve(results); - } - }); - }); -} - -// ends -//# sourceMappingURL=preferences.js.map - -/***/ }), + }); + } -/***/ "./lib/signup/config-default.js": -/*!**************************************!*\ - !*** ./lib/signup/config-default.js ***! - \**************************************/ -/***/ ((__unused_webpack_module, exports) => { + /** + * Looks up something. + * Looks up all the URIs a things has. + * + * @param term - canonical term for the thing whose URI is + * to be dereferenced + * @param rterm - the resource which referred to this + * (for tracking bad links) + */ + }, { + key: "lookUpThing", + value: function lookUpThing(term, rterm) { + var _this9 = this; + var uris = this.store.uris(term); // Get all URIs + uris = uris.map(function (u) { + return _uri__WEBPACK_IMPORTED_MODULE_21__.docpart(u); + }); // Drop hash fragments -"use strict"; + uris.forEach(function (u) { + _this9.lookedUp[u] = true; + }); + // @ts-ignore Recursive type + return this.load(uris, { + referringTerm: rterm + }); + } -/** - * Provides a simple configuration object for Solid web client and other - * modules. - * @module config-default - */ -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = { - // @@ should not use export default - /** - * Primary authentication endpoint - */ - authEndpoint: '', - /** - * Fallback authentication endpoint - */ - fallbackAuthEndpoint: 'https://databox.me/', - /** - * Default signup endpoints (list of identity providers) - */ - signupEndpoint: 'https://solidproject.org/use-solid/', - /** - * Default height of the Signup popup window, in pixels - */ - signupWindowHeight: 600, - /** - * Default width of the Signup popup window, in pixels - */ - signupWindowWidth: 1024, - /** - * Path to the client private key (only needed when running within node) - */ - key: '', - /** - * Path to the client certificate (only needed when running within node) - */ - cert: '' -}; -exports["default"] = _default; -//# sourceMappingURL=config-default.js.map + /** + * Looks up response header. + * + * @returns {Array|undefined} a list of header values found in a stored HTTP + * response, or [] if response was found but no header found, + * or undefined if no response is available. + * Looks for { [] link:requestedURI ?uri; link:response [ httph:header-name ?value ] } + */ + }, { + key: "getHeader", + value: function getHeader(doc, header) { + var kb = this.store; // look for the URI (AS A STRING NOT A NODE) for a stored request + var docuri = doc.value; + var requests = kb.each(undefined, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri)); + for (var r = 0; r < requests.length; r++) { + var request = requests[r]; + if (request !== undefined) { + var _response2 = kb.any(request, this.ns.link('response')); + if (_response2 !== undefined && kb.anyValue(_response2, this.ns.http('status')) && kb.anyValue(_response2, this.ns.http('status')).startsWith('2')) { + // Only look at success returns - not 401 error messagess etc + var results = kb.each(_response2, this.ns.httph(header.toLowerCase())); + if (results.length) { + return results.map(function (v) { + return v.value; + }); + } + return []; + } + } + } + return undefined; + } + }, { + key: "saveRequestMetadata", + value: function saveRequestMetadata(docuri, options) { + var req = options.req; + var kb = this.store; + var rterm = options.referringTerm; + this.addStatus(options.req, 'Accept: ' + options.headers['accept']); + if ((0,_utils_terms__WEBPACK_IMPORTED_MODULE_19__.isNamedNode)(rterm)) { + kb.add(kb.rdfFactory.namedNode(docuri), this.ns.link('requestedBy'), rterm, this.appNode); + } + if (options.original && options.original.value !== docuri) { + kb.add(req, this.ns.link('orginalURI'), kb.rdfFactory.literal(options.original.value), this.appNode); + } + var now = new Date(); + var timeNow = '[' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + '] '; + kb.add(req, this.ns.rdfs('label'), kb.rdfFactory.literal(timeNow + ' Request for ' + docuri), this.appNode); + // We store the docuri as a string, not as a node, + // see https://github.com/linkeddata/rdflib.js/pull/427#pullrequestreview-447910061 + kb.add(req, this.ns.link('requestedURI'), kb.rdfFactory.literal(docuri), this.appNode); + kb.add(req, this.ns.link('status'), kb.collection(), this.appNode); + } + }, { + key: "saveResponseMetadata", + value: function saveResponseMetadata(response, options) { + var _this10 = this; + var kb = this.store; + var responseNode = kb.bnode(); + kb.add(options.req, this.ns.link('response'), responseNode, this.appNode); + kb.add(responseNode, this.ns.http('status'), kb.rdfFactory.literal(response.status), this.appNode); + kb.add(responseNode, this.ns.http('statusText'), kb.rdfFactory.literal(response.statusText), this.appNode); -/***/ }), + // Save the response headers + response.headers.forEach(function (value, header) { + kb.add(responseNode, _this10.ns.httph(header), _this10.store.rdfFactory.literal(value), _this10.appNode); + if (header === 'content-type') { + kb.add(options.resource, _this10.ns.rdf('type'), kb.rdfFactory.namedNode(_utils_js__WEBPACK_IMPORTED_MODULE_11__.mediaTypeClass(value).value), _this10.appNode // responseNode + ); + } + }); -/***/ "./lib/signup/signup.js": -/*!******************************!*\ - !*** ./lib/signup/signup.js ***! - \******************************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + return responseNode; + } + }, { + key: "objectRefresh", + value: function objectRefresh(term) { + var uris = this.store.uris(term); // Get all URIs + if (typeof uris !== 'undefined') { + for (var i = 0; i < uris.length; i++) { + this.refresh(this.store.rdfFactory.namedNode(_uri__WEBPACK_IMPORTED_MODULE_21__.docpart(uris[i]))); + // what about rterm? + } + } + } -"use strict"; + /* refresh Reload data from a given document + ** + ** @param term - An RDF Named Node for the eodcument in question + ** @param userCallback - A function userCallback(ok, message, response) + */ + }, { + key: "refresh", + value: function refresh(term, userCallback) { + // sources_refresh + this.fireCallbacks('refresh', arguments); + this.nowOrWhenFetched(term, { + force: true, + clearPreviousData: true + }, userCallback); + } + /* refreshIfExpired Conditional refresh if Expired + ** + ** @param term - An RDF Named Node for the eodcument in question + ** @param userCallback - A function userCallback(ok, message, response) + */ + }, { + key: "refreshIfExpired", + value: function refreshIfExpired(term, userCallback) { + var exp = this.getHeader(term, 'Expires'); + if (!exp || new Date(exp[0]).getTime() <= new Date().getTime()) { + this.refresh(term, userCallback); + } else { + userCallback(true, 'Not expired', {}); + } + } + }, { + key: "retract", + value: function retract(term) { + // sources_retract + this.store.removeMany(undefined, undefined, undefined, term); + if (term.value) { + delete this.requested[_uri__WEBPACK_IMPORTED_MODULE_21__.docpart(term.value)]; + } + this.fireCallbacks('retract', arguments); + } + }, { + key: "getState", + value: function getState(docuri) { + if (typeof this.requested[docuri] === 'undefined') { + return 'unrequested'; + } else if (this.requested[docuri] === true) { + return 'requested'; + } else if (this.requested[docuri] === 'done') { + return 'fetched'; + } else if (this.requested[docuri] === 'redirected') { + return this.getState(this.redirectedTo[docuri]); + } else { + // An non-200 HTTP error status + return 'failed'; + } + } + }, { + key: "isPending", + value: function isPending(docuri) { + // sources_pending + // doing anyStatementMatching is wasting time + // if it's not pending: false -> flailed + // 'done' -> done 'redirected' -> redirected + return this.requested[docuri] === true; + } + }, { + key: "unload", + value: function unload(term) { + this.store.removeDocument(term); + delete this.requested[term.value]; // So it can be load2ed again + } + }, { + key: "addHandler", + value: function addHandler(handler) { + this.handlers.push(handler); + handler.register(this); + } + }, { + key: "retryNoCredentials", + value: function retryNoCredentials(docuri, options) { + // console.log('Fetcher: CORS: RETRYING with NO CREDENTIALS for ' + options.resource) -var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.Signup = Signup; -var _configDefault = _interopRequireDefault(__webpack_require__(/*! ./config-default */ "./lib/signup/config-default.js")); -/** - * Provides functionality for signing up with a Solid provider - * @module signup - */ + options.retriedWithNoCredentials = true; // protect against being called twice -/** - * Creates a Signup UI manager - * @class - */ -function Signup(config) { - this.config = config || _configDefault["default"]; -} + delete this.requested[docuri]; // forget the original request happened + delete this.fetchQueue[docuri]; + // Note: XHR property was withCredentials, but fetch property is just credentials + var newOptions = Object.assign({}, options, { + credentials: 'omit' + }); + this.addStatus(options.req, 'Abort: Will retry with credentials SUPPRESSED to see if that helps'); + return this.load(docuri, newOptions); + } -/** - * Sets up an event listener to monitor login messages from child window/iframe - * @method listen - * @return {Promise} Event listener promise, resolves to user's WebID - */ -Signup.prototype.listen = function listen() { - var promise = new Promise(function (resolve, reject) { - var eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent'; - var eventListener = window[eventMethod]; - var messageEvent = eventMethod === 'attachEvent' ? 'onmessage' : 'message'; - eventListener(messageEvent, function (e) { - var u = e.data; - if (u.slice(0, 5) === 'User:') { - var user = u.slice(5, u.length); - if (user && user.length > 0 && user.slice(0, 4) === 'http') { - return resolve(user); - } else { - return reject(user); - } + /** + * Tests whether a request is being made to a cross-site URI (for purposes + * of retrying with a proxy) + */ + }, { + key: "isCrossSite", + value: function isCrossSite(uri) { + // Mashup situation, not node etc + if (typeof document === 'undefined' || !document.location) { + return false; } - }, true); - }); - return promise; -}; - -/** - * Opens a signup popup window, sets up `listen()`. - * @method signup - * @static - * @param signupUrl {String} Location of a Solid server for user signup. - * @return {Promise} Returns a listener promise, resolves with signed - * up user's WebID. - */ -Signup.prototype.signup = function signup(signupUrl) { - signupUrl = signupUrl || this.config.signupEndpoint; - var width = this.config.signupWindowWidth; - var height = this.config.signupWindowHeight; - // set borders - var leftPosition = window.screen.width / 2 - (width / 2 + 10); - // set title and status bars - var topPosition = window.screen.height / 2 - (height / 2 + 50); - var windowTitle = 'Solid signup'; - var windowUrl = signupUrl + '?origin=' + encodeURIComponent(window.location.origin); - var windowSpecs = 'resizable,scrollbars,status,width=' + width + ',height=' + height + ',left=' + leftPosition + ',top=' + topPosition; - window.open(windowUrl, windowTitle, windowSpecs); - var self = this; - return new Promise(function (resolve) { - self.listen().then(function (webid) { - return resolve(webid); - }); - }); -}; -//# sourceMappingURL=signup.js.map - -/***/ }), + var hostpart = _uri__WEBPACK_IMPORTED_MODULE_21__.hostpart; + var here = '' + document.location; + return (hostpart(here) && hostpart(uri) && hostpart(here)) !== hostpart(uri); + } -/***/ "./lib/style.js": -/*!**********************!*\ - !*** ./lib/style.js ***! - \**********************/ -/***/ ((module, exports) => { + /** + * Called when there's a network error in fetch(), or a response + * with status of 0. + */ + }, { + key: "handleError", + value: function handleError(response, docuri, options) { + if (this.isCrossSite(docuri)) { + // Make sure we haven't retried already + if (options.credentials && options.credentials === 'include' && !options.retriedWithNoCredentials) { + return this.retryNoCredentials(docuri, options); + } -"use strict"; + // Now attempt retry via proxy + var proxyUri = Fetcher.crossSiteProxy(docuri); + if (proxyUri && !options.proxyUsed) { + // console.log('web: Direct failed so trying proxy ' + proxyUri) + return this.redirectToProxy(proxyUri, options); + } + } + var message; + if (response instanceof Error) { + message = 'Fetch error: ' + response.message; + } else { + message = response.statusText; + if (response.responseText) { + message += " ".concat(response.responseText); + } + } + // This is either not a CORS error, or retries have been made + return this.failFetch(options, message, response.status || 998, response); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.style = void 0; -// Common readable consistent stylesheet -// to avoid using style sheets which are document-global -// and make programmable style toggling with selection, drag over, etc easier + // deduce some things from the HTTP transaction + }, { + key: "addType", + value: function addType(rdfType, req, kb, locURI) { + // add type to all redirected resources too + var prev = req; + if (locURI) { + var reqURI = kb.any(prev, this.ns.link('requestedURI')); + if (reqURI && reqURI.value !== locURI) { + kb.add(kb.rdfFactory.namedNode(locURI), this.ns.rdf('type'), rdfType, this.appNode); + } + } + for (;;) { + var doc = kb.any(prev, this.ns.link('requestedURI')); + if (doc && doc.value) { + kb.add(kb.rdfFactory.namedNode(doc.value), this.ns.rdf('type'), rdfType, this.appNode); + } // convert Literal + prev = kb.any(undefined, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#redirectedRequest'), prev); + if (!prev) { + break; + } + var response = kb.any(prev, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#response')); + if (!response) { + break; + } + var redirection = kb.any(response, kb.rdfFactory.namedNode('http://www.w3.org/2007/ont/http#status')); + if (!redirection) { + break; + } + // @ts-ignore always true? + if (redirection !== '301' && redirection !== '302') { + break; + } + } + } -// These must all end with semicolon so they can be appended to. + /** + * Handle fetch() response + */ + }, { + key: "handleResponse", + value: function handleResponse(response, docuri, options) { + var _this11 = this; + var kb = this.store; + var headers = response.headers; + var reqNode = options.req; + var responseNode = this.saveResponseMetadata(response, options); + var contentType = this.normalizedContentType(options, headers) || ''; + var contentLocation = headers.get('content-location'); -var formBorderColor = '#888888'; // Mid-grey -var lowProfileLinkColor = '#3B5998'; // Grey-blue, e.g., for field labels linking to ontology -var formFieldNameBoxWidth = '8em'; // The fixed amount to get form fields to line up -// The latter we put in when switching awy from using tables. Getting allignment between -// fields in different groups though is hard problem. + // this.fireCallbacks('recv', xhr.args) + // this.fireCallbacks('headers', [{uri: docuri, headers: xhr.headers}]) -var style = { - // styleModule + // Check for masked errors (CORS, etc) + if (response.status === 0) { + // console.log('Masked error - status 0 for ' + docuri) + return this.handleError(response, docuri, options); + } + if (response.status >= 400) { + if (response.status === 404) { + this.nonexistent[options.original.value] = true; + this.nonexistent[docuri] = true; + } + return this.saveErrorResponse(response, responseNode).then(function () { + var errorMessage = options.resource + ' ' + response.statusText; + return _this11.failFetch(options, errorMessage, response.status, response); + }); + } + var diffLocation = null; + var absContentLocation = null; + if (contentLocation) { + absContentLocation = _uri__WEBPACK_IMPORTED_MODULE_21__.join(contentLocation, docuri); + if (absContentLocation !== docuri) { + diffLocation = absContentLocation; + } + } + if (response.status === 200) { + this.addType(this.ns.link('Document'), reqNode, kb, docuri); + if (diffLocation) { + this.addType(this.ns.link('Document'), reqNode, kb, diffLocation); + } - checkboxStyle: 'colour: black; font-size: 100%; padding-left: 0.5 em; padding-right: 0.5 em;', - checkboxInputStyle: 'font-size: 150%; height: 1.2em; width: 1.2em; background-color: #eef; border-radius:0.2em; margin: 0.1em', - fieldLabelStyle: 'color: #3B5998; text-decoration: none;', - formSelectSTyle: 'background-color: #eef; padding: 0.5em; border: .05em solid #88c; border-radius:0.2em; font-size: 100%; margin:0.4em;', - textInputStyle: 'background-color: #eef; padding: 0.5em; border: .05em solid #88c; border-radius:0.2em; font-size: 100%; margin:0.4em;', - textInputStyleUneditable: - // Color difference only - 'background-color: white; padding: 0.5em; border: .05em solid white; border-radius:0.2em; font-size: 100%; margin:0.4em;', - textInputSize: 20, - // Default text input size in characters roughly - buttonStyle: 'background-color: #fff; padding: 0.7em; border: .01em solid white; border-radius:0.2em; font-size: 100%; margin: 0.3em;', - // 'background-color: #eef; - commentStyle: 'padding: 0.7em; border: none; font-size: 100%; white-space: pre-wrap;', - iconStyle: 'width: 3em; height: 3em; margin: 0.1em; border-radius: 1em;', - smallButtonStyle: 'margin: 0.2em; width: 1em; height:1em;', - classIconStyle: 'width: 3em; height: 3em; margin: 0.1em; border-radius: 0.2em; border: 0.1em solid green; padding: 0.2em; background-color: #efe;', - // combine with buttonStyle - confirmPopupStyle: 'padding: 0.7em; border-radius: 0.2em; border: 0.1em solid orange; background-color: white; box-shadow: 0.5em 0.9em #888;', - tabBorderRadius: '0.2em', - messageBodyStyle: 'white-space: pre-wrap; width: 99%; font-size:100%; border: 0.07em solid #eee; border-radius:0.2em; padding: .3em 0.5em; margin: 0.1em;', - pendingeditModifier: 'color: #bbb;', - highlightColor: '#7C4DFF', - // Solid lavendar https://design.inrupt.com/atomic-core/?cat=Core + // Before we parse new data clear old but only on 200 + if (options.clearPreviousData) { + kb.removeDocument(options.resource); + } + var isImage = contentType.includes('image/') || contentType.includes('application/pdf'); + if (contentType && isImage) { + this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb, docuri); + if (diffLocation) { + this.addType(kb.rdfFactory.namedNode('http://purl.org/dc/terms/Image'), reqNode, kb, diffLocation); + } + } + } - // Contacts - personaBarStyle: 'width: 100%; height: 4em; background-color: #eee; vertical-align: middle;', - searchInputStyle: 'border: 0.1em solid #444; border-radius: 0.2em; width: 100%; font-size: 100%; padding: 0.1em 0.6em; margin 0.2em;', - autocompleteRowStyle: 'border: 0.2em solid straw;', - // Login buttons - signInButtonStyle: 'padding: 1em; border-radius:0.2em; font-size: 100%;', - // was 0.5em radius + // If we have already got the thing at this location, abort + if (contentLocation) { + if (!options.force && diffLocation && this.requested[absContentLocation] === 'done') { + // we have already fetched this + // should we smush too? + // log.info("HTTP headers indicate we have already" + " retrieved " + + // xhr.resource + " as " + absContentLocation + ". Aborting.") + return this.doneFetch(options, response); + } + this.requested[absContentLocation] = true; + } + this.parseLinkHeader(headers.get('link'), options.original, reqNode); + var handler = this.handlerForContentType(contentType, response); + if (!handler) { + // Not a problem, we just don't extract data + this.addStatus(reqNode, 'Fetch over. No data handled.'); + return this.doneFetch(options, response); + } + return response.text() + // @ts-ignore Types seem right + .then(function (responseText) { + response.responseText = responseText; + return handler.parse(_this11, responseText, options, response); + }); + } + }, { + key: "saveErrorResponse", + value: function saveErrorResponse(response, responseNode) { + var _this12 = this; + var kb = this.store; + return response.text().then(function (content) { + if (content.length > 10) { + kb.add(responseNode, _this12.ns.http('content'), kb.rdfFactory.literal(content), responseNode); + } + }); + } + }, { + key: "handlerForContentType", + value: function handlerForContentType(contentType, response) { + if (!contentType) { + return null; + } + var Handler = this.handlers.find(function (handler) { + return contentType.match(handler.pattern); + }); - // Forms - heading1Style: 'font-size: 180%; font-weight: bold; color: #888888; padding: 0.5em; margin: 0.7em 0.0m;', - // originally was brown; now grey - heading2Style: 'font-size: 130%; font-weight: bold; color: #888888; padding: 0.4em; margin: 0.7em 0.0em;', - // originally was brown; now grey - heading3Style: 'font-size: 120%; font-weight: bold; color: #888888; padding: 0.3em; margin: 0.7em 0.0em;', - // For example, in large forms or before a small form - heading4Style: 'font-size: 110%; font-weight: bold; color: #888888; padding: 0.2em; margin: 0.7em 0.0em;', - // Lowest level used by default in small things + // @ts-ignore in practice all Handlers have constructors. + return Handler ? new Handler(response) : null; + } + }, { + key: "guessContentType", + value: function guessContentType(uri) { + return CONTENT_TYPE_BY_EXT[uri.split('.').pop()]; + } + }, { + key: "normalizedContentType", + value: function normalizedContentType(options, headers) { + if (options.forceContentType) { + return options.forceContentType; + } + var contentType = headers.get('content-type'); + if (!contentType || contentType.includes('application/octet-stream')) { + var guess = this.guessContentType(options.resource.value); + if (guess) { + return guess; + } + } + var protocol = _uri__WEBPACK_IMPORTED_MODULE_21__.protocol(options.resource.value); + if (!contentType && ['file', 'chrome'].includes(protocol)) { + return 'text/xml'; + } + return contentType; + } - formBorderColor: formBorderColor, - // originally was brown; now grey - formHeadingColor: '#888888', - // originally was brown; now grey - formHeadingStyle: 'font-size: 110%; font-weight: bold; color: #888888; padding: 0.2em; margin: 0.7em 0.0em;', - // originally was brown; now grey - formTextInput: 'font-size: 100%; margin: 0.1em; padding: 0.1em;', - // originally used this - formGroupStyle: ["padding-left: 0em; border: 0.0em solid ".concat(formBorderColor, "; border-radius: 0.2em;"), // weight 0 - "padding-left: 2em; border: 0.05em solid ".concat(formBorderColor, "; border-radius: 0.2em;"), "padding-left: 2em; border: 0.1em solid ".concat(formBorderColor, "; border-radius: 0.2em;"), "padding-left: 2em; border: 0.2em solid ".concat(formBorderColor, "; border-radius: 0.2em;") // @@ pink - ], - formFieldLabelStyle: "'color: ".concat(lowProfileLinkColor, "; text-decoration: none;'"), - formFieldNameBoxWidth: formFieldNameBoxWidth, - formFieldNameBoxStyle: "padding: 0.3em; vertical-align: middle; width:".concat(formFieldNameBoxWidth, ";"), - textInputBackgroundColor: '#eef', - textInputBackgroundColorUneditable: '#fff', - textInputColor: '#000', - textInputColorPending: '#888', - multilineTextInputStyle: 'font-size:100%; white-space: pre-wrap; background-color: #eef;' + ' border: 0.07em solid gray; padding: 1em 0.5em; margin: 1em 1em;', - // Buttons - renderAsDivStyle: 'display: flex; align-items: center; justify-content: space-between; height: 2.5em; padding: 1em;', - imageDivStyle: 'width:2.5em; padding:0.5em; height: 2.5em;', - linkDivStyle: 'width:2em; padding:0.5em; height: 4em;' -}; -exports.style = style; -style.setStyle = function setStyle(ele, styleName) { - ele.style = style[styleName]; -}; -module.exports = style; // @@ No way to do this in ESM -//# sourceMappingURL=style.js.map + /** + * Sends a new request to the specified uri. (Extracted from `onerrorFactory()`) + */ + }, { + key: "redirectToProxy", + value: function redirectToProxy(newURI, options) { + var _this13 = this; + this.addStatus(options.req, 'BLOCKED -> Cross-site Proxy to <' + newURI + '>'); + options.proxyUsed = true; + var kb = this.store; + var oldReq = options.req; // request metadata blank node -/***/ }), + if (!options.noMeta) { + kb.add(oldReq, this.ns.link('redirectedTo'), kb.rdfFactory.namedNode(newURI), oldReq); + this.addStatus(oldReq, 'redirected to new request'); // why + } -/***/ "./lib/style_multiSelect.js": -/*!**********************************!*\ - !*** ./lib/style_multiSelect.js ***! - \**********************************/ -/***/ ((module, exports) => { + this.requested[options.resource.value] = 'redirected'; + this.redirectedTo[options.resource.value] = newURI; + var newOptions = Object.assign({}, options); + newOptions.baseURI = options.resource.value; + return this.fetchUri(newURI, newOptions).then(function (response) { + if (!newOptions.noMeta) { + kb.add(oldReq, _this13.ns.link('redirectedRequest'), newOptions.req, _this13.appNode); + } + return response; + }); + } + }, { + key: "setRequestTimeout", + value: function setRequestTimeout(uri, options) { + var _this14 = this; + return new Promise(function (resolve) { + _this14.timeouts[uri] = (_this14.timeouts[uri] || []).concat(setTimeout(function () { + if (_this14.isPending(uri) && !options.retriedWithNoCredentials && !options.proxyUsed) { + resolve(_this14.failFetch(options, "Request to ".concat(uri, " timed out"), 'timeout')); + } + }, _this14.timeout)); + }); + } + }, { + key: "addFetchCallback", + value: function addFetchCallback(uri, callback) { + if (!this.fetchCallbacks[uri]) { + this.fetchCallbacks[uri] = [callback]; + } else { + this.fetchCallbacks[uri].push(callback); + } + } + }, { + key: "acceptString", + value: function acceptString() { + var acceptstring = ''; + for (var mediaType in this.mediatypes) { + if (acceptstring !== '') { + acceptstring += ', '; + } + acceptstring += mediaType; + for (var property in this.mediatypes[mediaType]) { + acceptstring += ';' + property + '=' + this.mediatypes[mediaType][property]; + } + } + return acceptstring; + } + // var updatesVia = new $rdf.UpdatesVia(this) // Subscribe to headers + // @@@@@@@@ This is turned off because it causes a websocket to be set up for ANY fetch + // whether we want to track it ot not. including ontologies loaed though the XSSproxy + }], [{ + key: "crossSiteProxy", + value: function crossSiteProxy(uri) { + if (Fetcher.crossSiteProxyTemplate) { + return Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); + } else { + return undefined; + } + } + }, { + key: "offlineOverride", + value: function offlineOverride(uri) { + // Map the URI to a localhost proxy if we are running on localhost + // This is used for working offline, e.g. on planes. + // Is the script itself is running in localhost, then access all + // data in a localhost mirror. + // Do not remove without checking with TimBL + var requestedURI = uri; + var UI; + if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) && UI.preferences && UI.preferences.get('offlineModeUsingLocalhost')) { + if (requestedURI.slice(0, 7) === 'http://' && requestedURI.slice(7, 17) !== 'localhost/') { + requestedURI = 'http://localhost/' + requestedURI.slice(7); + _log__WEBPACK_IMPORTED_MODULE_20__["default"].warn('Localhost kludge for offline use: actually getting <' + requestedURI + '>'); + } else { + // log.warn("Localhost kludge NOT USED <" + requestedURI + ">") + } + } else { + // log.warn("Localhost kludge OFF offline use: actually getting <" + + // requestedURI + ">") + } + return requestedURI; + } + }, { + key: "proxyIfNecessary", + value: function proxyIfNecessary(uri) { + var UI; + if (typeof window !== 'undefined' && window.panes && (UI = window.panes.UI) && UI.isExtension) { + return uri; + } // Extension does not need proxy -"use strict"; + if (typeof $SolidTestEnvironment !== 'undefined' && $SolidTestEnvironment.localSiteMap) { + // nested dictionaries of URI parts from origin down + var hostpath = uri.split('/').slice(2); // the bit after the // + var lookup = function lookup(parts, index) { + var z = index[parts.shift()]; + if (!z) { + return null; + } + if (typeof z === 'string') { + return z + parts.join('/'); + } + if (!parts) { + return null; + } + return lookup(parts, z); + }; + var y = lookup(hostpath, $SolidTestEnvironment.localSiteMap); + if (y) { + return y; + } + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.style = void 0; -/* - * BASED ON: - * IconicMultiSelect v0.7.0 - * Licence: MIT - * (c) 2021 Sidney Wimart. - * repo & configuration: https://github.com/sidneywm/iconic-multiselect - */ + // browser does 2014 on as https browser script not trusted + // If the web app origin is https: then the mixed content rules + // prevent it loading insecure http: stuff so we need proxy. + if (Fetcher.crossSiteProxyTemplate && typeof document !== 'undefined' && document.location && ('' + document.location).slice(0, 6) === 'https:' && + // origin is secure + uri.slice(0, 5) === 'http:') { + // requested data is not + return Fetcher.crossSiteProxyTemplate.replace('{uri}', encodeURIComponent(uri)); + } + return uri; + } -/** - * @version IconicMultiSelect v0.7.0 - * @licence MIT - */ -var style = { - multiselect__container: "\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n background-color: #fff;\n border-radius: 2px;\n -webkit-box-shadow: 0 1px 3px 0 #d1d1d2, 0 0 0 1px #d1d1d2;\n box-shadow: 0 1px 3px 0 #d1d1d2, 0 0 0 1px #d1d1d2;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n min-height: 36px;\n padding: 4px 8px 0 8px;\n position: relative;\n width: 354px;\n margin-bottom: 5px;\n font-size: 100%\n ", - /* - multiselect__container:after: ` - content: ''; - min-height:inherit; - font-size:0; - `, - multiselect__container > *: ` - color: #656565; - font-size: 14px; - `, - */ - multiselect__wrapper: "\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n height: 100%;\n width: 100%;\n ", - multiselect__clear_btn: "\n cursor: pointer;\n align-items: center;\n margin-bottom: 4px;\n margin-left: 4px;\n ", - multiselect__options: "\n background-color: #f6f6f6;\n border-radius: 2px;\n left: 0;\n max-height: 0;\n overflow: hidden;\n position: absolute;\n top: calc(100% + 3px);\n z-index: 9999;\n width: 100%;\n opacity: 0;\n transition: max-height 0.1s ease;\n ", - multiselect__options_visible: "\n background-color: #f6f6f6;\n border-radius: 2px;\n left: 0;\n max-height: 0;\n overflow: hidden;\n position: absolute;\n top: calc(100% + 3px);\n z-index: 9999;\n width: 100%;\n opacity: 0;\n transition: max-height 0.1s ease;\n max-height: 200px;\n -webkit-box-shadow: 0 1px 3px 0 #d1d1d2, 0 0 0 1px #d1d1d2;\n box-shadow: 0 1px 3px 0 #d1d1d2, 0 0 0 1px #d1d1d2;\n opacity: 1;\n transition: max-height 0.2s ease;\n ", - multiselect__options_ul: "\n list-style: none;\n margin: 0;\n padding: 2px 0;\n max-height: 200px;\n overflow: auto;\n ", - multiselect__options_ul_li: "\n cursor: pointer;\n padding: 4px 8px;\n ", - // multiselect__options ul li:hover: ` - multiselect__options_ul_li_hover: "\n background-color: #dedede;\n ", - /* - multiselect__options ul li *: ` - pointer-events: none; - `, - */ + /** + * Tests whether the uri's protocol is supported by the Fetcher. + * @param uri + */ + }, { + key: "unsupportedProtocol", + value: function unsupportedProtocol(uri) { + var pcol = _uri__WEBPACK_IMPORTED_MODULE_21__.protocol(uri); + return pcol === 'tel' || pcol === 'mailto' || pcol === 'urn'; + } - multiselect__options_ul_p_multiselect__options_no_results: "\n margin: 0;\n padding: 8px;\n text-align: center;\n ", - multiselect__options_ul_p_multiselect__options_no_data: "\n margin: 0;\n padding: 8px;\n text-align: center;\n ", - // multiselect__options ul li.multiselect__options--selected: ` - multiselect__options_ul_li_multiselect__options_selected: "\n background-color: #656565;\n color: #fff;\n ", - // multiselect__options ul li.multiselect__options--selected:hover: ` - multiselect__options_ul_li_multiselect__options_selected_hover: "\n background-color: #656565;\n ", - // multiselect__options ul li.arrow-selected: ` - multiselect__options_ul_li_arrow_selected: "\n border: 2px solid rgba(101, 101, 101, 0.5);\n ", - multiselect__selected: "\n background-color: #656565;\n border-radius: 2px;\n color: #fff;\n margin-bottom: 4px;\n margin-right: 4px;\n padding: 4px 8px;\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n -webkit-box-align: center;\n -ms-flex-align: center;\n align-items: center;\n ", - multiselect__selected_multiselect__remove_btn: "\n cursor: pointer;\n display: flex;\n margin-left: 6px;\n ", - multiselect__input: "\n border: none;\n -ms-flex-preferred-size: 40%;\n flex-basis: 40%;\n -webkit-box-flex: 1;\n -ms-flex-positive: 1;\n flex-grow: 1;\n height: 5px; \n margin-bottom: 4px;\n min-width: 40%;\n outline: none; \n " -}; -exports.style = style; -style.setStyle = function setStyle(ele, styleName) { - ele.style = style[styleName]; -}; -module.exports = style; -//# sourceMappingURL=style_multiSelect.js.map + /** Decide on credentials using old XXHR api or new fetch() one + * @param requestedURI + * @param options + */ + }, { + key: "setCredentials", + value: function setCredentials(requestedURI) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + // 2014 CORS problem: + // XMLHttpRequest cannot load http://www.w3.org/People/Berners-Lee/card. + // A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' + // header when the credentials flag is true. + // @ Many ontology files under http: and need CORS wildcard -> + // can't have credentials + if (options.credentials === undefined) { + // Caller using new fetch convention + if (options.withCredentials !== undefined) { + // XHR style is what Fetcher specified before + options.credentials = options.withCredentials ? 'include' : 'omit'; + } else { + options.credentials = 'include'; // default is to be logged on + } + } + } + }]); + return Fetcher; +}(); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Fetcher, "HANDLERS", void 0); +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Fetcher, "CONTENT_TYPE_BY_EXT", void 0); +// TODO: Document this +(0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])(Fetcher, "crossSiteProxyTemplate", void 0); + +Fetcher.HANDLERS = defaultHandlers; +Fetcher.CONTENT_TYPE_BY_EXT = CONTENT_TYPE_BY_EXT; /***/ }), -/***/ "./lib/table.js": -/*!**********************!*\ - !*** ./lib/table.js ***! - \**********************/ -/***/ ((__unused_webpack_module, exports, __webpack_require__) => { +/***/ "./node_modules/rdflib/esm/formula.js": +/*!********************************************!*\ + !*** ./node_modules/rdflib/esm/formula.js ***! + \********************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ Formula) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "./node_modules/@babel/runtime/helpers/esm/classCallCheck.js"); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "./node_modules/@babel/runtime/helpers/esm/createClass.js"); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/assertThisInitialized */ "./node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js"); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "./node_modules/@babel/runtime/helpers/esm/inherits.js"); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "./node_modules/@babel/runtime/helpers/esm/possibleConstructorReturn.js"); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "./node_modules/@babel/runtime/helpers/esm/getPrototypeOf.js"); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "./node_modules/@babel/runtime/helpers/esm/defineProperty.js"); +/* harmony import */ var _class_order__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./class-order */ "./node_modules/rdflib/esm/class-order.js"); +/* harmony import */ var _collection__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./collection */ "./node_modules/rdflib/esm/collection.js"); +/* harmony import */ var _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./factories/canonical-data-factory */ "./node_modules/rdflib/esm/factories/canonical-data-factory.js"); +/* harmony import */ var _log__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./log */ "./node_modules/rdflib/esm/log.js"); +/* harmony import */ var _namespace__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./namespace */ "./node_modules/rdflib/esm/namespace.js"); +/* harmony import */ var _node_internal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./node-internal */ "./node_modules/rdflib/esm/node-internal.js"); +/* harmony import */ var _serialize__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./serialize */ "./node_modules/rdflib/esm/serialize.js"); +/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./types */ "./node_modules/rdflib/esm/types.js"); +/* harmony import */ var _utils_terms__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./utils/terms */ "./node_modules/rdflib/esm/utils/terms.js"); +/* harmony import */ var _variable__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./variable */ "./node_modules/rdflib/esm/variable.js"); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./utils */ "./node_modules/rdflib/esm/utils.js"); +/* harmony import */ var _named_node__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./named-node */ "./node_modules/rdflib/esm/named-node.js"); -var _typeof = __webpack_require__(/*! @babel/runtime/helpers/typeof */ "./node_modules/@babel/runtime/helpers/typeof.js"); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.renderTableViewPane = renderTableViewPane; -var debug = _interopRequireWildcard(__webpack_require__(/*! ./debug */ "./lib/debug.js")); -var _iconBase = __webpack_require__(/*! ./iconBase */ "./lib/iconBase.js"); -var _solidLogic = __webpack_require__(/*! solid-logic */ "../solid-logic/lib/index.js"); -var log = _interopRequireWildcard(__webpack_require__(/*! ./log */ "./lib/log.js")); -var ns = _interopRequireWildcard(__webpack_require__(/*! ./ns */ "./lib/ns.js")); -var rdf = _interopRequireWildcard(__webpack_require__(/*! rdflib */ "../rdflib/esm/index.js")); -var utils = _interopRequireWildcard(__webpack_require__(/*! ./utils */ "./lib/utils/index.js")); -var widgets = _interopRequireWildcard(__webpack_require__(/*! ./widgets */ "./lib/widgets/index.js")); -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); } -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; } -// Table Widget: Format an array of RDF statements as an HTML table. -// -// This can operate in one of three modes: when the class of object is given -// or when the source document from whuch data is taken is given, -// or if a prepared query object is given. -// (In principle it could operate with neither class nor document -// given but typically -// there would be too much data.) -// When the tableClass is not given, it looks for common classes in the data, -// and gives the user the option. -// -// 2008 Written, Ilaria Liccardi as the tableViewPane.js -// 2014 Core table widget moved into common/table.js - timbl -// -// pull in first avoid cross-refs -var UI = { - icons: _iconBase.icons, - log: log, - ns: ns, - utils: utils, - widgets: widgets -}; -// UI.widgets.renderTableViewPane -function renderTableViewPane(doc, options) { - var sourceDocument = options.sourceDocument; - var tableClass = options.tableClass; - var givenQuery = options.query; - var RDFS_LITERAL = 'http://www.w3.org/2000/01/rdf-schema#Literal'; - var ns = UI.ns; - var kb = _solidLogic.store; - var rowsLookup = {}; // Persistent mapping of subject URI to dom TR - // Predicates that are never made into columns: - var FORBIDDEN_COLUMNS = { - 'http://www.w3.org/2002/07/owl#sameAs': true, - 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': true - }; +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; } } }; } +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); } +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; } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0,_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_5__["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0,_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_4__["default"])(this, result); }; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - // Number types defined in the XML schema: - var XSD_NUMBER_TYPES = { - 'http://www.w3.org/2001/XMLSchema#decimal': true, - 'http://www.w3.org/2001/XMLSchema#float': true, - 'http://www.w3.org/2001/XMLSchema#double': true, - 'http://www.w3.org/2001/XMLSchema#integer': true, - 'http://www.w3.org/2001/XMLSchema#nonNegativeInteger': true, - 'http://www.w3.org/2001/XMLSchema#positiveInteger': true, - 'http://www.w3.org/2001/XMLSchema#nonPositiveInteger': true, - 'http://www.w3.org/2001/XMLSchema#negativeInteger': true, - 'http://www.w3.org/2001/XMLSchema#long': true, - 'http://www.w3.org/2001/XMLSchema#int': true, - 'http://www.w3.org/2001/XMLSchema#short': true, - 'http://www.w3.org/2001/XMLSchema#byte': true, - 'http://www.w3.org/2001/XMLSchema#unsignedLong': true, - 'http://www.w3.org/2001/XMLSchema#unsignedInt': true, - 'http://www.w3.org/2001/XMLSchema#unsignedShort': true, - 'http://www.w3.org/2001/XMLSchema#unsignedByte': true - }; - var XSD_DATE_TYPES = { - 'http://www.w3.org/2001/XMLSchema#dateTime': true, - 'http://www.w3.org/2001/XMLSchema#date': true - }; - // Classes that indicate an image: - var IMAGE_TYPES = { - 'http://xmlns.com/foaf/0.1/Image': true, - 'http://purl.org/dc/terms/Image': true - }; - // Name of the column used as a "key" value to look up the row. - // This is necessary because in the normal view, the columns are - // all "optional" values, meaning that we will get a result set - // for every individual value that is found. The row key acts - // as an anchor that can be used to combine this information - // back into the same row. - var keyVariable = options.keyVariable || '?_row'; - var subjectIdCounter = 0; - var allType, types; - var typeSelectorDiv, addColumnDiv; - // The last SPARQL query used: - var lastQuery = null; - var mostCommonType = null; - var resultDiv = doc.createElement('div'); - resultDiv.className = 'tableViewPane'; - resultDiv.appendChild(generateControlBar()); // sets typeSelectorDiv - var tableDiv = doc.createElement('div'); - resultDiv.appendChild(tableDiv); - // Save a refresh function for use by caller - resultDiv.refresh = function () { - runQuery(table.query, table.logicalRows, table.columns, table); - // updateTable(givenQuery, mostCommonType) // This could be a lot more incremental and efficient - }; - // A specifically asked-for query - var table; - if (givenQuery) { - table = renderTableForQuery(givenQuery); - // lastQuery = givenQuery - tableDiv.appendChild(table); - } else { - // Find the most common type and select it by default - var s = calculateTable(); - allType = s[0]; - types = s[1]; - if (!tableClass) { - typeSelectorDiv.appendChild(generateTypeSelector(allType, types)); - } - mostCommonType = getMostCommonType(types); - if (mostCommonType) { - buildFilteredTable(mostCommonType); - } else { - buildFilteredTable(allType); - } - } - return resultDiv; - // ///////////////////////////////////////////////////////////////// - /* - function closeDialog (dialog) { - dialog.parentNode.removeChild(dialog) - } - function createActionButton (label, callback) { - var button = doc.createElement('input') - button.setAttribute('type', 'submit') - button.setAttribute('value', label) - button.addEventListener('click', callback, false) - return button - } - // @@ Tdo: put these buttonsback in, - // to allow user to see and edit and save the sparql query for the table they are looking at - // - function createSparqlWindow () { - var dialog = doc.createElement('div') - dialog.setAttribute('class', 'sparqlDialog') - var title = doc.createElement('h3') - title.appendChild(doc.createTextNode('Edit SPARQL query')) - var inputbox = doc.createElement('textarea') - inputbox.value = rdf.queryToSPARQL(lastQuery) - dialog.appendChild(title) - dialog.appendChild(inputbox) - dialog.appendChild(createActionButton('Query', function () { - var query = rdf.SPARQLToQuery(inputbox.value) - updateTable(query) - closeDialog(dialog) - })) - dialog.appendChild(createActionButton('Close', function () { - closeDialog(dialog) - })) - return dialog - } - function sparqlButtonPressed () { - var dialog = createSparqlWindow() - resultDiv.appendChild(dialog) - } - function generateSparqlButton () { - var image = doc.createElement('img') - image.setAttribute('class', 'sparqlButton') - image.setAttribute('src', UI.iconBase + 'icons/1pt5a.gif') - image.setAttribute('alt', 'Edit SPARQL query') - image.addEventListener('click', sparqlButtonPressed, false) - return image - } +/** + * A formula, or store of RDF statements + */ +var Formula = /*#__PURE__*/function (_Node) { + (0,_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__["default"])(Formula, _Node); + var _super = _createSuper(Formula); + /** + * Initializes this formula + * @constructor + * @param statements - Initial array of statements + * @param constraints - initial array of constraints + * @param initBindings - initial bindings used in Query + * @param optional - optional + * @param opts + * @param opts.rdfFactory - The rdf factory that should be used by the store */ - // Generate the control bar displayed at the top of the screen. - - function generateControlBar() { - var result = doc.createElement('table'); - result.setAttribute('class', 'toolbar'); - var tr = doc.createElement('tr'); - - /* @@ Add in later -- not debugged yet - var sparqlButtonDiv = doc.createElement("td") - sparqlButtonDiv.appendChild(generateSparqlButton()) - tr.appendChild(sparqlButtonDiv) - */ - typeSelectorDiv = doc.createElement('td'); - tr.appendChild(typeSelectorDiv); - addColumnDiv = doc.createElement('td'); - tr.appendChild(addColumnDiv); - result.appendChild(tr); - return result; - } - - // Add the SELECT details to the query being built. - - function addSelectToQuery(query, type) { - var selectedColumns = type.getColumns(); - for (var i = 0; i < selectedColumns.length; ++i) { - // TODO: autogenerate nicer names for variables - // variables have to be unambiguous - - var variable = kb.variable('_col' + i); - query.vars.push(variable); - selectedColumns[i].setVariable(variable); + function Formula() { + var _this; + var statements = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + var constraints = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; + var initBindings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; + var optional = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; + var opts = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + (0,_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__["default"])(this, Formula); + _this = _super.call(this, ''); + _this.statements = statements; + _this.constraints = constraints; + _this.initBindings = initBindings; + _this.optional = optional; + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "termType", _types__WEBPACK_IMPORTED_MODULE_7__.GraphTermType); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "classOrder", _class_order__WEBPACK_IMPORTED_MODULE_8__["default"].Graph); + /** + * The accompanying fetcher instance. + * + * Is set by the fetcher when initialized. + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "fetcher", void 0); + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "isVar", 0); + /** + * A namespace for the specified namespace's URI + * @param nsuri The URI for the namespace + */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "ns", _namespace__WEBPACK_IMPORTED_MODULE_9__["default"]); + /** The factory used to generate statements and terms */ + (0,_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__["default"])((0,_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_2__["default"])(_this), "rdfFactory", void 0); + _this.rdfFactory = opts && opts.rdfFactory || _factories_canonical_data_factory__WEBPACK_IMPORTED_MODULE_10__["default"]; + // Enable default factory methods on this while preserving factory context. + var _iterator = _createForOfIteratorHelper(_utils__WEBPACK_IMPORTED_MODULE_11__.appliedFactoryMethods), + _step; + try { + var _loop = function _loop() { + var factoryMethod = _step.value; + _this[factoryMethod] = function () { + var _this$rdfFactory; + return (_this$rdfFactory = _this.rdfFactory)[factoryMethod].apply(_this$rdfFactory, arguments); + }; + }; + for (_iterator.s(); !(_step = _iterator.n()).done;) { + _loop(); + } + } catch (err) { + _iterator.e(err); + } finally { + _iterator.f(); } + return _this; } - // Add WHERE details to the query being built. - - function addWhereToQuery(query, rowVar, type) { - var queryType = type.type; - if (!queryType) { - queryType = kb.variable('_any'); + /** Add a statement from its parts + * @param subject - the first part of the statement + * @param predicate - the second part of the statement + * @param object - the third part of the statement + * @param graph - the last part of the statement + */ + (0,_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__["default"])(Formula, [{ + key: "add", + value: function add(subject, predicate, object, graph) { + var _this2 = this; + if (arguments.length === 1) { + subject.forEach(function (st) { + return _this2.add(st.subject, st.predicate, st.object, st.graph); + }); + } + return this.statements.push(this.rdfFactory.quad(subject, predicate, object, graph)); } - // _row a type - query.pat.add(rowVar, UI.ns.rdf('type'), queryType); - } - - // Generate OPTIONAL column selectors. - - function addColumnsToQuery(query, rowVar, type) { - var selectedColumns = type.getColumns(); - for (var i = 0; i < selectedColumns.length; ++i) { - var column = selectedColumns[i]; - var formula = kb.formula(); - formula.add(rowVar, column.predicate, column.getVariable()); - query.pat.optional.push(formula); + /** Add a statment object + * @param {Statement} statement - An existing constructed statement to add + */ + }, { + key: "addStatement", + value: function addStatement(statement) { + return this.add(statement); } - } - - // Generate a query object from the currently-selected type - // object. - - function generateQuery(type) { - var query = new rdf.Query(); - var rowVar = kb.variable(keyVariable.slice(1)); // don't pass '?' - - addSelectToQuery(query, type); - addWhereToQuery(query, rowVar, type); - addColumnsToQuery(query, rowVar, type); - return query; - } - - // Build the contents of the tableDiv element, filtered according - // to the specified type. - - function buildFilteredTable(type) { - // Generate "add column" cell. - - clearElement(addColumnDiv); - addColumnDiv.appendChild(generateColumnAddDropdown(type)); - var query = generateQuery(type); - updateTable(query, type); - } - function updateTable(query, type) { - // Stop the previous query from doing any updates. - if (lastQuery) { - lastQuery.running = false; + /** + * Shortcut for adding blankNodes + * @param [id] + */ + }, { + key: "bnode", + value: function bnode(id) { + return this.rdfFactory.blankNode(id); } - // Render the HTML table. + /** + * Adds all the statements to this formula + * @param statements - A collection of statements + */ + }, { + key: "addAll", + value: function addAll(statements) { + var _this3 = this; + statements.forEach(function (quad) { + _this3.add(quad.subject, quad.predicate, quad.object, quad.graph); + }); + } - var htmlTable = renderTableForQuery(query, type); + /** Follow link from one node, using one wildcard, looking for one + * + * For example, any(me, knows, null, profile) - a person I know accoring to my profile . + * any(me, knows, null, null) - a person I know accoring to anything in store . + * any(null, knows, me, null) - a person who know me accoring to anything in store . + * + * @param s - A node to search for as subject, or if null, a wildcard + * @param p - A node to search for as predicate, or if null, a wildcard + * @param o - A node to search for as object, or if null, a wildcard + * @param g - A node to search for as graph, or if null, a wildcard + * @returns A node which match the wildcard position, or null + */ + }, { + key: "any", + value: function any(s, p, o, g) { + var st = this.anyStatementMatching(s, p, o, g); + if (st == null) { + return null; + } else if (s == null) { + return st.subject; + } else if (p == null) { + return st.predicate; + } else if (o == null) { + return st.object; + } + return null; + } - // Clear the tableDiv element, and replace with the new table. + /** + * Gets the value of a node that matches the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + }, { + key: "anyValue", + value: function anyValue(s, p, o, g) { + var y = this.any(s, p, o, g); + return y ? y.value : void 0; + } - clearElement(tableDiv); - tableDiv.appendChild(htmlTable); + /** + * Gets the first JavaScript object equivalent to a node based on the specified pattern + * @param s The subject + * @param p The predicate + * @param o The object + * @param g The graph that contains the statement + */ + }, { + key: "anyJS", + value: function anyJS(s, p, o, g) { + var y = this.any(s, p, o, g); + return y ? _node_internal__WEBPACK_IMPORTED_MODULE_12__["default"].toJS(y) : void 0; + } - // Save the query for the edit dialog. + /** + * Gets the first statement that matches the specified pattern + */ + }, { + key: "anyStatementMatching", + value: function anyStatementMatching(s, p, o, g) { + var x = this.statementsMatching(s, p, o, g, true); + if (!x || x.length === 0) { + return undefined; + } + return x[0]; + } - lastQuery = query; - } + /** + * Returns a unique index-safe identifier for the given term. + * + * Falls back to the rdflib hashString implementation if the given factory doesn't support id. + */ + }, { + key: "id", + value: function id(term) { + return this.rdfFactory.id(term); + } - // Remove all subelements of the specified element. + /** + * Search the Store + * This is really a teaching method as to do this properly you would use IndexedFormula + * + * @param s - A node to search for as subject, or if null, a wildcard + * @param p - A node to search for as predicate, or if null, a wildcard + * @param o - A node to search for as object, or if null, a wildcard + * @param g - A node to search for as graph, or if null, a wildcard + * @param justOne - flag - stop when found one rather than get all of them? + * @returns {Array} - An array of nodes which match the wildcard position + */ + }, { + key: "statementsMatching", + value: function statementsMatching(s, p, o, g, justOne) { + var sts = this.statements.filter(function (st) { + return (!s || s.equals(st.subject)) && (!p || p.equals(st.predicate)) && (!o || o.equals(st.object)) && (!g || g.equals(st.graph)); + }); + if (justOne) { + return sts.length === 0 ? [] : [sts[0]]; + } + return sts; + } - function clearElement(element) { - while (element.childNodes.length > 0) { - element.removeChild(element.childNodes[0]); + /** + * Finds the types in the list which have no *stored* subtypes + * These are a set of classes which provide by themselves complete + * information -- the other classes are redundant for those who + * know the class DAG. + * @param types A map of the types + */ + }, { + key: "bottomTypeURIs", + value: function bottomTypeURIs(types) { + var bots; + var bottom; + var elt; + var i; + var len; + var ref; + var subs; + var v; + bots = []; + for (var _k in types) { + if (!types.hasOwnProperty(_k)) continue; + v = types[_k]; + subs = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), this.rdfFactory.namedNode(_k)); + bottom = true; + i = 0; + for (len = subs.length; i < len; i++) { + elt = subs[i]; + ref = elt.uri; + if (ref in types) { + // the subclass is one we know + bottom = false; + break; + } + } + if (bottom) { + bots[_k] = v; + } + } + return bots; } - } - - // A SubjectType is created for each rdf:type discovered. - - function SubjectType(type) { - this.type = type; - this.columns = null; - this.allColumns = []; - this.useCount = 0; - - // Get a list of all columns used by this type. - - this.getAllColumns = function () { - return this.allColumns; - }; - - // Get a list of the current columns used by this type - // (subset of allColumns) - this.getColumns = function () { - // The first time through, get a list of all the columns - // and select only the six most popular columns. + /** Creates a new collection */ + }, { + key: "collection", + value: function collection() { + return new _collection__WEBPACK_IMPORTED_MODULE_13__["default"](); + } - if (!this.columns) { - var allColumns = this.getAllColumns(); - this.columns = allColumns.slice(0, 7); + /** Follow links from one node, using one wildcard. + * + * For example, each(me, knows, null, profile) - people I know accoring to my profile . + * each(me, knows, null, null) - people I know accoring to anything in store . + * each(null, knows, me, null) - people who know me accoring to anything in store . + * + * @param s - A node to search for as subject, or if null, a wildcard + * @param p - A node to search for as predicate, or if null, a wildcard + * @param o - A node to search for as object, or if null, a wildcard + * @param g - A node to search for as graph, or if null, a wildcard + * @returns {Array} - An array of nodes which match the wildcard position + */ + }, { + key: "each", + value: function each(s, p, o, g) { + var results = []; + var sts = this.statementsMatching(s, p, o, g, false); + if (s == null) { + for (var i = 0, len = sts.length; i < len; i++) { + results.push(sts[i].subject); + } + } else if (p == null) { + for (var l = 0, len1 = sts.length; l < len1; l++) { + results.push(sts[l].predicate); + } + } else if (o == null) { + for (var m = 0, len2 = sts.length; m < len2; m++) { + results.push(sts[m].object); + } + } else if (g == null) { + for (var _q = 0, len3 = sts.length; _q < len3; _q++) { + results.push(new _named_node__WEBPACK_IMPORTED_MODULE_14__["default"](sts[_q].graph.value)); + } } - return this.columns; - }; + return results; + } - // Get a list of unused columns + /** + * Test whether this formula is equals to {other} + * @param other - The other formula + */ + }, { + key: "equals", + value: function equals(other) { + if (!other) { + return false; + } + return this.hashString() === other.hashString(); + } - this.getUnusedColumns = function () { - var allColumns = this.getAllColumns(); - var columns = this.getColumns(); - var result = []; - for (var i = 0; i < allColumns.length; ++i) { - if (columns.indexOf(allColumns[i]) === -1) { - result.push(allColumns[i]); + /** + * For thisClass or any subclass, anything which has it is its type + * or is the object of something which has the type as its range, or subject + * of something which has the type as its domain + * We don't bother doing subproperty (yet?)as it doesn't seeem to be used + * much. + * Get all the Classes of which we can RDFS-infer the subject is a member + * @return a hash of URIs + */ + }, { + key: "findMembersNT", + value: function findMembersNT(thisClass) { + var len2; + var len4; + var m; + var members; + var pred; + var ref; + var ref1; + var ref2; + var ref3; + var ref4; + var ref5; + var seeds; + var st; + var u; + seeds = {}; + seeds[thisClass.toNT()] = true; + members = {}; + ref = this.transitiveClosure(seeds, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true); + for (var t in ref) { + if (!ref.hasOwnProperty(t)) continue; + ref1 = this.statementsMatching(void 0, this.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), this.fromNT(t)); + for (var i = 0, len = ref1.length; i < len; i++) { + st = ref1[i]; + members[st.subject.toNT()] = st; + } + ref2 = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain'), this.fromNT(t)); + for (var l = 0, len1 = ref2.length; l < len1; l++) { + pred = ref2[l]; + ref3 = this.statementsMatching(void 0, pred); + for (m = 0, len2 = ref3.length; m < len2; m++) { + st = ref3[m]; + members[st.subject.toNT()] = st; + } + } + ref4 = this.each(void 0, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range'), this.fromNT(t)); + for (var _q2 = 0, len3 = ref4.length; _q2 < len3; _q2++) { + pred = ref4[_q2]; + ref5 = this.statementsMatching(void 0, pred); + for (u = 0, len4 = ref5.length; u < len4; u++) { + st = ref5[u]; + members[st.object.toNT()] = st; + } } } - return result; - }; - this.addColumn = function (column) { - this.columns.push(column); - }; - this.removeColumn = function (column) { - this.columns = this.columns.filter(function (x) { - return x !== column; - }); - }; - this.getLabel = function () { - return utils.label(this.type); - }; - this.addUse = function () { - this.useCount += 1; - }; - } - - // Class representing a column in the table. - - function Column() { - this.useCount = 0; - - // Have we checked any values for this column yet? - - this.checkedAnyValues = false; - - // If the range is unknown, but we just get literals in this - // column, then we can generate a literal selector. - - this.possiblyLiteral = true; - - // If the range is unknown, but we just get literals and they - // match the regular expression for numbers, we can generate - // a number selector. - - this.possiblyNumber = true; + return members; + } - // We accumulate classes which things in the column must be a member of + /** + * For thisClass or any subclass, anything which has it is its type + * or is the object of something which has the type as its range, or subject + * of something which has the type as its domain + * We don't bother doing subproperty (yet?)as it doesn't seeem to be used + * much. + * Get all the Classes of which we can RDFS-infer the subject is a member + * @param subject - A named node + */ + }, { + key: "findMemberURIs", + value: function findMemberURIs(subject) { + return this.NTtoURI(this.findMembersNT(subject)); + } - this.constraints = []; + /** + * Get all the Classes of which we can RDFS-infer the subject is a superclass + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + */ + }, { + key: "findSubClassesNT", + value: function findSubClassesNT(subject) { + var types = {}; + types[subject.toNT()] = true; + return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), true); + } - // Check values as they are read. If we don't know what the - // range is, we might be able to infer that it is a literal - // if all of the values are literals. Similarly, we might - // be able to determine if the literal values are actually - // numbers (using regexps). + /** + * Get all the Classes of which we can RDFS-infer the subject is a subclass + * @param {RDFlibNamedNode} subject - The thing whose classes are to be found + * @returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + */ + }, { + key: "findSuperClassesNT", + value: function findSuperClassesNT(subject) { + var types = {}; + types[subject.toNT()] = true; + return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false); + } - this.checkValue = function (term) { - var termType = term.termType; - if (this.possiblyLiteral && termType !== 'Literal' && termType !== 'NamedNode') { - this.possiblyNumber = false; - this.possiblyLiteral = false; - } else if (this.possiblyNumber) { - if (termType !== 'Literal') { - this.possiblyNumber = false; + /** + * Get all the Classes of which we can RDFS-infer the subject is a member + * todo: This will loop is there is a class subclass loop (Sublass loops are + * not illegal) + * @param {RDFlibNamedNode} subject - The thing whose classes are to be found + * @returns a hash table where key is NT of type and value is statement why we think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + */ + }, { + key: "findTypesNT", + value: function findTypesNT(subject) { + var domain; + var range; + var rdftype; + var ref; + var ref1; + var ref2; + var ref3; + var st; + var types; + rdftype = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'; + types = []; + ref = this.statementsMatching(subject, void 0, void 0); + for (var i = 0, len = ref.length; i < len; i++) { + st = ref[i]; + if (st.predicate.uri === rdftype) { + types[st.object.toNT()] = st; } else { - var literalValue = term.value; - if (!literalValue.match(/^-?\d+(\.\d*)?$/)) { - this.possiblyNumber = false; + ref1 = this.each(st.predicate, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#domain')); + for (var l = 0, len1 = ref1.length; l < len1; l++) { + range = ref1[l]; + types[range.toNT()] = st; } } } - this.checkedAnyValues = true; - }; - this.getVariable = function () { - return this.variable; - }; - this.setVariable = function (variable) { - this.variable = variable; - }; - this.getKey = function () { - return this.variable.toString(); - }; - this.addUse = function () { - this.useCount += 1; - }; - this.getHints = function () { - if (options && options.hints && this.variable && options.hints[this.variable.toNT()]) { - return options.hints[this.variable.toNT()]; - } - return {}; - }; - this.getLabel = function () { - if (this.getHints().label) { - return this.getHints().label; - } - if (this.predicate) { - if (this.predicate.sameTerm(ns.rdf('type')) && this.superClass) { - return utils.label(this.superClass, true); // do initial cap - } - - return utils.label(this.predicate); - } else if (this.variable) { - return this.variable.toString(); - } else { - return 'unlabeled column?'; - } - }; - this.setPredicate = function (predicate, inverse, other) { - if (inverse) { - // variable is in the subject pos - this.inverse = predicate; - this.constraints = this.constraints.concat(kb.each(predicate, UI.ns.rdfs('domain'))); - if (predicate.sameTerm(ns.rdfs('subClassOf')) && other.termType === 'NamedNode') { - this.superClass = other; - this.alternatives = kb.each(undefined, ns.rdfs('subClassOf'), other); + ref2 = this.statementsMatching(void 0, void 0, subject); + for (var m = 0, len2 = ref2.length; m < len2; m++) { + st = ref2[m]; + ref3 = this.each(st.predicate, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#range')); + for (var _q3 = 0, len3 = ref3.length; _q3 < len3; _q3++) { + domain = ref3[_q3]; + types[domain.toNT()] = st; } - } else { - // variable is the object - this.predicate = predicate; - this.constraints = this.constraints.concat(kb.each(predicate, UI.ns.rdfs('range'))); - } - }; - this.getConstraints = function () { - return this.constraints; - }; - this.filterFunction = function () { - return true; - }; - this.sortKey = function () { - return this.getLabel().toLowerCase(); - }; - this.isImageColumn = function () { - for (var i = 0; i < this.constraints.length; i++) { - if (this.constraints[i].uri in IMAGE_TYPES) return true; } - return false; - }; - } + return this.transitiveClosure(types, this.rdfFactory.namedNode('http://www.w3.org/2000/01/rdf-schema#subClassOf'), false); + } - // Convert an object to an array. + /** + * Get all the Classes of which we can RDFS-infer the subject is a member + * todo: This will loop is there is a class subclass loop (Sublass loops are + * not illegal) + * Returns a hash table where key is NT of type and value is statement why we + * think so. + * Does NOT return terms, returns URI strings. + * We use NT representations in this version because they handle blank nodes. + * @param subject - A subject node + */ + }, { + key: "findTypeURIs", + value: function findTypeURIs(subject) { + return this.NTtoURI(this.findTypesNT(subject)); + } - function objectToArray(obj, filter) { - var result = []; - for (var property in obj) { - // @@@ have to guard against methods - var value = obj[property]; - if (!filter || filter(property, value)) { - result.push(value); + /** Trace statements which connect directly, or through bnodes + * + * @param subject - The node to start looking for statments + * @param doc - The document to be searched, or null to search all documents + * @returns an array of statements, duplicate statements are suppresssed. + */ + }, { + key: "connectedStatements", + value: function connectedStatements(subject, doc, excludePredicateURIs) { + excludePredicateURIs = excludePredicateURIs || []; + var todo = [subject]; + var done = {}; + var doneArcs = {}; + var result = []; + var self = this; + var follow = function follow(x) { + var queue = function queue(x) { + if (x.termType === 'BlankNode' && !done[x.value]) { + done[x.value] = true; + todo.push(x); + } + }; + var sts = self.statementsMatching(null, null, x, doc).concat(self.statementsMatching(x, null, null, doc)); + sts = sts.filter(function (st) { + if (excludePredicateURIs[st.predicate.value]) return false; + var hash = st.toNT(); + if (doneArcs[hash]) return false; + doneArcs[hash] = true; + return true; + }); + sts.forEach(function (st) { + queue(st.subject); + queue(st.object); + }); + result = result.concat(sts); + }; + while (todo.length) { + follow(todo.shift()); } + return result; } - return result; - } - - // Generate an